2 * \file InsetMathHull.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 #include "InsetMathHull.h"
15 #include "InsetMathArray.h"
16 #include "InsetMathChar.h"
17 #include "InsetMathColor.h"
18 #include "InsetMathDelim.h"
19 #include "InsetMathRef.h"
20 #include "InsetMathSpace.h"
22 #include "MathExtern.h"
23 #include "MathFactory.h"
24 #include "MathParser.h"
25 #include "MathStream.h"
26 #include "MathSupport.h"
29 #include "buffer_funcs.h"
30 #include "BufferParams.h"
31 #include "BufferView.h"
33 #include "CutAndPaste.h"
34 #include "DispatchResult.h"
36 #include "FuncRequest.h"
37 #include "FuncStatus.h"
38 #include "LaTeXFeatures.h"
41 #include "OutputParams.h"
42 #include "ParIterator.h"
45 #include "TextPainter.h"
46 #include "TocBackend.h"
48 #include "insets/InsetLabel.h"
49 #include "insets/InsetRef.h"
50 #include "insets/RenderPreview.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(Buffer * buf)
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;
166 InsetMathHull::InsetMathHull(HullType type, Buffer * buf)
167 : InsetMathGrid(getCols(type), 1), type_(type), nonum_(1, false),
168 label_(1, dummy_pointer), preview_(new RenderPreview(this))
176 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid()
182 InsetMathHull::~InsetMathHull()
184 for (size_t i = 0; i < label_.size(); ++i)
189 Inset * InsetMathHull::clone() const
191 return new InsetMathHull(*this);
195 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
199 InsetMathGrid::operator=(other);
201 nonum_ = other.nonum_;
202 buffer_ = other.buffer_;
203 for (size_t i = 0; i < label_.size(); ++i)
205 label_ = other.label_;
206 for (size_t i = 0; i != label_.size(); ++i) {
208 label_[i] = new InsetLabel(*label_[i]);
210 preview_.reset(new RenderPreview(*other.preview_, this));
216 void InsetMathHull::setBuffer(Buffer & buffer)
218 InsetMathGrid::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, WriteStream::wsDefault);
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, WriteStream::wsDefault);
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 or a math
453 // macro containing math in text mode (such as $\text{$\phi$}$ or
454 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
455 // first time as a whole, and the second time only the inner math.
456 // In this last case inset.buffer() would be invalid.
457 static Encoding const * encoding = 0;
458 if (inset.isBufferValid())
459 encoding = &(inset.buffer().params().encoding());
460 WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
466 void InsetMathHull::initUnicodeMath() const
468 // Trigger classification of the unicode symbols in this inset
469 docstring const dummy = latexString(*this);
473 void InsetMathHull::addPreview(graphics::PreviewLoader & ploader) const
475 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
476 docstring const snippet = latexString(*this);
477 preview_->addPreview(snippet, ploader);
482 bool InsetMathHull::notifyCursorLeaves(Cursor const & /*old*/, Cursor & cur)
484 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
485 Buffer const * buffer = cur.buffer();
486 docstring const snippet = latexString(*this);
487 preview_->addPreview(snippet, *buffer);
488 preview_->startLoading(*buffer);
489 cur.updateFlags(Update::Force);
495 docstring InsetMathHull::label(row_type row) const
497 LASSERT(row < nrows(), /**/);
498 if (InsetLabel * il = label_[row])
499 return il->screenLabel();
504 void InsetMathHull::label(row_type row, docstring const & label)
506 //lyxerr << "setting label '" << label << "' for row " << row << endl;
510 label_[row] = dummy_pointer;
511 // We need an update of the Buffer reference cache.
512 // This is achieved by updateLabels().
514 buffer().updateLabels();
517 label_[row]->updateCommand(label);
519 label_[row]->setParam("name", label);
523 InsetCommandParams p(LABEL_CODE);
525 label_[row] = new InsetLabel(p);
527 label_[row]->setBuffer(buffer());
531 void InsetMathHull::numbered(row_type row, bool num)
534 if (nonum_[row] && label_[row]) {
538 // The buffer is set at the end of readInset.
539 // When parsing the inset, buffer_ is 0.
542 // We need an update of the Buffer reference cache.
543 // This is achieved by updateLabels().
544 buffer().updateLabels();
549 bool InsetMathHull::numbered(row_type row) const
555 bool InsetMathHull::ams() const
557 return type_ == hullAlign
558 || type_ == hullFlAlign
559 || type_ == hullMultline
560 || type_ == hullGather
561 || type_ == hullAlignAt
562 || type_ == hullXAlignAt
563 || type_ == hullXXAlignAt;
567 Inset::DisplayType InsetMathHull::display() const
569 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
574 bool InsetMathHull::numberedType() const
576 if (type_ == hullNone)
578 if (type_ == hullSimple)
580 if (type_ == hullXXAlignAt)
582 if (type_ == hullRegexp)
584 for (row_type row = 0; row < nrows(); ++row)
591 void InsetMathHull::validate(LaTeXFeatures & features) const
594 features.require("amsmath");
596 // Validation is necessary only if not using AMS math.
597 // To be safe, we will always run mathedvalidate.
598 //if (features.amsstyle)
601 //features.binom = true;
603 InsetMathGrid::validate(features);
607 void InsetMathHull::header_write(WriteStream & os) const
609 bool n = numberedType();
623 os << "\\begin{equation" << star(n) << "}\n";
633 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
638 os << "\\begin{" << hullName(type_) << star(n) << '}'
639 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
643 os << "\\begin{" << hullName(type_) << '}'
644 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
652 os << "\\begin{unknown" << star(n) << '}';
658 void InsetMathHull::footer_write(WriteStream & os) const
660 bool n = numberedType();
673 os << "\\end{equation" << star(n) << "}\n";
685 os << "\\end{" << hullName(type_) << star(n) << "}\n";
689 os << "\\end{" << hullName(type_) << "}\n";
697 os << "\\end{unknown" << star(n) << '}';
703 bool InsetMathHull::rowChangeOK() const
706 type_ == hullEqnArray || type_ == hullAlign ||
707 type_ == hullFlAlign || type_ == hullAlignAt ||
708 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
709 type_ == hullGather || type_ == hullMultline;
713 bool InsetMathHull::colChangeOK() const
716 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
717 type_ == hullXAlignAt || type_ == hullXXAlignAt;
721 void InsetMathHull::addRow(row_type row)
726 bool numbered = numberedType();
728 if (type_ == hullMultline) {
729 if (row + 1 == nrows()) {
736 nonum_.insert(nonum_.begin() + row + 1, !numbered);
737 label_.insert(label_.begin() + row + 1, dummy_pointer);
740 InsetMathGrid::addRow(row);
744 void InsetMathHull::swapRow(row_type row)
748 if (row + 1 == nrows())
750 // gcc implements the standard std::vector<bool> which is *not* a container:
751 // http://www.gotw.ca/publications/N1185.pdf
752 // As a results, it doesn't like this:
753 // swap(nonum_[row], nonum_[row + 1]);
754 // so we do it manually:
755 bool const b = nonum_[row];
756 nonum_[row] = nonum_[row + 1];
758 swap(label_[row], label_[row + 1]);
759 InsetMathGrid::swapRow(row);
763 void InsetMathHull::delRow(row_type row)
765 if (nrows() <= 1 || !rowChangeOK())
767 if (row + 1 == nrows() && type_ == hullMultline) {
768 bool const b = nonum_[row - 1];
769 nonum_[row - 1] = nonum_[row];
771 swap(label_[row - 1], label_[row]);
772 InsetMathGrid::delRow(row);
775 InsetMathGrid::delRow(row);
776 // The last dummy row has no number info nor a label.
777 // Test nrows() + 1 because we have already erased the row.
778 if (row == nrows() + 1)
780 nonum_.erase(nonum_.begin() + row);
782 label_.erase(label_.begin() + row);
786 void InsetMathHull::addCol(col_type col)
790 InsetMathGrid::addCol(col);
794 void InsetMathHull::delCol(col_type col)
796 if (ncols() <= 1 || !colChangeOK())
798 InsetMathGrid::delCol(col);
802 docstring InsetMathHull::nicelabel(row_type row) const
807 return from_ascii("(#)");
808 return '(' + label_[row]->screenLabel() + from_ascii(", #)");
812 void InsetMathHull::glueall()
815 for (idx_type i = 0; i < nargs(); ++i)
817 *this = InsetMathHull(hullSimple, &buffer());
823 void InsetMathHull::splitTo2Cols()
825 LASSERT(ncols() == 1, /**/);
826 InsetMathGrid::addCol(1);
827 for (row_type row = 0; row < nrows(); ++row) {
828 idx_type const i = 2 * row;
829 pos_type pos = firstRelOp(cell(i));
830 cell(i + 1) = MathData(cell(i).begin() + pos, cell(i).end());
831 cell(i).erase(pos, cell(i).size());
836 void InsetMathHull::splitTo3Cols()
838 LASSERT(ncols() < 3, /**/);
841 InsetMathGrid::addCol(2);
842 for (row_type row = 0; row < nrows(); ++row) {
843 idx_type const i = 3 * row + 1;
844 if (cell(i).size()) {
845 cell(i + 1) = MathData(cell(i).begin() + 1, cell(i).end());
846 cell(i).erase(1, cell(i).size());
852 void InsetMathHull::changeCols(col_type cols)
856 else if (ncols() < cols) {
862 while (ncols() < cols)
863 InsetMathGrid::addCol(ncols());
869 for (row_type row = 0; row < nrows(); ++row) {
870 idx_type const i = row * ncols();
871 for (col_type col = cols; col < ncols(); ++col) {
872 cell(i + cols - 1).append(cell(i + col));
876 while (ncols() > cols) {
877 InsetMathGrid::delCol(ncols() - 1);
882 HullType InsetMathHull::getType() const
888 void InsetMathHull::setType(HullType type)
895 void InsetMathHull::mutate(HullType newtype)
897 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
899 // we try to move along the chain
900 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
902 // +-------------------------------------+
903 // we use eqnarray as intermediate type for mutations that are not
904 // directly supported because it handles labels and numbering for
907 if (newtype == type_) {
911 else if (newtype < hullNone) {
916 else if (type_ == hullNone) {
922 else if (type_ == hullSimple) {
923 if (newtype == hullNone) {
927 setType(hullEquation);
933 else if (type_ == hullEquation) {
934 if (newtype < type_) {
938 } else if (newtype == hullEqnArray) {
939 // split it "nicely" on the first relop
941 setType(hullEqnArray);
942 } else if (newtype == hullMultline || newtype == hullGather) {
952 else if (type_ == hullEqnArray) {
953 if (newtype < type_) {
954 // set correct (no)numbering
956 for (row_type row = 0; row < nrows(); ++row) {
963 // set first non-empty label
964 for (row_type row = 0; row < nrows(); ++row) {
966 label_[0] = label_[row];
973 } else { // align & Co.
980 else if (type_ == hullAlign || type_ == hullAlignAt ||
981 type_ == hullXAlignAt || type_ == hullFlAlign) {
982 if (newtype < hullAlign) {
984 setType(hullEqnArray);
986 } else if (newtype == hullGather || newtype == hullMultline) {
989 } else if (newtype == hullXXAlignAt) {
990 for (row_type row = 0; row < nrows(); ++row)
991 numbered(row, false);
998 else if (type_ == hullXXAlignAt) {
999 for (row_type row = 0; row < nrows(); ++row)
1000 numbered(row, false);
1001 if (newtype < hullAlign) {
1003 setType(hullEqnArray);
1005 } else if (newtype == hullGather || newtype == hullMultline) {
1013 else if (type_ == hullMultline || type_ == hullGather) {
1014 if (newtype == hullGather || newtype == hullMultline)
1016 else if (newtype == hullAlign || newtype == hullFlAlign ||
1017 newtype == hullAlignAt || newtype == hullXAlignAt) {
1020 } else if (newtype == hullXXAlignAt) {
1022 for (row_type row = 0; row < nrows(); ++row)
1023 numbered(row, false);
1027 setType(hullEqnArray);
1033 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1034 << "' to '" << to_utf8(hullName(newtype))
1035 << "' not implemented" << endl;
1040 docstring InsetMathHull::eolString(row_type row, bool fragile) const
1043 if (numberedType()) {
1044 if (label_[row] && !nonum_[row])
1045 res += "\\label{" + label_[row]->getParam("name") + '}';
1046 if (nonum_[row] && (type_ != hullMultline))
1047 res += "\\nonumber ";
1049 return res + InsetMathGrid::eolString(row, fragile);
1053 void InsetMathHull::write(WriteStream & os) const
1055 ModeSpecifier specifier(os, MATH_MODE);
1057 InsetMathGrid::write(os);
1062 void InsetMathHull::normalize(NormalStream & os) const
1064 os << "[formula " << hullName(type_) << ' ';
1065 InsetMathGrid::normalize(os);
1070 void InsetMathHull::mathmlize(MathStream & os) const
1072 InsetMathGrid::mathmlize(os);
1076 void InsetMathHull::infoize(odocstream & os) const
1078 os << "Type: " << hullName(type_);
1082 void InsetMathHull::check() const
1084 LASSERT(nonum_.size() == nrows(), /**/);
1085 LASSERT(label_.size() == nrows(), /**/);
1089 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1093 idocstringstream iss(func.argument());
1094 iss >> dlang >> extra;
1096 extra = from_ascii("noextra");
1097 string const lang = to_ascii(dlang);
1099 // FIXME: temporarily disabled
1100 //if (cur.selection()) {
1103 // lyxerr << "use selection: " << ar << endl;
1104 // insert(pipeThroughExtern(lang, extra, ar));
1109 eq.push_back(MathAtom(new InsetMathChar('=')));
1111 // go to first item in line
1112 cur.idx() -= cur.idx() % ncols();
1115 if (getType() == hullSimple) {
1116 size_type pos = cur.cell().find_last(eq);
1118 if (cur.inMathed() && cur.selection()) {
1119 asArray(grabAndEraseSelection(cur), ar);
1120 } else if (pos == cur.cell().size()) {
1122 lyxerr << "use whole cell: " << ar << endl;
1124 ar = MathData(cur.cell().begin() + pos + 1, cur.cell().end());
1125 lyxerr << "use partial cell form pos: " << pos << endl;
1127 cur.cell().append(eq);
1128 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1129 cur.pos() = cur.lastpos();
1133 if (getType() == hullEquation) {
1134 lyxerr << "use equation inset" << endl;
1135 mutate(hullEqnArray);
1136 MathData & ar = cur.cell();
1137 lyxerr << "use cell: " << ar << endl;
1141 cur.cell() = pipeThroughExtern(lang, extra, ar);
1142 // move to end of line
1143 cur.pos() = cur.lastpos();
1148 lyxerr << "use eqnarray" << endl;
1149 cur.idx() += 2 - cur.idx() % ncols();
1151 MathData ar = cur.cell();
1152 lyxerr << "use cell: " << ar << endl;
1153 // FIXME: temporarily disabled
1159 cur.cell() = pipeThroughExtern(lang, extra, ar);
1160 cur.pos() = cur.lastpos();
1165 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1167 //lyxerr << "action: " << cmd.action << endl;
1168 switch (cmd.action) {
1170 case LFUN_FINISHED_BACKWARD:
1171 case LFUN_FINISHED_FORWARD:
1172 case LFUN_FINISHED_RIGHT:
1173 case LFUN_FINISHED_LEFT:
1174 //lyxerr << "action: " << cmd.action << endl;
1175 InsetMathGrid::doDispatch(cur, cmd);
1179 case LFUN_BREAK_PARAGRAPH:
1180 // just swallow this
1183 case LFUN_NEWLINE_INSERT:
1184 // some magic for the common case
1185 if (type_ == hullSimple || type_ == hullEquation) {
1186 cur.recordUndoInset();
1188 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1189 mutate(align ? hullAlign : hullEqnArray);
1190 cur.idx() = nrows() * ncols() - 1;
1191 cur.pos() = cur.lastpos();
1193 InsetMathGrid::doDispatch(cur, cmd);
1196 case LFUN_MATH_NUMBER_TOGGLE: {
1197 //lyxerr << "toggling all numbers" << endl;
1198 cur.recordUndoInset();
1199 bool old = numberedType();
1200 if (type_ == hullMultline)
1201 numbered(nrows() - 1, !old);
1203 for (row_type row = 0; row < nrows(); ++row)
1204 numbered(row, !old);
1206 cur.message(old ? _("No number") : _("Number"));
1210 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1211 cur.recordUndoInset();
1212 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1213 bool old = numbered(r);
1214 cur.message(old ? _("No number") : _("Number"));
1219 case LFUN_LABEL_INSERT: {
1220 cur.recordUndoInset();
1221 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1222 docstring old_label = label(r);
1223 docstring const default_label = from_ascii(
1224 (lyxrc.label_init_length >= 0) ? "eq:" : "");
1225 if (old_label.empty())
1226 old_label = default_label;
1228 InsetCommandParams p(LABEL_CODE);
1229 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1230 string const data = InsetCommand::params2string("label", p);
1232 if (cmd.argument().empty())
1233 cur.bv().showDialog("label", data);
1235 FuncRequest fr(LFUN_INSET_INSERT, data);
1241 case LFUN_LABEL_COPY_AS_REF: {
1243 if (cmd.argument().empty() && &cur.inset() == this)
1244 // if there is no argument and we're inside math, we retrieve
1245 // the row number from the cursor position.
1246 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1248 // if there is an argument, find the corresponding label, else
1249 // check whether there is at least one label.
1250 for (row = 0; row != nrows(); ++row)
1251 if (!nonum_[row] && label_[row]
1252 && (cmd.argument().empty() || label(row) == cmd.argument()))
1259 InsetCommandParams p(REF_CODE, "ref");
1260 p["reference"] = label(row);
1261 cap::clearSelection();
1262 cap::copyInset(cur, new InsetRef(*cur.buffer(), p), label(row));
1266 case LFUN_WORD_DELETE_FORWARD:
1267 case LFUN_CHAR_DELETE_FORWARD:
1268 if (col(cur.idx()) + 1 == ncols()
1269 && cur.pos() == cur.lastpos()
1270 && !cur.selection()) {
1271 if (!label(row(cur.idx())).empty()) {
1272 cur.recordUndoInset();
1273 label(row(cur.idx()), docstring());
1274 } else if (numbered(row(cur.idx()))) {
1275 cur.recordUndoInset();
1276 numbered(row(cur.idx()), false);
1278 InsetMathGrid::doDispatch(cur, cmd);
1282 InsetMathGrid::doDispatch(cur, cmd);
1287 case LFUN_INSET_INSERT: {
1288 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1289 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1290 string const name = cmd.getArg(0);
1291 if (name == "label") {
1292 InsetCommandParams p(LABEL_CODE);
1293 InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1294 docstring str = p["name"];
1295 cur.recordUndoInset();
1296 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1300 docstring old = label(r);
1303 // The label will take care of the reference update.
1307 // Newly created inset so initialize it.
1308 label_[r]->initView();
1313 InsetMathGrid::doDispatch(cur, cmd);
1317 case LFUN_MATH_EXTERN:
1318 cur.recordUndoInset();
1322 case LFUN_MATH_MUTATE: {
1323 cur.recordUndoInset();
1324 row_type row = cur.row();
1325 col_type col = cur.col();
1326 mutate(hullType(cmd.argument()));
1327 cur.idx() = row * ncols() + col;
1328 if (cur.idx() > cur.lastidx()) {
1329 cur.idx() = cur.lastidx();
1330 cur.pos() = cur.lastpos();
1332 if (cur.pos() > cur.lastpos())
1333 cur.pos() = cur.lastpos();
1335 // FIXME: find some more clever handling of the selection,
1336 // i.e. preserve it.
1337 cur.clearSelection();
1338 //cur.dispatched(FINISHED);
1342 case LFUN_MATH_DISPLAY: {
1343 cur.recordUndoInset();
1344 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1346 cur.pos() = cur.lastpos();
1347 //cur.dispatched(FINISHED);
1352 InsetMathGrid::doDispatch(cur, cmd);
1358 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1359 FuncStatus & status) const
1361 switch (cmd.action) {
1362 case LFUN_FINISHED_BACKWARD:
1363 case LFUN_FINISHED_FORWARD:
1364 case LFUN_FINISHED_RIGHT:
1365 case LFUN_FINISHED_LEFT:
1368 case LFUN_NEWLINE_INSERT:
1369 case LFUN_MATH_EXTERN:
1370 case LFUN_MATH_DISPLAY:
1372 status.setEnabled(true);
1375 case LFUN_MATH_MUTATE: {
1376 HullType ht = hullType(cmd.argument());
1377 status.setOnOff(type_ == ht);
1378 status.setEnabled(true);
1382 case LFUN_MATH_NUMBER_TOGGLE:
1383 // FIXME: what is the right test, this or the one of
1385 status.setEnabled(display());
1386 status.setOnOff(numberedType());
1389 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1390 // FIXME: what is the right test, this or the one of
1392 bool const enable = (type_ == hullMultline)
1393 ? (nrows() - 1 == cur.row())
1394 : display() != Inline && nrows() > 1;
1395 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1396 status.setEnabled(enable);
1397 status.setOnOff(enable && numbered(r));
1401 case LFUN_LABEL_INSERT:
1402 status.setEnabled(type_ != hullSimple);
1405 case LFUN_LABEL_COPY_AS_REF: {
1406 bool enabled = false;
1408 if (cmd.argument().empty() && &cur.inset() == this) {
1409 // if there is no argument and we're inside math, we retrieve
1410 // the row number from the cursor position.
1411 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1412 enabled = numberedType() && label_[row] && !nonum_[row];
1414 // if there is an argument, find the corresponding label, else
1415 // check whether there is at least one label.
1416 for (row_type row = 0; row != nrows(); ++row) {
1417 if (!nonum_[row] && label_[row] &&
1418 (cmd.argument().empty() || label(row) == cmd.argument())) {
1424 status.setEnabled(enabled);
1428 case LFUN_INSET_INSERT:
1429 if (cmd.getArg(0) == "label") {
1430 status.setEnabled(type_ != hullSimple);
1433 return InsetMathGrid::getStatus(cur, cmd, status);
1435 case LFUN_TABULAR_FEATURE: {
1436 istringstream is(to_utf8(cmd.argument()));
1440 && (s == "append-row"
1441 || s == "delete-row"
1442 || s == "copy-row")) {
1443 status.message(bformat(
1444 from_utf8(N_("Can't change number of rows in '%1$s'")),
1446 status.setEnabled(false);
1450 && (s == "append-column"
1451 || s == "delete-column"
1452 || s == "copy-column")) {
1453 status.message(bformat(
1454 from_utf8(N_("Can't change number of columns in '%1$s'")),
1456 status.setEnabled(false);
1459 if ((type_ == hullSimple
1460 || type_ == hullEquation
1461 || type_ == hullNone) &&
1462 (s == "add-hline-above" || s == "add-hline-below")) {
1463 status.message(bformat(
1464 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1466 status.setEnabled(false);
1469 if (s == "add-vline-left" || s == "add-vline-right") {
1470 status.message(bformat(
1471 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1473 status.setEnabled(false);
1476 if (s == "valign-top" || s == "valign-middle"
1477 || s == "valign-bottom" || s == "align-left"
1478 || s == "align-center" || s == "align-right") {
1479 status.setEnabled(false);
1482 return InsetMathGrid::getStatus(cur, cmd, status);
1486 return InsetMathGrid::getStatus(cur, cmd, status);
1489 // This cannot really happen, but inserted to shut-up gcc
1490 return InsetMathGrid::getStatus(cur, cmd, status);
1494 /////////////////////////////////////////////////////////////////////
1498 // simply scrap this function if you want
1499 void InsetMathHull::mutateToText()
1502 // translate to latex
1504 latex(os, false, false);
1505 string str = os.str();
1508 Text * lt = view_->cursor().innerText();
1509 string::const_iterator cit = str.begin();
1510 string::const_iterator end = str.end();
1511 for (; cit != end; ++cit)
1512 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1515 //dispatch(LFUN_ESCAPE);
1520 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1521 docstring const & font)
1523 // this whole function is a hack and won't work for incremental font
1526 if (cur.inset().asInsetMath()->name() == font)
1527 cur.handleFont(to_utf8(font));
1529 cur.handleNest(createInsetMath(font));
1535 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1540 font.fromString(to_utf8(arg), b);
1541 if (font.fontInfo().color() != Color_inherit) {
1542 MathAtom at = MathAtom(new InsetMathColor(true, font.fontInfo().color()));
1543 cur.handleNest(at, 0);
1548 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1551 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1552 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1553 enter_front ? idxFirst(cur) : idxLast(cur);
1554 // The inset formula dimension is not necessarily the same as the
1555 // one of the instant preview image, so we have to indicate to the
1556 // BufferView that a metrics update is needed.
1557 cur.updateFlags(Update::Force);
1561 void InsetMathHull::revealCodes(Cursor & cur) const
1563 if (!cur.inMathed())
1565 odocstringstream os;
1567 cur.message(os.str());
1569 // write something to the minibuffer
1570 // translate to latex
1574 string str = os.str();
1576 string::size_type pos = 0;
1578 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1581 else if (*it == '\0') {
1583 pos = it - str.begin();
1589 res = res.substr(pos - 30);
1590 if (res.size() > 60)
1591 res = res.substr(0, 60);
1597 /////////////////////////////////////////////////////////////////////
1601 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1604 // FIXME: completely broken
1605 static InsetMathHull * lastformula = 0;
1606 static CursorBase current = DocIterator(ibegin(nucleus()));
1608 static string laststr;
1610 if (lastformula != this || laststr != str) {
1611 //lyxerr << "reset lastformula to " << this << endl;
1614 current = ibegin(nucleus());
1616 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1620 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1622 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1623 CursorSlice & top = it.back();
1624 MathData const & a = top.asInsetMath()->cell(top.idx_);
1625 if (a.matchpart(ar, top.pos_)) {
1626 bv->cursor().setSelection(it, ar.size());
1628 top.pos_ += ar.size();
1634 //lyxerr << "not found!" << endl;
1641 void InsetMathHull::write(ostream & os) const
1643 odocstringstream oss;
1644 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1647 os << to_utf8(oss.str());
1651 void InsetMathHull::read(Lexer & lex)
1654 mathed_parse_normal(at, lex, Parse::NORMAL, &buffer());
1655 operator=(*at->asHullInset());
1659 bool InsetMathHull::readQuiet(Lexer & lex)
1662 bool success = mathed_parse_normal(at, lex, Parse::QUIET, &buffer());
1664 operator=(*at->asHullInset());
1669 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1671 if (0 && display()) {
1675 TextPainter tpain(dim.width(), dim.height());
1676 drawT(tpain, 0, dim.ascent());
1678 // reset metrics cache to "real" values
1680 return tpain.textheight();
1682 odocstringstream oss;
1683 Encoding const * const enc = encodings.fromLyXName("utf8");
1684 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1686 if (type_ == hullRegexp)
1690 docstring const str = oss.str();
1697 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1702 if (getType() == hullSimple)
1703 name = from_ascii("inlineequation");
1705 name = from_ascii("informalequation");
1707 docstring bname = name;
1708 if (!label(0).empty())
1709 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1711 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1713 odocstringstream ls;
1714 if (runparams.flavor == OutputParams::XML) {
1715 ms << MTag("alt role='tex' ");
1716 // Workaround for db2latex: db2latex always includes equations with
1717 // \ensuremath{} or \begin{display}\end{display}
1718 // so we strip LyX' math environment
1719 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1720 InsetMathGrid::write(wi);
1721 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1726 InsetMathGrid::mathmlize(ms);
1729 ms << MTag("alt role='tex'");
1730 res = latex(ls, runparams);
1731 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1735 ms << from_ascii("<graphic fileref=\"eqn/");
1736 if (!label(0).empty())
1737 ms << sgml::cleanID(buffer(), runparams, label(0));
1739 ms << sgml::uniqueID(from_ascii("anon"));
1741 if (runparams.flavor == OutputParams::XML)
1742 ms << from_ascii("\"/>");
1744 ms << from_ascii("\">");
1746 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1748 return ms.line() + res;
1752 void InsetMathHull::tocString(odocstream & os) const
1754 plaintext(os, OutputParams(0));
1758 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1760 return from_ascii("context-math");