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"
34 #include "FuncStatus.h"
35 #include "LaTeXFeatures.h"
37 #include "DispatchResult.h"
38 #include "FuncRequest.h"
41 #include "OutputParams.h"
42 #include "ParIterator.h"
45 #include "TextPainter.h"
46 #include "TocBackend.h"
48 #include "insets/RenderPreview.h"
49 #include "insets/InsetLabel.h"
50 #include "insets/InsetRef.h"
52 #include "graphics/PreviewImage.h"
53 #include "graphics/PreviewLoader.h"
55 #include "frontends/Painter.h"
57 #include "support/lassert.h"
58 #include "support/debug.h"
59 #include "support/gettext.h"
60 #include "support/lstrings.h"
65 using namespace lyx::support;
69 using cap::grabAndEraseSelection;
73 int getCols(HullType type)
90 // returns position of first relation operator in the array
91 // used for "intelligent splitting"
92 size_t firstRelOp(MathData const & ar)
94 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
96 return it - ar.begin();
101 char const * star(bool numbered)
103 return numbered ? "" : "*";
107 } // end anon namespace
110 HullType hullType(docstring const & s)
112 if (s == "none") return hullNone;
113 if (s == "simple") return hullSimple;
114 if (s == "equation") return hullEquation;
115 if (s == "eqnarray") return hullEqnArray;
116 if (s == "align") return hullAlign;
117 if (s == "alignat") return hullAlignAt;
118 if (s == "xalignat") return hullXAlignAt;
119 if (s == "xxalignat") return hullXXAlignAt;
120 if (s == "multline") return hullMultline;
121 if (s == "gather") return hullGather;
122 if (s == "flalign") return hullFlAlign;
123 if (s == "regexp") return hullRegexp;
124 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
129 docstring hullName(HullType type)
132 case hullNone: return from_ascii("none");
133 case hullSimple: return from_ascii("simple");
134 case hullEquation: return from_ascii("equation");
135 case hullEqnArray: return from_ascii("eqnarray");
136 case hullAlign: return from_ascii("align");
137 case hullAlignAt: return from_ascii("alignat");
138 case hullXAlignAt: return from_ascii("xalignat");
139 case hullXXAlignAt: return from_ascii("xxalignat");
140 case hullMultline: return from_ascii("multline");
141 case hullGather: return from_ascii("gather");
142 case hullFlAlign: return from_ascii("flalign");
143 case hullRegexp: return from_ascii("regexp");
145 lyxerr << "unknown hull type '" << type << "'" << endl;
146 return from_ascii("none");
150 static InsetLabel * dummy_pointer = 0;
152 InsetMathHull::InsetMathHull()
153 : InsetMathGrid(1, 1), type_(hullNone), nonum_(1, false),
154 label_(1, dummy_pointer), preview_(new RenderPreview(this))
156 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
157 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
158 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
159 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
165 InsetMathHull::InsetMathHull(HullType type)
166 : InsetMathGrid(getCols(type), 1), type_(type), nonum_(1, false),
167 label_(1, dummy_pointer), preview_(new RenderPreview(this))
174 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid()
180 InsetMathHull::~InsetMathHull()
182 for (size_t i = 0; i < label_.size(); ++i)
187 Inset * InsetMathHull::clone() const
189 return new InsetMathHull(*this);
193 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
197 InsetMathGrid::operator=(other);
199 nonum_ = other.nonum_;
200 for (size_t i = 0; i < label_.size(); ++i)
202 label_ = other.label_;
203 for (size_t i = 0; i != label_.size(); ++i) {
205 label_[i] = new InsetLabel(*label_[i]);
207 preview_.reset(new RenderPreview(*other.preview_, this));
213 void InsetMathHull::setBuffer(Buffer & buffer)
215 InsetMathGrid::setBuffer(buffer);
217 for (size_t i = 0; i != label_.size(); ++i) {
219 label_[i]->setBuffer(buffer);
224 void InsetMathHull::updateLabels(ParIterator const & it)
227 //FIXME: buffer_ should be set at creation for this inset! Problem is
228 // This inset is created at too many places (see Parser::parse1() in
232 for (size_t i = 0; i != label_.size(); ++i) {
234 label_[i]->updateLabels(it);
239 void InsetMathHull::addToToc(DocIterator const & pit)
242 //FIXME: buffer_ should be set at creation for this inset! Problem is
243 // This inset is created at too many places (see Parser::parse1() in
248 Toc & toc = buffer().tocBackend().toc("equation");
250 for (row_type row = 0; row != nrows(); ++row) {
254 label_[row]->addToToc(pit);
255 toc.push_back(TocItem(pit, 0, nicelabel(row)));
260 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
266 return InsetMathNest::editXY(cur, x, y);
270 InsetMath::mode_type InsetMathHull::currentMode() const
272 if (type_ == hullNone)
273 return UNDECIDED_MODE;
274 // definitely math mode ...
279 bool InsetMathHull::idxFirst(Cursor & cur) const
287 bool InsetMathHull::idxLast(Cursor & cur) const
289 cur.idx() = nargs() - 1;
290 cur.pos() = cur.lastpos();
295 char InsetMathHull::defaultColAlign(col_type col)
297 if (type_ == hullEqnArray)
299 if (type_ == hullGather)
301 if (type_ >= hullAlign)
302 return "rl"[col & 1];
307 int InsetMathHull::defaultColSpace(col_type col)
309 if (type_ == hullAlign || type_ == hullAlignAt)
311 if (type_ == hullXAlignAt)
312 return (col & 1) ? 20 : 0;
313 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
314 return (col & 1) ? 40 : 0;
319 docstring InsetMathHull::standardFont() const
321 return from_ascii(type_ == hullNone ? "lyxnochange" : "mathnormal");
325 bool InsetMathHull::previewState(BufferView * bv) const
327 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
328 graphics::PreviewImage const * pimage =
329 preview_->getPreviewImage(bv->buffer());
330 return pimage && pimage->image();
336 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
338 if (previewState(mi.base.bv)) {
339 preview_->metrics(mi, dim);
340 // insert a one pixel gap in front of the formula
343 dim.des += displayMargin();
344 // Cache the inset dimension.
345 setDimCache(mi, dim);
349 FontSetChanger dummy1(mi.base, standardFont());
350 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
352 // let the cells adjust themselves
353 InsetMathGrid::metrics(mi, dim);
356 dim.asc += displayMargin();
357 dim.des += displayMargin();
360 if (numberedType()) {
361 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
363 for (row_type row = 0; row < nrows(); ++row)
364 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
370 // make it at least as high as the current font
373 math_font_max_dim(mi.base.font, asc, des);
374 dim.asc = max(dim.asc, asc);
375 dim.des = max(dim.des, des);
376 // Cache the inset dimension.
377 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
378 setDimCache(mi, dim);
382 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
384 Dimension const dim = dimension(*pi.base.bv);
385 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
386 dim.asc + dim.des - 1, pi.backgroundColor(this));
390 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
392 use_preview_ = previewState(pi.base.bv);
395 // one pixel gap in front
396 preview_->draw(pi, x + 1, y);
397 setPosCache(pi, x, y);
401 FontSetChanger dummy1(pi.base, standardFont());
402 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
403 InsetMathGrid::draw(pi, x + 1, y);
405 if (numberedType()) {
406 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
407 for (row_type row = 0; row < nrows(); ++row) {
408 int const yy = y + rowinfo_[row].offset_;
409 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
410 docstring const nl = nicelabel(row);
414 setPosCache(pi, x, y);
418 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
421 InsetMathGrid::metricsT(mi, dim);
424 WriteStream wi(os, false, true, WriteStream::wsDefault);
426 dim.wid = os.str().size();
433 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
436 InsetMathGrid::drawT(pain, x, y);
439 WriteStream wi(os, false, true, WriteStream::wsDefault);
441 pain.draw(x, y, os.str().c_str());
446 static docstring latexString(InsetMathHull const & inset)
449 // This has to be static, because a preview snippet or a math
450 // macro containing math in text mode (such as $\text{$\phi$}$ or
451 // \newcommand{\xxx}{\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 static Encoding const * encoding = 0;
455 if (inset.isBufferValid())
456 encoding = &(inset.buffer().params().encoding());
457 WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
463 void InsetMathHull::initUnicodeMath() const
465 // Trigger classification of the unicode symbols in this inset
466 docstring const dummy = latexString(*this);
470 void InsetMathHull::addPreview(graphics::PreviewLoader & ploader) const
472 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
473 docstring const snippet = latexString(*this);
474 preview_->addPreview(snippet, ploader);
479 bool InsetMathHull::notifyCursorLeaves(Cursor const & /*old*/, Cursor & cur)
481 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
482 Buffer const * buffer = cur.buffer();
483 docstring const snippet = latexString(*this);
484 preview_->addPreview(snippet, *buffer);
485 preview_->startLoading(*buffer);
486 cur.updateFlags(Update::Force);
492 docstring InsetMathHull::label(row_type row) const
494 LASSERT(row < nrows(), /**/);
495 if (InsetLabel * il = label_[row])
496 return il->screenLabel();
501 void InsetMathHull::label(row_type row, docstring const & label)
503 //lyxerr << "setting label '" << label << "' for row " << row << endl;
507 label_[row] = dummy_pointer;
508 // We need an update of the Buffer reference cache.
509 // This is achieved by updateLabels().
510 buffer().updateLabels();
512 label_[row]->updateCommand(label);
516 InsetCommandParams p(LABEL_CODE);
518 label_[row] = new InsetLabel(p);
520 label_[row]->setBuffer(buffer());
524 void InsetMathHull::numbered(row_type row, bool num)
527 if (nonum_[row] && label_[row]) {
531 // The buffer is set at the end of readInset.
532 // When parsing the inset, buffer_ is 0.
535 // We need an update of the Buffer reference cache.
536 // This is achieved by updateLabels().
537 buffer().updateLabels();
542 bool InsetMathHull::numbered(row_type row) const
548 bool InsetMathHull::ams() const
550 return type_ == hullAlign
551 || type_ == hullFlAlign
552 || type_ == hullMultline
553 || type_ == hullGather
554 || type_ == hullAlignAt
555 || type_ == hullXAlignAt
556 || type_ == hullXXAlignAt;
560 Inset::DisplayType InsetMathHull::display() const
562 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
567 bool InsetMathHull::numberedType() const
569 if (type_ == hullNone)
571 if (type_ == hullSimple)
573 if (type_ == hullXXAlignAt)
575 if (type_ == hullRegexp)
577 for (row_type row = 0; row < nrows(); ++row)
584 void InsetMathHull::validate(LaTeXFeatures & features) const
587 features.require("amsmath");
589 // Validation is necessary only if not using AMS math.
590 // To be safe, we will always run mathedvalidate.
591 //if (features.amsstyle)
594 //features.binom = true;
596 InsetMathGrid::validate(features);
600 void InsetMathHull::header_write(WriteStream & os) const
602 bool n = numberedType();
616 os << "\\begin{equation" << star(n) << "}\n";
626 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
631 os << "\\begin{" << hullName(type_) << star(n) << '}'
632 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
636 os << "\\begin{" << hullName(type_) << '}'
637 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
645 os << "\\begin{unknown" << star(n) << '}';
651 void InsetMathHull::footer_write(WriteStream & os) const
653 bool n = numberedType();
666 os << "\\end{equation" << star(n) << "}\n";
678 os << "\\end{" << hullName(type_) << star(n) << "}\n";
682 os << "\\end{" << hullName(type_) << "}\n";
690 os << "\\end{unknown" << star(n) << '}';
696 bool InsetMathHull::rowChangeOK() const
699 type_ == hullEqnArray || type_ == hullAlign ||
700 type_ == hullFlAlign || type_ == hullAlignAt ||
701 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
702 type_ == hullGather || type_ == hullMultline;
706 bool InsetMathHull::colChangeOK() const
709 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
710 type_ == hullXAlignAt || type_ == hullXXAlignAt;
714 void InsetMathHull::addRow(row_type row)
719 bool numbered = numberedType();
721 if (type_ == hullMultline) {
722 if (row + 1 == nrows()) {
729 nonum_.insert(nonum_.begin() + row + 1, !numbered);
730 label_.insert(label_.begin() + row + 1, dummy_pointer);
733 InsetMathGrid::addRow(row);
737 void InsetMathHull::swapRow(row_type row)
741 if (row + 1 == nrows())
743 // gcc implements the standard std::vector<bool> which is *not* a container:
744 // http://www.gotw.ca/publications/N1185.pdf
745 // As a results, it doesn't like this:
746 // swap(nonum_[row], nonum_[row + 1]);
747 // so we do it manually:
748 bool const b = nonum_[row];
749 nonum_[row] = nonum_[row + 1];
751 swap(label_[row], label_[row + 1]);
752 InsetMathGrid::swapRow(row);
756 void InsetMathHull::delRow(row_type row)
758 if (nrows() <= 1 || !rowChangeOK())
760 if (row + 1 == nrows() && type_ == hullMultline) {
761 bool const b = nonum_[row - 1];
762 nonum_[row - 1] = nonum_[row];
764 swap(label_[row - 1], label_[row]);
765 InsetMathGrid::delRow(row);
768 InsetMathGrid::delRow(row);
769 // The last dummy row has no number info nor a label.
770 // Test nrows() + 1 because we have already erased the row.
771 if (row == nrows() + 1)
773 nonum_.erase(nonum_.begin() + row);
775 label_.erase(label_.begin() + row);
779 void InsetMathHull::addCol(col_type col)
783 InsetMathGrid::addCol(col);
787 void InsetMathHull::delCol(col_type col)
789 if (ncols() <= 1 || !colChangeOK())
791 InsetMathGrid::delCol(col);
795 docstring InsetMathHull::nicelabel(row_type row) const
800 return from_ascii("(#)");
801 return '(' + label_[row]->screenLabel() + from_ascii(", #)");
805 void InsetMathHull::glueall()
808 for (idx_type i = 0; i < nargs(); ++i)
810 *this = InsetMathHull(hullSimple);
816 void InsetMathHull::splitTo2Cols()
818 LASSERT(ncols() == 1, /**/);
819 InsetMathGrid::addCol(1);
820 for (row_type row = 0; row < nrows(); ++row) {
821 idx_type const i = 2 * row;
822 pos_type pos = firstRelOp(cell(i));
823 cell(i + 1) = MathData(cell(i).begin() + pos, cell(i).end());
824 cell(i).erase(pos, cell(i).size());
829 void InsetMathHull::splitTo3Cols()
831 LASSERT(ncols() < 3, /**/);
834 InsetMathGrid::addCol(2);
835 for (row_type row = 0; row < nrows(); ++row) {
836 idx_type const i = 3 * row + 1;
837 if (cell(i).size()) {
838 cell(i + 1) = MathData(cell(i).begin() + 1, cell(i).end());
839 cell(i).erase(1, cell(i).size());
845 void InsetMathHull::changeCols(col_type cols)
849 else if (ncols() < cols) {
855 while (ncols() < cols)
856 InsetMathGrid::addCol(ncols());
862 for (row_type row = 0; row < nrows(); ++row) {
863 idx_type const i = row * ncols();
864 for (col_type col = cols; col < ncols(); ++col) {
865 cell(i + cols - 1).append(cell(i + col));
869 while (ncols() > cols) {
870 InsetMathGrid::delCol(ncols() - 1);
875 HullType InsetMathHull::getType() const
881 void InsetMathHull::setType(HullType type)
888 void InsetMathHull::mutate(HullType newtype)
890 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
892 // we try to move along the chain
893 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
895 // +-------------------------------------+
896 // we use eqnarray as intermediate type for mutations that are not
897 // directly supported because it handles labels and numbering for
900 if (newtype == type_) {
904 else if (newtype < hullNone) {
909 else if (type_ == hullNone) {
915 else if (type_ == hullSimple) {
916 if (newtype == hullNone) {
920 setType(hullEquation);
926 else if (type_ == hullEquation) {
927 if (newtype < type_) {
931 } else if (newtype == hullEqnArray) {
932 // split it "nicely" on the first relop
934 setType(hullEqnArray);
935 } else if (newtype == hullMultline || newtype == hullGather) {
945 else if (type_ == hullEqnArray) {
946 if (newtype < type_) {
947 // set correct (no)numbering
949 for (row_type row = 0; row < nrows(); ++row) {
956 // set first non-empty label
957 for (row_type row = 0; row < nrows(); ++row) {
959 label_[0] = label_[row];
966 } else { // align & Co.
973 else if (type_ == hullAlign || type_ == hullAlignAt ||
974 type_ == hullXAlignAt || type_ == hullFlAlign) {
975 if (newtype < hullAlign) {
977 setType(hullEqnArray);
979 } else if (newtype == hullGather || newtype == hullMultline) {
982 } else if (newtype == hullXXAlignAt) {
983 for (row_type row = 0; row < nrows(); ++row)
984 numbered(row, false);
991 else if (type_ == hullXXAlignAt) {
992 for (row_type row = 0; row < nrows(); ++row)
993 numbered(row, false);
994 if (newtype < hullAlign) {
996 setType(hullEqnArray);
998 } else if (newtype == hullGather || newtype == hullMultline) {
1006 else if (type_ == hullMultline || type_ == hullGather) {
1007 if (newtype == hullGather || newtype == hullMultline)
1009 else if (newtype == hullAlign || newtype == hullFlAlign ||
1010 newtype == hullAlignAt || newtype == hullXAlignAt) {
1013 } else if (newtype == hullXXAlignAt) {
1015 for (row_type row = 0; row < nrows(); ++row)
1016 numbered(row, false);
1020 setType(hullEqnArray);
1026 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1027 << "' to '" << to_utf8(hullName(newtype))
1028 << "' not implemented" << endl;
1033 docstring InsetMathHull::eolString(row_type row, bool fragile) const
1036 if (numberedType()) {
1037 if (label_[row] && !nonum_[row])
1038 res += "\\label{" + label_[row]->getParam("name") + '}';
1039 if (nonum_[row] && (type_ != hullMultline))
1040 res += "\\nonumber ";
1042 return res + InsetMathGrid::eolString(row, fragile);
1046 void InsetMathHull::write(WriteStream & os) const
1048 ModeSpecifier specifier(os, MATH_MODE);
1050 InsetMathGrid::write(os);
1055 void InsetMathHull::normalize(NormalStream & os) const
1057 os << "[formula " << hullName(type_) << ' ';
1058 InsetMathGrid::normalize(os);
1063 void InsetMathHull::mathmlize(MathStream & os) const
1065 InsetMathGrid::mathmlize(os);
1069 void InsetMathHull::infoize(odocstream & os) const
1071 os << "Type: " << hullName(type_);
1075 void InsetMathHull::check() const
1077 LASSERT(nonum_.size() == nrows(), /**/);
1078 LASSERT(label_.size() == nrows(), /**/);
1082 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1086 idocstringstream iss(func.argument());
1087 iss >> dlang >> extra;
1089 extra = from_ascii("noextra");
1090 string const lang = to_ascii(dlang);
1092 // FIXME: temporarily disabled
1093 //if (cur.selection()) {
1096 // lyxerr << "use selection: " << ar << endl;
1097 // insert(pipeThroughExtern(lang, extra, ar));
1102 eq.push_back(MathAtom(new InsetMathChar('=')));
1104 // go to first item in line
1105 cur.idx() -= cur.idx() % ncols();
1108 if (getType() == hullSimple) {
1109 size_type pos = cur.cell().find_last(eq);
1111 if (cur.inMathed() && cur.selection()) {
1112 asArray(grabAndEraseSelection(cur), ar);
1113 } else if (pos == cur.cell().size()) {
1115 lyxerr << "use whole cell: " << ar << endl;
1117 ar = MathData(cur.cell().begin() + pos + 1, cur.cell().end());
1118 lyxerr << "use partial cell form pos: " << pos << endl;
1120 cur.cell().append(eq);
1121 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1122 cur.pos() = cur.lastpos();
1126 if (getType() == hullEquation) {
1127 lyxerr << "use equation inset" << endl;
1128 mutate(hullEqnArray);
1129 MathData & ar = cur.cell();
1130 lyxerr << "use cell: " << ar << endl;
1134 cur.cell() = pipeThroughExtern(lang, extra, ar);
1135 // move to end of line
1136 cur.pos() = cur.lastpos();
1141 lyxerr << "use eqnarray" << endl;
1142 cur.idx() += 2 - cur.idx() % ncols();
1144 MathData ar = cur.cell();
1145 lyxerr << "use cell: " << ar << endl;
1146 // FIXME: temporarily disabled
1152 cur.cell() = pipeThroughExtern(lang, extra, ar);
1153 cur.pos() = cur.lastpos();
1158 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1160 //lyxerr << "action: " << cmd.action << endl;
1161 switch (cmd.action) {
1163 case LFUN_FINISHED_BACKWARD:
1164 case LFUN_FINISHED_FORWARD:
1165 case LFUN_FINISHED_RIGHT:
1166 case LFUN_FINISHED_LEFT:
1167 //lyxerr << "action: " << cmd.action << endl;
1168 InsetMathGrid::doDispatch(cur, cmd);
1172 case LFUN_BREAK_PARAGRAPH:
1173 // just swallow this
1176 case LFUN_NEWLINE_INSERT:
1177 // some magic for the common case
1178 if (type_ == hullSimple || type_ == hullEquation) {
1179 cur.recordUndoInset();
1181 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1182 mutate(align ? hullAlign : hullEqnArray);
1183 cur.idx() = nrows() * ncols() - 1;
1184 cur.pos() = cur.lastpos();
1186 InsetMathGrid::doDispatch(cur, cmd);
1189 case LFUN_MATH_NUMBER_TOGGLE: {
1190 //lyxerr << "toggling all numbers" << endl;
1191 cur.recordUndoInset();
1192 bool old = numberedType();
1193 if (type_ == hullMultline)
1194 numbered(nrows() - 1, !old);
1196 for (row_type row = 0; row < nrows(); ++row)
1197 numbered(row, !old);
1199 cur.message(old ? _("No number") : _("Number"));
1203 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1204 cur.recordUndoInset();
1205 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1206 bool old = numbered(r);
1207 cur.message(old ? _("No number") : _("Number"));
1212 case LFUN_LABEL_INSERT: {
1213 cur.recordUndoInset();
1214 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1215 docstring old_label = label(r);
1216 docstring const default_label = from_ascii(
1217 (lyxrc.label_init_length >= 0) ? "eq:" : "");
1218 if (old_label.empty())
1219 old_label = default_label;
1221 InsetCommandParams p(LABEL_CODE);
1222 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1223 string const data = InsetCommand::params2string("label", p);
1225 if (cmd.argument().empty())
1226 cur.bv().showDialog("label", data);
1228 FuncRequest fr(LFUN_INSET_INSERT, data);
1234 case LFUN_LABEL_COPY_AS_REF: {
1236 if (cmd.argument().empty() && &cur.inset() == this)
1237 // if there is no argument and we're inside math, we retrieve
1238 // the row number from the cursor position.
1239 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1241 // if there is an argument, find the corresponding label, else
1242 // check whether there is at least one label.
1243 for (row = 0; row != nrows(); ++row)
1244 if (!nonum_[row] && label_[row]
1245 && (cmd.argument().empty() || label(row) == cmd.argument()))
1252 InsetCommandParams p(REF_CODE, "ref");
1253 p["reference"] = label(row);
1254 cap::clearSelection();
1255 cap::copyInset(cur, new InsetRef(*cur.buffer(), p), label(row));
1259 case LFUN_WORD_DELETE_FORWARD:
1260 case LFUN_CHAR_DELETE_FORWARD:
1261 if (col(cur.idx()) + 1 == ncols()
1262 && cur.pos() == cur.lastpos()) {
1263 if (!label(row(cur.idx())).empty()) {
1264 cur.recordUndoInset();
1265 label(row(cur.idx()), docstring());
1266 } else if (numbered(row(cur.idx()))) {
1267 cur.recordUndoInset();
1268 numbered(row(cur.idx()), false);
1270 InsetMathGrid::doDispatch(cur, cmd);
1274 InsetMathGrid::doDispatch(cur, cmd);
1279 case LFUN_INSET_INSERT: {
1280 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1281 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1282 string const name = cmd.getArg(0);
1283 if (name == "label") {
1284 InsetCommandParams p(LABEL_CODE);
1285 InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1286 docstring str = p["name"];
1287 cur.recordUndoInset();
1288 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1292 docstring old = label(r);
1295 // The label will take care of the reference update.
1299 // Newly created inset so initialize it.
1300 label_[r]->initView();
1305 InsetMathGrid::doDispatch(cur, cmd);
1309 case LFUN_MATH_EXTERN:
1310 cur.recordUndoInset();
1314 case LFUN_MATH_MUTATE: {
1315 cur.recordUndoInset();
1316 row_type row = cur.row();
1317 col_type col = cur.col();
1318 mutate(hullType(cmd.argument()));
1319 cur.idx() = row * ncols() + col;
1320 if (cur.idx() > cur.lastidx()) {
1321 cur.idx() = cur.lastidx();
1322 cur.pos() = cur.lastpos();
1324 if (cur.pos() > cur.lastpos())
1325 cur.pos() = cur.lastpos();
1327 // FIXME: find some more clever handling of the selection,
1328 // i.e. preserve it.
1329 cur.clearSelection();
1330 //cur.dispatched(FINISHED);
1334 case LFUN_MATH_DISPLAY: {
1335 cur.recordUndoInset();
1336 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1338 cur.pos() = cur.lastpos();
1339 //cur.dispatched(FINISHED);
1344 InsetMathGrid::doDispatch(cur, cmd);
1350 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1351 FuncStatus & status) const
1353 switch (cmd.action) {
1354 case LFUN_FINISHED_BACKWARD:
1355 case LFUN_FINISHED_FORWARD:
1356 case LFUN_FINISHED_RIGHT:
1357 case LFUN_FINISHED_LEFT:
1360 case LFUN_NEWLINE_INSERT:
1361 case LFUN_MATH_EXTERN:
1362 case LFUN_MATH_DISPLAY:
1364 status.setEnabled(true);
1367 case LFUN_MATH_MUTATE: {
1368 HullType ht = hullType(cmd.argument());
1369 status.setOnOff(type_ == ht);
1370 status.setEnabled(true);
1374 case LFUN_MATH_NUMBER_TOGGLE:
1375 // FIXME: what is the right test, this or the one of
1377 status.setEnabled(display());
1378 status.setOnOff(numberedType());
1381 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1382 // FIXME: what is the right test, this or the one of
1384 bool const enable = (type_ == hullMultline)
1385 ? (nrows() - 1 == cur.row())
1386 : display() != Inline && nrows() > 1;
1387 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1388 status.setEnabled(enable);
1389 status.setOnOff(enable && numbered(r));
1393 case LFUN_LABEL_INSERT:
1394 status.setEnabled(type_ != hullSimple);
1397 case LFUN_LABEL_COPY_AS_REF: {
1398 bool enabled = false;
1400 if (cmd.argument().empty() && &cur.inset() == this) {
1401 // if there is no argument and we're inside math, we retrieve
1402 // the row number from the cursor position.
1403 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1404 enabled = numberedType() && label_[row] && !nonum_[row];
1406 // if there is an argument, find the corresponding label, else
1407 // check whether there is at least one label.
1408 for (row_type row = 0; row != nrows(); ++row) {
1409 if (!nonum_[row] && label_[row] &&
1410 (cmd.argument().empty() || label(row) == cmd.argument())) {
1416 status.setEnabled(enabled);
1420 case LFUN_INSET_INSERT:
1421 if (cmd.getArg(0) == "label") {
1422 status.setEnabled(type_ != hullSimple);
1425 return InsetMathGrid::getStatus(cur, cmd, status);
1427 case LFUN_TABULAR_FEATURE: {
1428 istringstream is(to_utf8(cmd.argument()));
1432 && (s == "append-row"
1433 || s == "delete-row"
1434 || s == "copy-row")) {
1435 status.message(bformat(
1436 from_utf8(N_("Can't change number of rows in '%1$s'")),
1438 status.setEnabled(false);
1442 && (s == "append-column"
1443 || s == "delete-column"
1444 || s == "copy-column")) {
1445 status.message(bformat(
1446 from_utf8(N_("Can't change number of columns in '%1$s'")),
1448 status.setEnabled(false);
1451 if ((type_ == hullSimple
1452 || type_ == hullEquation
1453 || type_ == hullNone) &&
1454 (s == "add-hline-above" || s == "add-hline-below")) {
1455 status.message(bformat(
1456 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1458 status.setEnabled(false);
1461 if (s == "add-vline-left" || s == "add-vline-right") {
1462 status.message(bformat(
1463 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1465 status.setEnabled(false);
1468 if (s == "valign-top" || s == "valign-middle"
1469 || s == "valign-bottom" || s == "align-left"
1470 || s == "align-center" || s == "align-right") {
1471 status.setEnabled(false);
1474 return InsetMathGrid::getStatus(cur, cmd, status);
1478 return InsetMathGrid::getStatus(cur, cmd, status);
1481 // This cannot really happen, but inserted to shut-up gcc
1482 return InsetMathGrid::getStatus(cur, cmd, status);
1486 /////////////////////////////////////////////////////////////////////
1490 // simply scrap this function if you want
1491 void InsetMathHull::mutateToText()
1494 // translate to latex
1496 latex(os, false, false);
1497 string str = os.str();
1500 Text * lt = view_->cursor().innerText();
1501 string::const_iterator cit = str.begin();
1502 string::const_iterator end = str.end();
1503 for (; cit != end; ++cit)
1504 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1507 //dispatch(LFUN_ESCAPE);
1512 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1513 docstring const & font)
1515 // this whole function is a hack and won't work for incremental font
1518 if (cur.inset().asInsetMath()->name() == font)
1519 cur.handleFont(to_utf8(font));
1521 cur.handleNest(createInsetMath(font));
1527 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1532 font.fromString(to_utf8(arg), b);
1533 if (font.fontInfo().color() != Color_inherit) {
1534 MathAtom at = MathAtom(new InsetMathColor(true, font.fontInfo().color()));
1535 cur.handleNest(at, 0);
1540 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1543 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1544 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1545 enter_front ? idxFirst(cur) : idxLast(cur);
1546 // The inset formula dimension is not necessarily the same as the
1547 // one of the instant preview image, so we have to indicate to the
1548 // BufferView that a metrics update is needed.
1549 cur.updateFlags(Update::Force);
1553 void InsetMathHull::revealCodes(Cursor & cur) const
1555 if (!cur.inMathed())
1557 odocstringstream os;
1559 cur.message(os.str());
1561 // write something to the minibuffer
1562 // translate to latex
1566 string str = os.str();
1568 string::size_type pos = 0;
1570 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1573 else if (*it == '\0') {
1575 pos = it - str.begin();
1581 res = res.substr(pos - 30);
1582 if (res.size() > 60)
1583 res = res.substr(0, 60);
1589 /////////////////////////////////////////////////////////////////////
1593 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1596 // FIXME: completely broken
1597 static InsetMathHull * lastformula = 0;
1598 static CursorBase current = DocIterator(ibegin(nucleus()));
1600 static string laststr;
1602 if (lastformula != this || laststr != str) {
1603 //lyxerr << "reset lastformula to " << this << endl;
1606 current = ibegin(nucleus());
1608 mathed_parse_cell(ar, str);
1612 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1614 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1615 CursorSlice & top = it.back();
1616 MathData const & a = top.asInsetMath()->cell(top.idx_);
1617 if (a.matchpart(ar, top.pos_)) {
1618 bv->cursor().setSelection(it, ar.size());
1620 top.pos_ += ar.size();
1626 //lyxerr << "not found!" << endl;
1633 void InsetMathHull::write(ostream & os) const
1635 odocstringstream oss;
1636 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1639 os << to_utf8(oss.str());
1643 void InsetMathHull::read(Lexer & lex)
1646 mathed_parse_normal(at, lex);
1647 operator=(*at->asHullInset());
1651 bool InsetMathHull::readQuiet(Lexer & lex)
1654 bool result = mathed_parse_normal(at, lex, Parse::QUIET);
1655 operator=(*at->asHullInset());
1660 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1662 if (0 && display()) {
1666 TextPainter tpain(dim.width(), dim.height());
1667 drawT(tpain, 0, dim.ascent());
1669 // reset metrics cache to "real" values
1671 return tpain.textheight();
1673 odocstringstream oss;
1674 Encoding const * const enc = encodings.fromLyXName("utf8");
1675 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1677 if (type_ == hullRegexp)
1681 docstring const str = oss.str();
1688 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1693 if (getType() == hullSimple)
1694 name = from_ascii("inlineequation");
1696 name = from_ascii("informalequation");
1698 docstring bname = name;
1699 if (!label(0).empty())
1700 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1702 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1704 odocstringstream ls;
1705 if (runparams.flavor == OutputParams::XML) {
1706 ms << MTag("alt role='tex' ");
1707 // Workaround for db2latex: db2latex always includes equations with
1708 // \ensuremath{} or \begin{display}\end{display}
1709 // so we strip LyX' math environment
1710 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1711 InsetMathGrid::write(wi);
1712 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1717 InsetMathGrid::mathmlize(ms);
1720 ms << MTag("alt role='tex'");
1721 res = latex(ls, runparams);
1722 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1726 ms << from_ascii("<graphic fileref=\"eqn/");
1727 if (!label(0).empty())
1728 ms << sgml::cleanID(buffer(), runparams, label(0));
1730 ms << sgml::uniqueID(from_ascii("anon"));
1732 if (runparams.flavor == OutputParams::XML)
1733 ms << from_ascii("\"/>");
1735 ms << from_ascii("\">");
1737 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1739 return ms.line() + res;
1743 void InsetMathHull::tocString(odocstream & os) const
1745 plaintext(os, OutputParams(0));
1749 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1751 return from_ascii("context-math");