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 if (s == "regexp") return hullRegexp;
122 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
127 docstring hullName(HullType type)
130 case hullNone: return from_ascii("none");
131 case hullSimple: return from_ascii("simple");
132 case hullEquation: return from_ascii("equation");
133 case hullEqnArray: return from_ascii("eqnarray");
134 case hullAlign: return from_ascii("align");
135 case hullAlignAt: return from_ascii("alignat");
136 case hullXAlignAt: return from_ascii("xalignat");
137 case hullXXAlignAt: return from_ascii("xxalignat");
138 case hullMultline: return from_ascii("multline");
139 case hullGather: return from_ascii("gather");
140 case hullFlAlign: return from_ascii("flalign");
141 case hullRegexp: return from_ascii("regexp");
143 lyxerr << "unknown hull type '" << type << "'" << endl;
144 return from_ascii("none");
148 static InsetLabel * dummy_pointer = 0;
150 InsetMathHull::InsetMathHull()
151 : InsetMathGrid(1, 1), type_(hullNone), nonum_(1, false),
152 label_(1, dummy_pointer), preview_(new RenderPreview(this))
154 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
155 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
156 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
157 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
163 InsetMathHull::InsetMathHull(HullType type)
164 : InsetMathGrid(getCols(type), 1), type_(type), nonum_(1, false),
165 label_(1, dummy_pointer), preview_(new RenderPreview(this))
172 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid()
178 InsetMathHull::~InsetMathHull()
180 for (size_t i = 0; i < label_.size(); ++i)
185 Inset * InsetMathHull::clone() const
187 return new InsetMathHull(*this);
191 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
195 InsetMathGrid::operator=(other);
197 nonum_ = other.nonum_;
198 for (size_t i = 0; i < label_.size(); ++i)
200 label_ = other.label_;
201 for (size_t i = 0; i != label_.size(); ++i) {
203 label_[i] = new InsetLabel(*label_[i]);
205 preview_.reset(new RenderPreview(*other.preview_, this));
211 void InsetMathHull::setBuffer(Buffer & buffer)
214 for (idx_type i = 0, n = nargs(); i != n; ++i) {
215 MathData & data = cell(i);
216 for (size_t j = 0; j != data.size(); ++j)
217 data[j].nucleus()->setBuffer(buffer);
220 for (size_t i = 0; i != label_.size(); ++i) {
222 label_[i]->setBuffer(buffer);
227 void InsetMathHull::updateLabels(ParIterator const & it)
230 //FIXME: buffer_ should be set at creation for this inset! Problem is
231 // This inset is created at too many places (see Parser::parse1() in
235 for (size_t i = 0; i != label_.size(); ++i) {
237 label_[i]->updateLabels(it);
242 void InsetMathHull::addToToc(DocIterator const & pit)
245 //FIXME: buffer_ should be set at creation for this inset! Problem is
246 // This inset is created at too many places (see Parser::parse1() in
251 Toc & toc = buffer().tocBackend().toc("equation");
253 for (row_type row = 0; row != nrows(); ++row) {
257 label_[row]->addToToc(pit);
258 toc.push_back(TocItem(pit, 0, nicelabel(row)));
263 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
269 return InsetMathNest::editXY(cur, x, y);
273 InsetMath::mode_type InsetMathHull::currentMode() const
275 if (type_ == hullNone)
276 return UNDECIDED_MODE;
277 // definitely math mode ...
282 bool InsetMathHull::idxFirst(Cursor & cur) const
290 bool InsetMathHull::idxLast(Cursor & cur) const
292 cur.idx() = nargs() - 1;
293 cur.pos() = cur.lastpos();
298 char InsetMathHull::defaultColAlign(col_type col)
300 if (type_ == hullEqnArray)
302 if (type_ == hullGather)
304 if (type_ >= hullAlign)
305 return "rl"[col & 1];
310 int InsetMathHull::defaultColSpace(col_type col)
312 if (type_ == hullAlign || type_ == hullAlignAt)
314 if (type_ == hullXAlignAt)
315 return (col & 1) ? 20 : 0;
316 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
317 return (col & 1) ? 40 : 0;
322 docstring InsetMathHull::standardFont() const
324 return from_ascii(type_ == hullNone ? "lyxnochange" : "mathnormal");
328 bool InsetMathHull::previewState(BufferView * bv) const
330 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
331 graphics::PreviewImage const * pimage =
332 preview_->getPreviewImage(bv->buffer());
333 return pimage && pimage->image();
339 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
341 if (previewState(mi.base.bv)) {
342 preview_->metrics(mi, dim);
343 // insert a one pixel gap in front of the formula
346 dim.des += displayMargin();
347 // Cache the inset dimension.
348 setDimCache(mi, dim);
352 FontSetChanger dummy1(mi.base, standardFont());
353 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
355 // let the cells adjust themselves
356 InsetMathGrid::metrics(mi, dim);
359 dim.asc += displayMargin();
360 dim.des += displayMargin();
363 if (numberedType()) {
364 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
366 for (row_type row = 0; row < nrows(); ++row)
367 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
373 // make it at least as high as the current font
376 math_font_max_dim(mi.base.font, asc, des);
377 dim.asc = max(dim.asc, asc);
378 dim.des = max(dim.des, des);
379 // Cache the inset dimension.
380 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
381 setDimCache(mi, dim);
385 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
387 Dimension const dim = dimension(*pi.base.bv);
388 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
389 dim.asc + dim.des - 1, pi.backgroundColor(this));
393 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
395 use_preview_ = previewState(pi.base.bv);
398 // one pixel gap in front
399 preview_->draw(pi, x + 1, y);
400 setPosCache(pi, x, y);
404 FontSetChanger dummy1(pi.base, standardFont());
405 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
406 InsetMathGrid::draw(pi, x + 1, y);
408 if (numberedType()) {
409 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
410 for (row_type row = 0; row < nrows(); ++row) {
411 int const yy = y + rowinfo_[row].offset_;
412 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
413 docstring const nl = nicelabel(row);
417 setPosCache(pi, x, y);
421 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
424 InsetMathGrid::metricsT(mi, dim);
427 WriteStream wi(os, false, true, false);
429 dim.wid = os.str().size();
436 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
439 InsetMathGrid::drawT(pain, x, y);
442 WriteStream wi(os, false, true, false);
444 pain.draw(x, y, os.str().c_str());
449 static docstring latexString(InsetMathHull const & inset)
452 // This has to be static, because a preview snippet containing math
453 // in text mode (such as $\text{$\phi$}$) gets processed twice. The
454 // first time as a whole, and the second time only the inner math.
455 // In this last case inset.buffer() would be invalid.
456 // FIXME: preview snippets should only be processed once, such that
457 // both static qualifier and isBufferValid() check can be dropped.
458 static Encoding const * encoding = 0;
459 if (inset.isBufferValid())
460 encoding = &(inset.buffer().params().encoding());
461 WriteStream wi(ls, false, true, false, encoding);
467 void InsetMathHull::initUnicodeMath() const
469 // Trigger classification of the unicode symbols in this inset
470 docstring const dummy = latexString(*this);
474 void InsetMathHull::addPreview(graphics::PreviewLoader & ploader) const
476 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
477 docstring const snippet = latexString(*this);
478 preview_->addPreview(snippet, ploader);
483 bool InsetMathHull::notifyCursorLeaves(Cursor const & /*old*/, Cursor & cur)
485 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
486 Buffer const * buffer = cur.buffer();
487 docstring const snippet = latexString(*this);
488 preview_->addPreview(snippet, *buffer);
489 preview_->startLoading(*buffer);
490 cur.updateFlags(Update::Force);
496 docstring InsetMathHull::label(row_type row) const
498 LASSERT(row < nrows(), /**/);
499 if (InsetLabel * il = label_[row])
500 return il->screenLabel();
505 void InsetMathHull::label(row_type row, docstring const & label)
507 //lyxerr << "setting label '" << label << "' for row " << row << endl;
511 label_[row] = dummy_pointer;
512 // We need an update of the Buffer reference cache.
513 // This is achieved by updateLabels().
514 buffer().updateLabels();
516 label_[row]->updateCommand(label);
520 InsetCommandParams p(LABEL_CODE);
522 label_[row] = new InsetLabel(p);
524 label_[row]->setBuffer(buffer());
528 void InsetMathHull::numbered(row_type row, bool num)
531 if (nonum_[row] && label_[row]) {
534 // We need an update of the Buffer reference cache.
535 // This is achieved by updateLabels().
536 buffer().updateLabels();
541 bool InsetMathHull::numbered(row_type row) const
547 bool InsetMathHull::ams() const
549 return type_ == hullAlign
550 || type_ == hullFlAlign
551 || type_ == hullMultline
552 || type_ == hullGather
553 || type_ == hullAlignAt
554 || type_ == hullXAlignAt
555 || type_ == hullXXAlignAt;
559 Inset::DisplayType InsetMathHull::display() const
561 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
566 bool InsetMathHull::numberedType() const
568 if (type_ == hullNone)
570 if (type_ == hullSimple)
572 if (type_ == hullXXAlignAt)
574 if (type_ == hullRegexp)
576 for (row_type row = 0; row < nrows(); ++row)
583 void InsetMathHull::validate(LaTeXFeatures & features) const
586 features.require("amsmath");
588 // Validation is necessary only if not using AMS math.
589 // To be safe, we will always run mathedvalidate.
590 //if (features.amsstyle)
593 //features.binom = true;
595 InsetMathGrid::validate(features);
599 void InsetMathHull::header_write(WriteStream & os) const
601 bool n = numberedType();
615 os << "\\begin{equation" << star(n) << "}\n";
625 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
630 os << "\\begin{" << hullName(type_) << star(n) << '}'
631 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
635 os << "\\begin{" << hullName(type_) << '}'
636 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
644 os << "\\begin{unknown" << star(n) << '}';
650 void InsetMathHull::footer_write(WriteStream & os) const
652 bool n = numberedType();
665 os << "\\end{equation" << star(n) << "}\n";
677 os << "\\end{" << hullName(type_) << star(n) << "}\n";
681 os << "\\end{" << hullName(type_) << "}\n";
689 os << "\\end{unknown" << star(n) << '}';
695 bool InsetMathHull::rowChangeOK() const
698 type_ == hullEqnArray || type_ == hullAlign ||
699 type_ == hullFlAlign || type_ == hullAlignAt ||
700 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
701 type_ == hullGather || type_ == hullMultline;
705 bool InsetMathHull::colChangeOK() const
708 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
709 type_ == hullXAlignAt || type_ == hullXXAlignAt;
713 void InsetMathHull::addRow(row_type row)
718 bool numbered = numberedType();
720 if (type_ == hullMultline) {
721 if (row + 1 == nrows()) {
728 nonum_.insert(nonum_.begin() + row + 1, !numbered);
729 label_.insert(label_.begin() + row + 1, dummy_pointer);
732 InsetMathGrid::addRow(row);
736 void InsetMathHull::swapRow(row_type row)
740 if (row + 1 == nrows())
742 // gcc implements the standard std::vector<bool> which is *not* a container:
743 // http://www.gotw.ca/publications/N1185.pdf
744 // As a results, it doesn't like this:
745 // swap(nonum_[row], nonum_[row + 1]);
746 // so we do it manually:
747 bool const b = nonum_[row];
748 nonum_[row] = nonum_[row + 1];
750 swap(label_[row], label_[row + 1]);
751 InsetMathGrid::swapRow(row);
755 void InsetMathHull::delRow(row_type row)
757 if (nrows() <= 1 || !rowChangeOK())
759 if (row + 1 == nrows() && type_ == hullMultline) {
760 bool const b = nonum_[row - 1];
761 nonum_[row - 1] = nonum_[row];
763 swap(label_[row - 1], label_[row]);
764 InsetMathGrid::delRow(row);
767 InsetMathGrid::delRow(row);
768 // The last dummy row has no number info nor a label.
769 // Test nrows() + 1 because we have already erased the row.
770 if (row == nrows() + 1)
772 nonum_.erase(nonum_.begin() + row);
774 label_.erase(label_.begin() + row);
778 void InsetMathHull::addCol(col_type col)
782 InsetMathGrid::addCol(col);
786 void InsetMathHull::delCol(col_type col)
788 if (ncols() <= 1 || !colChangeOK())
790 InsetMathGrid::delCol(col);
794 docstring InsetMathHull::nicelabel(row_type row) const
799 return from_ascii("(#)");
800 return '(' + label_[row]->screenLabel() + from_ascii(", #)");
804 void InsetMathHull::glueall()
807 for (idx_type i = 0; i < nargs(); ++i)
809 *this = InsetMathHull(hullSimple);
815 void InsetMathHull::splitTo2Cols()
817 LASSERT(ncols() == 1, /**/);
818 InsetMathGrid::addCol(1);
819 for (row_type row = 0; row < nrows(); ++row) {
820 idx_type const i = 2 * row;
821 pos_type pos = firstRelOp(cell(i));
822 cell(i + 1) = MathData(cell(i).begin() + pos, cell(i).end());
823 cell(i).erase(pos, cell(i).size());
828 void InsetMathHull::splitTo3Cols()
830 LASSERT(ncols() < 3, /**/);
833 InsetMathGrid::addCol(2);
834 for (row_type row = 0; row < nrows(); ++row) {
835 idx_type const i = 3 * row + 1;
836 if (cell(i).size()) {
837 cell(i + 1) = MathData(cell(i).begin() + 1, cell(i).end());
838 cell(i).erase(1, cell(i).size());
844 void InsetMathHull::changeCols(col_type cols)
848 else if (ncols() < cols) {
854 while (ncols() < cols)
855 InsetMathGrid::addCol(ncols());
861 for (row_type row = 0; row < nrows(); ++row) {
862 idx_type const i = row * ncols();
863 for (col_type col = cols; col < ncols(); ++col) {
864 cell(i + cols - 1).append(cell(i + col));
868 while (ncols() > cols) {
869 InsetMathGrid::delCol(ncols() - 1);
874 HullType InsetMathHull::getType() const
880 void InsetMathHull::setType(HullType type)
887 void InsetMathHull::mutate(HullType newtype)
889 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
891 // we try to move along the chain
892 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
894 // +-------------------------------------+
895 // we use eqnarray as intermediate type for mutations that are not
896 // directly supported because it handles labels and numbering for
899 if (newtype == type_) {
903 else if (newtype < hullNone) {
908 else if (type_ == hullNone) {
914 else if (type_ == hullSimple) {
915 if (newtype == hullNone) {
919 setType(hullEquation);
925 else if (type_ == hullEquation) {
926 if (newtype < type_) {
930 } else if (newtype == hullEqnArray) {
931 // split it "nicely" on the first relop
933 setType(hullEqnArray);
934 } else if (newtype == hullMultline || newtype == hullGather) {
944 else if (type_ == hullEqnArray) {
945 if (newtype < type_) {
946 // set correct (no)numbering
948 for (row_type row = 0; row < nrows(); ++row) {
955 // set first non-empty label
956 for (row_type row = 0; row < nrows(); ++row) {
958 label_[0] = label_[row];
965 } else { // align & Co.
972 else if (type_ == hullAlign || type_ == hullAlignAt ||
973 type_ == hullXAlignAt || type_ == hullFlAlign) {
974 if (newtype < hullAlign) {
976 setType(hullEqnArray);
978 } else if (newtype == hullGather || newtype == hullMultline) {
981 } else if (newtype == hullXXAlignAt) {
982 for (row_type row = 0; row < nrows(); ++row)
983 numbered(row, false);
990 else if (type_ == hullXXAlignAt) {
991 for (row_type row = 0; row < nrows(); ++row)
992 numbered(row, false);
993 if (newtype < hullAlign) {
995 setType(hullEqnArray);
997 } else if (newtype == hullGather || newtype == hullMultline) {
1005 else if (type_ == hullMultline || type_ == hullGather) {
1006 if (newtype == hullGather || newtype == hullMultline)
1008 else if (newtype == hullAlign || newtype == hullFlAlign ||
1009 newtype == hullAlignAt || newtype == hullXAlignAt) {
1012 } else if (newtype == hullXXAlignAt) {
1014 for (row_type row = 0; row < nrows(); ++row)
1015 numbered(row, false);
1019 setType(hullEqnArray);
1025 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1026 << "' to '" << to_utf8(hullName(newtype))
1027 << "' not implemented" << endl;
1032 docstring InsetMathHull::eolString(row_type row, bool emptyline, bool fragile) const
1035 if (numberedType()) {
1036 if (label_[row] && !nonum_[row])
1037 res += "\\label{" + label_[row]->getParam("name") + '}';
1038 if (nonum_[row] && (type_ != hullMultline))
1039 res += "\\nonumber ";
1041 return res + InsetMathGrid::eolString(row, emptyline, fragile);
1045 void InsetMathHull::write(WriteStream & os) const
1047 ModeSpecifier specifier(os, MATH_MODE);
1049 InsetMathGrid::write(os);
1054 void InsetMathHull::normalize(NormalStream & os) const
1056 os << "[formula " << hullName(type_) << ' ';
1057 InsetMathGrid::normalize(os);
1062 void InsetMathHull::mathmlize(MathStream & os) const
1064 InsetMathGrid::mathmlize(os);
1068 void InsetMathHull::infoize(odocstream & os) const
1070 os << "Type: " << hullName(type_);
1074 void InsetMathHull::check() const
1076 LASSERT(nonum_.size() == nrows(), /**/);
1077 LASSERT(label_.size() == nrows(), /**/);
1081 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1085 idocstringstream iss(func.argument());
1086 iss >> dlang >> extra;
1088 extra = from_ascii("noextra");
1089 string const lang = to_ascii(dlang);
1091 // FIXME: temporarily disabled
1092 //if (cur.selection()) {
1095 // lyxerr << "use selection: " << ar << endl;
1096 // insert(pipeThroughExtern(lang, extra, ar));
1101 eq.push_back(MathAtom(new InsetMathChar('=')));
1103 // go to first item in line
1104 cur.idx() -= cur.idx() % ncols();
1107 if (getType() == hullSimple) {
1108 size_type pos = cur.cell().find_last(eq);
1110 if (cur.inMathed() && cur.selection()) {
1111 asArray(grabAndEraseSelection(cur), ar);
1112 } else if (pos == cur.cell().size()) {
1114 lyxerr << "use whole cell: " << ar << endl;
1116 ar = MathData(cur.cell().begin() + pos + 1, cur.cell().end());
1117 lyxerr << "use partial cell form pos: " << pos << endl;
1119 cur.cell().append(eq);
1120 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1121 cur.pos() = cur.lastpos();
1125 if (getType() == hullEquation) {
1126 lyxerr << "use equation inset" << endl;
1127 mutate(hullEqnArray);
1128 MathData & ar = cur.cell();
1129 lyxerr << "use cell: " << ar << endl;
1133 cur.cell() = pipeThroughExtern(lang, extra, ar);
1134 // move to end of line
1135 cur.pos() = cur.lastpos();
1140 lyxerr << "use eqnarray" << endl;
1141 cur.idx() += 2 - cur.idx() % ncols();
1143 MathData ar = cur.cell();
1144 lyxerr << "use cell: " << ar << endl;
1145 // FIXME: temporarily disabled
1151 cur.cell() = pipeThroughExtern(lang, extra, ar);
1152 cur.pos() = cur.lastpos();
1157 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1159 //lyxerr << "action: " << cmd.action << endl;
1160 switch (cmd.action) {
1162 case LFUN_FINISHED_BACKWARD:
1163 case LFUN_FINISHED_FORWARD:
1164 case LFUN_FINISHED_RIGHT:
1165 case LFUN_FINISHED_LEFT:
1166 //lyxerr << "action: " << cmd.action << endl;
1167 InsetMathGrid::doDispatch(cur, cmd);
1171 case LFUN_BREAK_PARAGRAPH:
1172 // just swallow this
1175 case LFUN_NEWLINE_INSERT:
1176 // some magic for the common case
1177 if (type_ == hullSimple || type_ == hullEquation) {
1178 cur.recordUndoInset();
1180 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1181 mutate(align ? hullAlign : hullEqnArray);
1182 cur.idx() = nrows() * ncols() - 1;
1183 cur.pos() = cur.lastpos();
1185 InsetMathGrid::doDispatch(cur, cmd);
1188 case LFUN_MATH_NUMBER_TOGGLE: {
1189 //lyxerr << "toggling all numbers" << endl;
1190 cur.recordUndoInset();
1191 bool old = numberedType();
1192 if (type_ == hullMultline)
1193 numbered(nrows() - 1, !old);
1195 for (row_type row = 0; row < nrows(); ++row)
1196 numbered(row, !old);
1198 cur.message(old ? _("No number") : _("Number"));
1202 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1203 cur.recordUndoInset();
1204 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1205 bool old = numbered(r);
1206 cur.message(old ? _("No number") : _("Number"));
1211 case LFUN_LABEL_INSERT: {
1212 cur.recordUndoInset();
1213 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1214 docstring old_label = label(r);
1215 docstring const default_label = from_ascii(
1216 (lyxrc.label_init_length >= 0) ? "eq:" : "");
1217 if (old_label.empty())
1218 old_label = default_label;
1220 InsetCommandParams p(LABEL_CODE);
1221 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1222 string const data = InsetCommand::params2string("label", p);
1224 if (cmd.argument().empty())
1225 cur.bv().showDialog("label", data);
1227 FuncRequest fr(LFUN_INSET_INSERT, data);
1233 case LFUN_WORD_DELETE_FORWARD:
1234 case LFUN_CHAR_DELETE_FORWARD:
1235 if (col(cur.idx()) + 1 == ncols()
1236 && cur.pos() == cur.lastpos()) {
1237 if (!label(row(cur.idx())).empty()) {
1238 cur.recordUndoInset();
1239 label(row(cur.idx()), docstring());
1240 } else if (numbered(row(cur.idx()))) {
1241 cur.recordUndoInset();
1242 numbered(row(cur.idx()), false);
1244 InsetMathGrid::doDispatch(cur, cmd);
1248 InsetMathGrid::doDispatch(cur, cmd);
1253 case LFUN_INSET_INSERT: {
1254 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1255 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1256 string const name = cmd.getArg(0);
1257 if (name == "label") {
1258 InsetCommandParams p(LABEL_CODE);
1259 InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1260 docstring str = p["name"];
1261 cur.recordUndoInset();
1262 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1266 docstring old = label(r);
1269 // The label will take care of the reference update.
1273 // Newly created inset so initialize it.
1274 label_[r]->initView();
1279 InsetMathGrid::doDispatch(cur, cmd);
1283 case LFUN_MATH_EXTERN:
1284 cur.recordUndoInset();
1288 case LFUN_MATH_MUTATE: {
1289 cur.recordUndoInset();
1290 row_type row = cur.row();
1291 col_type col = cur.col();
1292 mutate(hullType(cmd.argument()));
1293 cur.idx() = row * ncols() + col;
1294 if (cur.idx() > cur.lastidx()) {
1295 cur.idx() = cur.lastidx();
1296 cur.pos() = cur.lastpos();
1298 if (cur.pos() > cur.lastpos())
1299 cur.pos() = cur.lastpos();
1301 // FIXME: find some more clever handling of the selection,
1302 // i.e. preserve it.
1303 cur.clearSelection();
1304 //cur.dispatched(FINISHED);
1308 case LFUN_MATH_DISPLAY: {
1309 cur.recordUndoInset();
1310 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1312 cur.pos() = cur.lastpos();
1313 //cur.dispatched(FINISHED);
1318 InsetMathGrid::doDispatch(cur, cmd);
1324 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1325 FuncStatus & status) const
1327 switch (cmd.action) {
1328 case LFUN_FINISHED_BACKWARD:
1329 case LFUN_FINISHED_FORWARD:
1330 case LFUN_FINISHED_RIGHT:
1331 case LFUN_FINISHED_LEFT:
1334 case LFUN_NEWLINE_INSERT:
1335 case LFUN_MATH_EXTERN:
1336 case LFUN_MATH_MUTATE:
1337 case LFUN_MATH_DISPLAY:
1339 status.setEnabled(true);
1341 case LFUN_MATH_NUMBER_TOGGLE:
1342 // FIXME: what is the right test, this or the one of
1344 status.setEnabled(display());
1345 status.setOnOff(numberedType());
1347 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1348 // FIXME: what is the right test, this or the one of
1350 bool const enable = (type_ == hullMultline)
1351 ? (nrows() - 1 == cur.row())
1352 : display() != Inline;
1353 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1354 status.setEnabled(enable);
1355 status.setOnOff(numbered(r));
1358 case LFUN_LABEL_INSERT:
1359 status.setEnabled(type_ != hullSimple);
1361 case LFUN_INSET_INSERT:
1362 if (cmd.getArg(0) == "label") {
1363 status.setEnabled(type_ != hullSimple);
1366 return InsetMathGrid::getStatus(cur, cmd, status);
1367 case LFUN_TABULAR_FEATURE: {
1368 istringstream is(to_utf8(cmd.argument()));
1372 && (s == "append-row"
1373 || s == "delete-row"
1374 || s == "copy-row")) {
1375 status.message(bformat(
1376 from_utf8(N_("Can't change number of rows in '%1$s'")),
1378 status.setEnabled(false);
1382 && (s == "append-column"
1383 || s == "delete-column"
1384 || s == "copy-column")) {
1385 status.message(bformat(
1386 from_utf8(N_("Can't change number of columns in '%1$s'")),
1388 status.setEnabled(false);
1391 if ((type_ == hullSimple
1392 || type_ == hullEquation
1393 || type_ == hullNone) &&
1394 (s == "add-hline-above" || s == "add-hline-below")) {
1395 status.message(bformat(
1396 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1398 status.setEnabled(false);
1401 if (s == "add-vline-left" || s == "add-vline-right") {
1402 status.message(bformat(
1403 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1405 status.setEnabled(false);
1408 if (s == "valign-top" || s == "valign-middle"
1409 || s == "valign-bottom" || s == "align-left"
1410 || s == "align-center" || s == "align-right") {
1411 status.setEnabled(false);
1414 return InsetMathGrid::getStatus(cur, cmd, status);
1417 return InsetMathGrid::getStatus(cur, cmd, status);
1420 // This cannot really happen, but inserted to shut-up gcc
1421 return InsetMathGrid::getStatus(cur, cmd, status);
1425 /////////////////////////////////////////////////////////////////////
1429 // simply scrap this function if you want
1430 void InsetMathHull::mutateToText()
1433 // translate to latex
1435 latex(os, false, false);
1436 string str = os.str();
1439 Text * lt = view_->cursor().innerText();
1440 string::const_iterator cit = str.begin();
1441 string::const_iterator end = str.end();
1442 for (; cit != end; ++cit)
1443 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1446 //dispatch(LFUN_ESCAPE);
1451 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1452 docstring const & font)
1454 // this whole function is a hack and won't work for incremental font
1457 if (cur.inset().asInsetMath()->name() == font)
1458 cur.handleFont(to_utf8(font));
1460 cur.handleNest(createInsetMath(font));
1466 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1471 font.fromString(to_utf8(arg), b);
1472 if (font.fontInfo().color() != Color_inherit) {
1473 MathAtom at = MathAtom(new InsetMathColor(true, font.fontInfo().color()));
1474 cur.handleNest(at, 0);
1479 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1482 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1483 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1484 enter_front ? idxFirst(cur) : idxLast(cur);
1485 // The inset formula dimension is not necessarily the same as the
1486 // one of the instant preview image, so we have to indicate to the
1487 // BufferView that a metrics update is needed.
1488 cur.updateFlags(Update::Force);
1492 docstring InsetMathHull::editMessage() const
1494 return _("Math editor mode");
1498 void InsetMathHull::revealCodes(Cursor & cur) const
1500 if (!cur.inMathed())
1502 odocstringstream os;
1504 cur.message(os.str());
1506 // write something to the minibuffer
1507 // translate to latex
1511 string str = os.str();
1513 string::size_type pos = 0;
1515 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1518 else if (*it == '\0') {
1520 pos = it - str.begin();
1526 res = res.substr(pos - 30);
1527 if (res.size() > 60)
1528 res = res.substr(0, 60);
1534 InsetCode InsetMathHull::lyxCode() const
1540 /////////////////////////////////////////////////////////////////////
1544 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1547 // FIXME: completely broken
1548 static InsetMathHull * lastformula = 0;
1549 static CursorBase current = DocIterator(ibegin(nucleus()));
1551 static string laststr;
1553 if (lastformula != this || laststr != str) {
1554 //lyxerr << "reset lastformula to " << this << endl;
1557 current = ibegin(nucleus());
1559 mathed_parse_cell(ar, str);
1563 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1565 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1566 CursorSlice & top = it.back();
1567 MathData const & a = top.asInsetMath()->cell(top.idx_);
1568 if (a.matchpart(ar, top.pos_)) {
1569 bv->cursor().setSelection(it, ar.size());
1571 top.pos_ += ar.size();
1577 //lyxerr << "not found!" << endl;
1584 void InsetMathHull::write(ostream & os) const
1586 odocstringstream oss;
1587 WriteStream wi(oss, false, false, false);
1590 os << to_utf8(oss.str());
1594 void InsetMathHull::read(Lexer & lex)
1597 mathed_parse_normal(at, lex);
1598 operator=(*at->asHullInset());
1602 bool InsetMathHull::readQuiet(Lexer & lex)
1605 bool result = mathed_parse_normal(at, lex, Parse::QUIET);
1606 operator=(*at->asHullInset());
1611 int InsetMathHull::plaintext(odocstream & os, OutputParams const & runparams) const
1613 if (0 && display()) {
1617 TextPainter tpain(dim.width(), dim.height());
1618 drawT(tpain, 0, dim.ascent());
1620 // reset metrics cache to "real" values
1622 return tpain.textheight();
1624 odocstringstream oss;
1625 WriteStream wi(oss, false, true, false, runparams.encoding);
1628 docstring const str = oss.str();
1635 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1640 if (getType() == hullSimple)
1641 name = from_ascii("inlineequation");
1643 name = from_ascii("informalequation");
1645 docstring bname = name;
1646 if (!label(0).empty())
1647 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1649 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1651 odocstringstream ls;
1652 if (runparams.flavor == OutputParams::XML) {
1653 ms << MTag("alt role='tex' ");
1654 // Workaround for db2latex: db2latex always includes equations with
1655 // \ensuremath{} or \begin{display}\end{display}
1656 // so we strip LyX' math environment
1657 WriteStream wi(ls, false, false, false, runparams.encoding);
1658 InsetMathGrid::write(wi);
1659 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1664 InsetMathGrid::mathmlize(ms);
1667 ms << MTag("alt role='tex'");
1668 res = latex(ls, runparams);
1669 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1673 ms << from_ascii("<graphic fileref=\"eqn/");
1674 if (!label(0).empty())
1675 ms << sgml::cleanID(buffer(), runparams, label(0));
1677 ms << sgml::uniqueID(from_ascii("anon"));
1679 if (runparams.flavor == OutputParams::XML)
1680 ms << from_ascii("\"/>");
1682 ms << from_ascii("\">");
1684 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1686 return ms.line() + res;
1690 void InsetMathHull::textString(odocstream & os) const
1692 plaintext(os, OutputParams(0));
1696 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1698 return from_ascii("context-math");