2 * \file InsetMathHull.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 #include "InsetMathArray.h"
14 #include "InsetMathChar.h"
15 #include "InsetMathColor.h"
17 #include "InsetMathDelim.h"
18 #include "MathExtern.h"
19 #include "MathFactory.h"
20 #include "InsetMathHull.h"
21 #include "MathStream.h"
22 #include "MathParser.h"
23 #include "InsetMathSpace.h"
24 #include "MathStream.h"
25 #include "MathSupport.h"
26 #include "InsetMathRef.h"
29 #include "buffer_funcs.h"
30 #include "BufferParams.h"
31 #include "BufferView.h"
32 #include "CutAndPaste.h"
33 #include "FuncStatus.h"
34 #include "LaTeXFeatures.h"
36 #include "DispatchResult.h"
37 #include "FuncRequest.h"
40 #include "OutputParams.h"
41 #include "ParIterator.h"
44 #include "TextPainter.h"
45 #include "TocBackend.h"
47 #include "insets/RenderPreview.h"
48 #include "insets/InsetLabel.h"
50 #include "graphics/PreviewImage.h"
51 #include "graphics/PreviewLoader.h"
53 #include "frontends/Painter.h"
55 #include "support/lassert.h"
56 #include "support/debug.h"
57 #include "support/gettext.h"
58 #include "support/lstrings.h"
63 using namespace lyx::support;
67 using cap::grabAndEraseSelection;
71 int getCols(HullType type)
88 // returns position of first relation operator in the array
89 // used for "intelligent splitting"
90 size_t firstRelOp(MathData const & ar)
92 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
94 return it - ar.begin();
99 char const * star(bool numbered)
101 return numbered ? "" : "*";
105 } // end anon namespace
108 HullType hullType(docstring const & s)
110 if (s == "none") return hullNone;
111 if (s == "simple") return hullSimple;
112 if (s == "equation") return hullEquation;
113 if (s == "eqnarray") return hullEqnArray;
114 if (s == "align") return hullAlign;
115 if (s == "alignat") return hullAlignAt;
116 if (s == "xalignat") return hullXAlignAt;
117 if (s == "xxalignat") return hullXXAlignAt;
118 if (s == "multline") return hullMultline;
119 if (s == "gather") return hullGather;
120 if (s == "flalign") return hullFlAlign;
121 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
126 docstring hullName(HullType type)
129 case hullNone: return from_ascii("none");
130 case hullSimple: return from_ascii("simple");
131 case hullEquation: return from_ascii("equation");
132 case hullEqnArray: return from_ascii("eqnarray");
133 case hullAlign: return from_ascii("align");
134 case hullAlignAt: return from_ascii("alignat");
135 case hullXAlignAt: return from_ascii("xalignat");
136 case hullXXAlignAt: return from_ascii("xxalignat");
137 case hullMultline: return from_ascii("multline");
138 case hullGather: return from_ascii("gather");
139 case hullFlAlign: return from_ascii("flalign");
141 lyxerr << "unknown hull type '" << type << "'" << endl;
142 return from_ascii("none");
146 static InsetLabel * dummy_pointer = 0;
148 InsetMathHull::InsetMathHull()
149 : InsetMathGrid(1, 1), type_(hullNone), nonum_(1, false),
150 label_(1, dummy_pointer), preview_(new RenderPreview(this))
152 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
153 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
154 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
155 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
161 InsetMathHull::InsetMathHull(HullType type)
162 : InsetMathGrid(getCols(type), 1), type_(type), nonum_(1, false),
163 label_(1, dummy_pointer), preview_(new RenderPreview(this))
170 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid()
176 InsetMathHull::~InsetMathHull()
178 for (size_t i = 0; i < label_.size(); ++i)
183 Inset * InsetMathHull::clone() const
185 return new InsetMathHull(*this);
189 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
193 InsetMathGrid::operator=(other);
195 nonum_ = other.nonum_;
196 for (size_t i = 0; i < label_.size(); ++i)
198 label_ = other.label_;
199 for (size_t i = 0; i != label_.size(); ++i) {
201 label_[i] = new InsetLabel(*label_[i]);
203 preview_.reset(new RenderPreview(*other.preview_, this));
209 void InsetMathHull::setBuffer(Buffer & buffer)
212 for (idx_type i = 0, n = nargs(); i != n; ++i) {
213 MathData & data = cell(i);
214 for (size_t j = 0; j != data.size(); ++j)
215 data[j].nucleus()->setBuffer(buffer);
218 for (size_t i = 0; i != label_.size(); ++i) {
220 label_[i]->setBuffer(buffer);
225 void InsetMathHull::updateLabels(ParIterator const & it)
228 //FIXME: buffer_ should be set at creation for this inset! Problem is
229 // This inset is created at too many places (see Parser::parse1() in
233 for (size_t i = 0; i != label_.size(); ++i) {
235 label_[i]->updateLabels(it);
240 void InsetMathHull::addToToc(DocIterator const & pit)
243 //FIXME: buffer_ should be set at creation for this inset! Problem is
244 // This inset is created at too many places (see Parser::parse1() in
249 Toc & toc = buffer().tocBackend().toc("equation");
251 for (row_type row = 0; row != nrows(); ++row) {
255 label_[row]->addToToc(pit);
256 toc.push_back(TocItem(pit, 0, nicelabel(row)));
261 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
267 return InsetMathNest::editXY(cur, x, y);
271 InsetMath::mode_type InsetMathHull::currentMode() const
273 if (type_ == hullNone)
274 return UNDECIDED_MODE;
275 // definitely math mode ...
280 bool InsetMathHull::idxFirst(Cursor & cur) const
288 bool InsetMathHull::idxLast(Cursor & cur) const
290 cur.idx() = nargs() - 1;
291 cur.pos() = cur.lastpos();
296 char InsetMathHull::defaultColAlign(col_type col)
298 if (type_ == hullEqnArray)
300 if (type_ == hullGather)
302 if (type_ >= hullAlign)
303 return "rl"[col & 1];
308 int InsetMathHull::defaultColSpace(col_type col)
310 if (type_ == hullAlign || type_ == hullAlignAt)
312 if (type_ == hullXAlignAt)
313 return (col & 1) ? 20 : 0;
314 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
315 return (col & 1) ? 40 : 0;
320 docstring InsetMathHull::standardFont() const
322 return from_ascii(type_ == hullNone ? "lyxnochange" : "mathnormal");
326 bool InsetMathHull::previewState(BufferView * bv) const
328 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
329 graphics::PreviewImage const * pimage =
330 preview_->getPreviewImage(bv->buffer());
331 return pimage && pimage->image();
337 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
339 if (previewState(mi.base.bv)) {
340 preview_->metrics(mi, dim);
341 // insert a one pixel gap in front of the formula
344 dim.des += displayMargin();
345 // Cache the inset dimension.
346 setDimCache(mi, dim);
350 FontSetChanger dummy1(mi.base, standardFont());
351 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
353 // let the cells adjust themselves
354 InsetMathGrid::metrics(mi, dim);
357 dim.asc += displayMargin();
358 dim.des += displayMargin();
361 if (numberedType()) {
362 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
364 for (row_type row = 0; row < nrows(); ++row)
365 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
371 // make it at least as high as the current font
374 math_font_max_dim(mi.base.font, asc, des);
375 dim.asc = max(dim.asc, asc);
376 dim.des = max(dim.des, des);
377 // Cache the inset dimension.
378 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
379 setDimCache(mi, dim);
383 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
385 Dimension const dim = dimension(*pi.base.bv);
386 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
387 dim.asc + dim.des - 1, pi.backgroundColor(this));
391 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
393 use_preview_ = previewState(pi.base.bv);
396 // one pixel gap in front
397 preview_->draw(pi, x + 1, y);
398 setPosCache(pi, x, y);
402 FontSetChanger dummy1(pi.base, standardFont());
403 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
404 InsetMathGrid::draw(pi, x + 1, y);
406 if (numberedType()) {
407 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
408 for (row_type row = 0; row < nrows(); ++row) {
409 int const yy = y + rowinfo_[row].offset_;
410 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
411 docstring const nl = nicelabel(row);
415 setPosCache(pi, x, y);
419 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
422 InsetMathGrid::metricsT(mi, dim);
425 WriteStream wi(os, false, true, false);
427 dim.wid = os.str().size();
434 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
437 InsetMathGrid::drawT(pain, x, y);
440 WriteStream wi(os, false, true, false);
442 pain.draw(x, y, os.str().c_str());
447 static docstring latexString(InsetMathHull const & inset)
450 // This has to be static, because a preview snippet containing math
451 // in text mode (such as $\text{$\phi$}$) gets processed twice. The
452 // first time as a whole, and the second time only the inner math.
453 // In this last case inset.buffer() would be invalid.
454 // FIXME: preview snippets should only be processed once, such that
455 // both static qualifier and isBufferValid() check can be dropped.
456 static Encoding const * encoding = 0;
457 if (inset.isBufferValid())
458 encoding = &(inset.buffer().params().encoding());
459 WriteStream wi(ls, false, true, false, encoding);
465 void InsetMathHull::initUnicodeMath() const
467 // Trigger classification of the unicode symbols in this inset
468 docstring const dummy = latexString(*this);
472 void InsetMathHull::addPreview(graphics::PreviewLoader & ploader) const
474 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
475 docstring const snippet = latexString(*this);
476 preview_->addPreview(snippet, ploader);
481 bool InsetMathHull::notifyCursorLeaves(Cursor const & /*old*/, Cursor & cur)
483 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
484 Buffer const & buffer = cur.buffer();
485 docstring const snippet = latexString(*this);
486 preview_->addPreview(snippet, buffer);
487 preview_->startLoading(buffer);
488 cur.updateFlags(Update::Force);
494 docstring InsetMathHull::label(row_type row) const
496 LASSERT(row < nrows(), /**/);
497 if (InsetLabel * il = label_[row])
498 return il->screenLabel();
503 void InsetMathHull::label(row_type row, docstring const & label)
505 //lyxerr << "setting label '" << label << "' for row " << row << endl;
509 label_[row] = dummy_pointer;
510 // We need an update of the Buffer reference cache.
511 // This is achieved by updateLabels().
512 lyx::updateLabels(buffer());
514 label_[row]->updateCommand(label);
517 InsetCommandParams p(LABEL_CODE);
519 label_[row] = new InsetLabel(p);
521 label_[row]->setBuffer(buffer());
525 void InsetMathHull::numbered(row_type row, bool num)
528 if (nonum_[row] && label_[row]) {
531 // We need an update of the Buffer reference cache.
532 // This is achieved by updateLabels().
533 lyx::updateLabels(buffer());
538 bool InsetMathHull::numbered(row_type row) const
544 bool InsetMathHull::ams() const
547 type_ == hullAlign ||
548 type_ == hullFlAlign ||
549 type_ == hullMultline ||
550 type_ == hullGather ||
551 type_ == hullAlignAt ||
552 type_ == hullXAlignAt ||
553 type_ == hullXXAlignAt;
557 Inset::DisplayType InsetMathHull::display() const
559 return (type_ != hullSimple && type_ != hullNone) ? AlignCenter : Inline;
563 bool InsetMathHull::numberedType() const
565 if (type_ == hullNone)
567 if (type_ == hullSimple)
569 if (type_ == hullXXAlignAt)
571 for (row_type row = 0; row < nrows(); ++row)
578 void InsetMathHull::validate(LaTeXFeatures & features) const
581 features.require("amsmath");
583 // Validation is necessary only if not using AMS math.
584 // To be safe, we will always run mathedvalidate.
585 //if (features.amsstyle)
588 //features.binom = true;
590 InsetMathGrid::validate(features);
594 void InsetMathHull::header_write(WriteStream & os) const
596 bool n = numberedType();
610 os << "\\begin{equation" << star(n) << "}\n";
620 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
625 os << "\\begin{" << hullName(type_) << star(n) << '}'
626 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
630 os << "\\begin{" << hullName(type_) << '}'
631 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
635 os << "\\begin{unknown" << star(n) << '}';
641 void InsetMathHull::footer_write(WriteStream & os) const
643 bool n = numberedType();
656 os << "\\end{equation" << star(n) << "}\n";
668 os << "\\end{" << hullName(type_) << star(n) << "}\n";
672 os << "\\end{" << hullName(type_) << "}\n";
676 os << "\\end{unknown" << star(n) << '}';
682 bool InsetMathHull::rowChangeOK() const
685 type_ == hullEqnArray || type_ == hullAlign ||
686 type_ == hullFlAlign || type_ == hullAlignAt ||
687 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
688 type_ == hullGather || type_ == hullMultline;
692 bool InsetMathHull::colChangeOK() const
695 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
696 type_ == hullXAlignAt || type_ == hullXXAlignAt;
700 void InsetMathHull::addRow(row_type row)
705 bool numbered = numberedType();
707 if (type_ == hullMultline) {
708 if (row + 1 == nrows()) {
715 nonum_.insert(nonum_.begin() + row + 1, !numbered);
716 label_.insert(label_.begin() + row + 1, dummy_pointer);
719 InsetMathGrid::addRow(row);
723 void InsetMathHull::swapRow(row_type row)
727 if (row + 1 == nrows())
729 // gcc implements the standard std::vector<bool> which is *not* a container:
730 // http://www.gotw.ca/publications/N1185.pdf
731 // As a results, it doesn't like this:
732 // swap(nonum_[row], nonum_[row + 1]);
733 // so we do it manually:
734 bool const b = nonum_[row];
735 nonum_[row] = nonum_[row + 1];
737 swap(label_[row], label_[row + 1]);
738 InsetMathGrid::swapRow(row);
742 void InsetMathHull::delRow(row_type row)
744 if (nrows() <= 1 || !rowChangeOK())
746 if (row + 1 == nrows() && type_ == hullMultline) {
747 bool const b = nonum_[row - 1];
748 nonum_[row - 1] = nonum_[row];
750 swap(label_[row - 1], label_[row]);
751 InsetMathGrid::delRow(row);
754 InsetMathGrid::delRow(row);
755 // The last dummy row has no number info nor a label.
756 // Test nrows() + 1 because we have already erased the row.
757 if (row == nrows() + 1)
759 nonum_.erase(nonum_.begin() + row);
761 label_.erase(label_.begin() + row);
765 void InsetMathHull::addCol(col_type col)
769 InsetMathGrid::addCol(col);
773 void InsetMathHull::delCol(col_type col)
775 if (ncols() <= 1 || !colChangeOK())
777 InsetMathGrid::delCol(col);
781 docstring InsetMathHull::nicelabel(row_type row) const
786 return from_ascii("(#)");
787 return '(' + label_[row]->screenLabel() + from_ascii(", #)");
791 void InsetMathHull::glueall()
794 for (idx_type i = 0; i < nargs(); ++i)
796 *this = InsetMathHull(hullSimple);
802 void InsetMathHull::splitTo2Cols()
804 LASSERT(ncols() == 1, /**/);
805 InsetMathGrid::addCol(1);
806 for (row_type row = 0; row < nrows(); ++row) {
807 idx_type const i = 2 * row;
808 pos_type pos = firstRelOp(cell(i));
809 cell(i + 1) = MathData(cell(i).begin() + pos, cell(i).end());
810 cell(i).erase(pos, cell(i).size());
815 void InsetMathHull::splitTo3Cols()
817 LASSERT(ncols() < 3, /**/);
820 InsetMathGrid::addCol(2);
821 for (row_type row = 0; row < nrows(); ++row) {
822 idx_type const i = 3 * row + 1;
823 if (cell(i).size()) {
824 cell(i + 1) = MathData(cell(i).begin() + 1, cell(i).end());
825 cell(i).erase(1, cell(i).size());
831 void InsetMathHull::changeCols(col_type cols)
835 else if (ncols() < cols) {
841 while (ncols() < cols)
842 InsetMathGrid::addCol(ncols());
848 for (row_type row = 0; row < nrows(); ++row) {
849 idx_type const i = row * ncols();
850 for (col_type col = cols; col < ncols(); ++col) {
851 cell(i + cols - 1).append(cell(i + col));
855 while (ncols() > cols) {
856 InsetMathGrid::delCol(ncols() - 1);
861 HullType InsetMathHull::getType() const
867 void InsetMathHull::setType(HullType type)
874 void InsetMathHull::mutate(HullType newtype)
876 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
878 // we try to move along the chain
879 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
881 // +-------------------------------------+
882 // we use eqnarray as intermediate type for mutations that are not
883 // directly supported because it handles labels and numbering for
886 if (newtype == type_) {
890 else if (newtype < hullNone) {
895 else if (type_ == hullNone) {
901 else if (type_ == hullSimple) {
902 if (newtype == hullNone) {
906 setType(hullEquation);
912 else if (type_ == hullEquation) {
913 if (newtype < type_) {
917 } else if (newtype == hullEqnArray) {
918 // split it "nicely" on the first relop
920 setType(hullEqnArray);
921 } else if (newtype == hullMultline || newtype == hullGather) {
931 else if (type_ == hullEqnArray) {
932 if (newtype < type_) {
933 // set correct (no)numbering
935 for (row_type row = 0; row < nrows(); ++row) {
942 // set first non-empty label
943 for (row_type row = 0; row < nrows(); ++row) {
945 label_[0] = label_[row];
952 } else { // align & Co.
959 else if (type_ == hullAlign || type_ == hullAlignAt ||
960 type_ == hullXAlignAt || type_ == hullFlAlign) {
961 if (newtype < hullAlign) {
963 setType(hullEqnArray);
965 } else if (newtype == hullGather || newtype == hullMultline) {
968 } else if (newtype == hullXXAlignAt) {
969 for (row_type row = 0; row < nrows(); ++row)
970 numbered(row, false);
977 else if (type_ == hullXXAlignAt) {
978 for (row_type row = 0; row < nrows(); ++row)
979 numbered(row, false);
980 if (newtype < hullAlign) {
982 setType(hullEqnArray);
984 } else if (newtype == hullGather || newtype == hullMultline) {
992 else if (type_ == hullMultline || type_ == hullGather) {
993 if (newtype == hullGather || newtype == hullMultline)
995 else if (newtype == hullAlign || newtype == hullFlAlign ||
996 newtype == hullAlignAt || newtype == hullXAlignAt) {
999 } else if (newtype == hullXXAlignAt) {
1001 for (row_type row = 0; row < nrows(); ++row)
1002 numbered(row, false);
1006 setType(hullEqnArray);
1012 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1013 << "' to '" << to_utf8(hullName(newtype))
1014 << "' not implemented" << endl;
1019 docstring InsetMathHull::eolString(row_type row, bool emptyline, bool fragile) const
1022 if (numberedType()) {
1023 if (label_[row] && !nonum_[row])
1025 + escape(label_[row]->getParam("name"))
1027 if (nonum_[row] && (type_ != hullMultline))
1028 res += "\\nonumber ";
1030 return res + InsetMathGrid::eolString(row, emptyline, fragile);
1034 void InsetMathHull::write(WriteStream & os) const
1036 ModeSpecifier specifier(os, MATH_MODE);
1038 InsetMathGrid::write(os);
1043 void InsetMathHull::normalize(NormalStream & os) const
1045 os << "[formula " << hullName(type_) << ' ';
1046 InsetMathGrid::normalize(os);
1051 void InsetMathHull::mathmlize(MathStream & os) const
1053 InsetMathGrid::mathmlize(os);
1057 void InsetMathHull::infoize(odocstream & os) const
1059 os << "Type: " << hullName(type_);
1063 void InsetMathHull::check() const
1065 LASSERT(nonum_.size() == nrows(), /**/);
1066 LASSERT(label_.size() == nrows(), /**/);
1070 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1074 idocstringstream iss(func.argument());
1075 iss >> dlang >> extra;
1077 extra = from_ascii("noextra");
1078 string const lang = to_ascii(dlang);
1080 // FIXME: temporarily disabled
1081 //if (cur.selection()) {
1084 // lyxerr << "use selection: " << ar << endl;
1085 // insert(pipeThroughExtern(lang, extra, ar));
1090 eq.push_back(MathAtom(new InsetMathChar('=')));
1092 // go to first item in line
1093 cur.idx() -= cur.idx() % ncols();
1096 if (getType() == hullSimple) {
1097 size_type pos = cur.cell().find_last(eq);
1099 if (cur.inMathed() && cur.selection()) {
1100 asArray(grabAndEraseSelection(cur), ar);
1101 } else if (pos == cur.cell().size()) {
1103 lyxerr << "use whole cell: " << ar << endl;
1105 ar = MathData(cur.cell().begin() + pos + 1, cur.cell().end());
1106 lyxerr << "use partial cell form pos: " << pos << endl;
1108 cur.cell().append(eq);
1109 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1110 cur.pos() = cur.lastpos();
1114 if (getType() == hullEquation) {
1115 lyxerr << "use equation inset" << endl;
1116 mutate(hullEqnArray);
1117 MathData & ar = cur.cell();
1118 lyxerr << "use cell: " << ar << endl;
1122 cur.cell() = pipeThroughExtern(lang, extra, ar);
1123 // move to end of line
1124 cur.pos() = cur.lastpos();
1129 lyxerr << "use eqnarray" << endl;
1130 cur.idx() += 2 - cur.idx() % ncols();
1132 MathData ar = cur.cell();
1133 lyxerr << "use cell: " << ar << endl;
1134 // FIXME: temporarily disabled
1140 cur.cell() = pipeThroughExtern(lang, extra, ar);
1141 cur.pos() = cur.lastpos();
1146 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1148 //lyxerr << "action: " << cmd.action << endl;
1149 switch (cmd.action) {
1151 case LFUN_FINISHED_BACKWARD:
1152 case LFUN_FINISHED_FORWARD:
1153 case LFUN_FINISHED_RIGHT:
1154 case LFUN_FINISHED_LEFT:
1155 //lyxerr << "action: " << cmd.action << endl;
1156 InsetMathGrid::doDispatch(cur, cmd);
1160 case LFUN_BREAK_PARAGRAPH:
1161 // just swallow this
1164 case LFUN_NEWLINE_INSERT:
1165 // some magic for the common case
1166 if (type_ == hullSimple || type_ == hullEquation) {
1167 cur.recordUndoInset();
1169 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1170 mutate(align ? hullAlign : hullEqnArray);
1171 cur.idx() = nrows() * ncols() - 1;
1172 cur.pos() = cur.lastpos();
1174 InsetMathGrid::doDispatch(cur, cmd);
1177 case LFUN_MATH_NUMBER_TOGGLE: {
1178 //lyxerr << "toggling all numbers" << endl;
1179 cur.recordUndoInset();
1180 bool old = numberedType();
1181 if (type_ == hullMultline)
1182 numbered(nrows() - 1, !old);
1184 for (row_type row = 0; row < nrows(); ++row)
1185 numbered(row, !old);
1187 cur.message(old ? _("No number") : _("Number"));
1191 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1192 cur.recordUndoInset();
1193 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1194 bool old = numbered(r);
1195 cur.message(old ? _("No number") : _("Number"));
1200 case LFUN_LABEL_INSERT: {
1201 cur.recordUndoInset();
1202 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1203 docstring old_label = label(r);
1204 docstring const default_label = from_ascii(
1205 (lyxrc.label_init_length >= 0) ? "eq:" : "");
1206 if (old_label.empty())
1207 old_label = default_label;
1209 InsetCommandParams p(LABEL_CODE);
1210 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1211 string const data = InsetCommand::params2string("label", p);
1213 if (cmd.argument().empty())
1214 cur.bv().showDialog("label", data);
1216 FuncRequest fr(LFUN_INSET_INSERT, data);
1222 case LFUN_WORD_DELETE_FORWARD:
1223 case LFUN_CHAR_DELETE_FORWARD:
1224 if (col(cur.idx()) + 1 == ncols()
1225 && cur.pos() == cur.lastpos()) {
1226 if (!label(row(cur.idx())).empty()) {
1227 cur.recordUndoInset();
1228 label(row(cur.idx()), docstring());
1229 } else if (numbered(row(cur.idx()))) {
1230 cur.recordUndoInset();
1231 numbered(row(cur.idx()), false);
1233 InsetMathGrid::doDispatch(cur, cmd);
1237 InsetMathGrid::doDispatch(cur, cmd);
1242 case LFUN_INSET_INSERT: {
1243 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1244 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1245 string const name = cmd.getArg(0);
1246 if (name == "label") {
1247 InsetCommandParams p(LABEL_CODE);
1248 InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1249 docstring str = p["name"];
1250 cur.recordUndoInset();
1251 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1255 docstring old = label(r);
1258 // The label will take care of the reference update.
1262 // Newly created inset so initialize it.
1263 label_[r]->initView();
1268 InsetMathGrid::doDispatch(cur, cmd);
1272 case LFUN_MATH_EXTERN:
1273 cur.recordUndoInset();
1277 case LFUN_MATH_MUTATE: {
1278 cur.recordUndoInset();
1279 row_type row = cur.row();
1280 col_type col = cur.col();
1281 mutate(hullType(cmd.argument()));
1282 cur.idx() = row * ncols() + col;
1283 if (cur.idx() > cur.lastidx()) {
1284 cur.idx() = cur.lastidx();
1285 cur.pos() = cur.lastpos();
1287 if (cur.pos() > cur.lastpos())
1288 cur.pos() = cur.lastpos();
1290 // FIXME: find some more clever handling of the selection,
1291 // i.e. preserve it.
1292 cur.clearSelection();
1293 //cur.dispatched(FINISHED);
1297 case LFUN_MATH_DISPLAY: {
1298 cur.recordUndoInset();
1299 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1301 cur.pos() = cur.lastpos();
1302 //cur.dispatched(FINISHED);
1307 InsetMathGrid::doDispatch(cur, cmd);
1313 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1314 FuncStatus & status) const
1316 switch (cmd.action) {
1317 case LFUN_FINISHED_BACKWARD:
1318 case LFUN_FINISHED_FORWARD:
1319 case LFUN_FINISHED_RIGHT:
1320 case LFUN_FINISHED_LEFT:
1323 case LFUN_NEWLINE_INSERT:
1324 case LFUN_MATH_EXTERN:
1325 case LFUN_MATH_MUTATE:
1326 case LFUN_MATH_DISPLAY:
1328 status.setEnabled(true);
1330 case LFUN_MATH_NUMBER_TOGGLE:
1331 // FIXME: what is the right test, this or the one of
1333 status.setEnabled(display());
1334 status.setOnOff(numberedType());
1336 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1337 // FIXME: what is the right test, this or the one of
1339 bool const enable = (type_ == hullMultline) ?
1340 (nrows() - 1 == cur.row()) : display();
1341 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1342 status.setEnabled(enable);
1343 status.setOnOff(numbered(r));
1346 case LFUN_LABEL_INSERT:
1347 status.setEnabled(type_ != hullSimple);
1349 case LFUN_INSET_INSERT:
1350 if (cmd.getArg(0) == "label") {
1351 status.setEnabled(type_ != hullSimple);
1354 return InsetMathGrid::getStatus(cur, cmd, status);
1355 case LFUN_TABULAR_FEATURE: {
1356 istringstream is(to_utf8(cmd.argument()));
1360 && (s == "append-row"
1361 || s == "delete-row"
1362 || s == "copy-row")) {
1363 status.message(bformat(
1364 from_utf8(N_("Can't change number of rows in '%1$s'")),
1366 status.setEnabled(false);
1370 && (s == "append-column"
1371 || s == "delete-column"
1372 || s == "copy-column")) {
1373 status.message(bformat(
1374 from_utf8(N_("Can't change number of columns in '%1$s'")),
1376 status.setEnabled(false);
1379 if ((type_ == hullSimple
1380 || type_ == hullEquation
1381 || type_ == hullNone) &&
1382 (s == "add-hline-above" || s == "add-hline-below")) {
1383 status.message(bformat(
1384 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1386 status.setEnabled(false);
1389 if (s == "add-vline-left" || s == "add-vline-right") {
1390 status.message(bformat(
1391 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1393 status.setEnabled(false);
1396 if (s == "valign-top" || s == "valign-middle"
1397 || s == "valign-bottom" || s == "align-left"
1398 || s == "align-center" || s == "align-right") {
1399 status.setEnabled(false);
1402 return InsetMathGrid::getStatus(cur, cmd, status);
1405 return InsetMathGrid::getStatus(cur, cmd, status);
1408 // This cannot really happen, but inserted to shut-up gcc
1409 return InsetMathGrid::getStatus(cur, cmd, status);
1413 /////////////////////////////////////////////////////////////////////
1417 // simply scrap this function if you want
1418 void InsetMathHull::mutateToText()
1421 // translate to latex
1423 latex(os, false, false);
1424 string str = os.str();
1427 Text * lt = view_->cursor().innerText();
1428 string::const_iterator cit = str.begin();
1429 string::const_iterator end = str.end();
1430 for (; cit != end; ++cit)
1431 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1434 //dispatch(LFUN_ESCAPE);
1439 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1440 docstring const & font)
1442 // this whole function is a hack and won't work for incremental font
1445 if (cur.inset().asInsetMath()->name() == font)
1446 cur.handleFont(to_utf8(font));
1448 cur.handleNest(createInsetMath(font));
1454 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1459 font.fromString(to_utf8(arg), b);
1460 if (font.fontInfo().color() != Color_inherit) {
1461 MathAtom at = MathAtom(new InsetMathColor(true, font.fontInfo().color()));
1462 cur.handleNest(at, 0);
1467 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1470 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1471 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1472 enter_front ? idxFirst(cur) : idxLast(cur);
1473 // The inset formula dimension is not necessarily the same as the
1474 // one of the instant preview image, so we have to indicate to the
1475 // BufferView that a metrics update is needed.
1476 cur.updateFlags(Update::Force);
1480 docstring InsetMathHull::editMessage() const
1482 return _("Math editor mode");
1486 void InsetMathHull::revealCodes(Cursor & cur) const
1488 if (!cur.inMathed())
1490 odocstringstream os;
1492 cur.message(os.str());
1494 // write something to the minibuffer
1495 // translate to latex
1499 string str = os.str();
1501 string::size_type pos = 0;
1503 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1506 else if (*it == '\0') {
1508 pos = it - str.begin();
1514 res = res.substr(pos - 30);
1515 if (res.size() > 60)
1516 res = res.substr(0, 60);
1522 InsetCode InsetMathHull::lyxCode() const
1528 /////////////////////////////////////////////////////////////////////
1532 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1535 // FIXME: completely broken
1536 static InsetMathHull * lastformula = 0;
1537 static CursorBase current = DocIterator(ibegin(nucleus()));
1539 static string laststr;
1541 if (lastformula != this || laststr != str) {
1542 //lyxerr << "reset lastformula to " << this << endl;
1545 current = ibegin(nucleus());
1547 mathed_parse_cell(ar, str);
1551 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1553 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1554 CursorSlice & top = it.back();
1555 MathData const & a = top.asInsetMath()->cell(top.idx_);
1556 if (a.matchpart(ar, top.pos_)) {
1557 bv->cursor().setSelection(it, ar.size());
1559 top.pos_ += ar.size();
1565 //lyxerr << "not found!" << endl;
1572 void InsetMathHull::write(ostream & os) const
1574 odocstringstream oss;
1575 WriteStream wi(oss, false, false, false);
1578 os << to_utf8(oss.str());
1582 void InsetMathHull::read(Lexer & lex)
1585 mathed_parse_normal(at, lex);
1586 operator=(*at->asHullInset());
1590 bool InsetMathHull::readQuiet(Lexer & lex)
1593 bool result = mathed_parse_normal(at, lex, Parse::QUIET);
1594 operator=(*at->asHullInset());
1599 int InsetMathHull::plaintext(odocstream & os, OutputParams const & runparams) const
1601 if (0 && display()) {
1605 TextPainter tpain(dim.width(), dim.height());
1606 drawT(tpain, 0, dim.ascent());
1608 // reset metrics cache to "real" values
1610 return tpain.textheight();
1612 odocstringstream oss;
1613 WriteStream wi(oss, false, true, false, runparams.encoding);
1616 docstring const str = oss.str();
1623 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1628 if (getType() == hullSimple)
1629 name = from_ascii("inlineequation");
1631 name = from_ascii("informalequation");
1633 docstring bname = name;
1634 if (!label(0).empty())
1635 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1637 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1639 odocstringstream ls;
1640 if (runparams.flavor == OutputParams::XML) {
1641 ms << MTag("alt role='tex' ");
1642 // Workaround for db2latex: db2latex always includes equations with
1643 // \ensuremath{} or \begin{display}\end{display}
1644 // so we strip LyX' math environment
1645 WriteStream wi(ls, false, false, false, runparams.encoding);
1646 InsetMathGrid::write(wi);
1647 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1652 InsetMathGrid::mathmlize(ms);
1655 ms << MTag("alt role='tex'");
1656 res = latex(ls, runparams);
1657 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1661 ms << from_ascii("<graphic fileref=\"eqn/");
1662 if (!label(0).empty())
1663 ms << sgml::cleanID(buffer(), runparams, label(0));
1665 ms << sgml::uniqueID(from_ascii("anon"));
1667 if (runparams.flavor == OutputParams::XML)
1668 ms << from_ascii("\"/>");
1670 ms << from_ascii("\">");
1672 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1674 return ms.line() + res;
1678 void InsetMathHull::textString(odocstream & os) const
1680 plaintext(os, OutputParams(0));
1684 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1686 return from_ascii("context-math");