2 * \file InsetMathHull.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 #include "InsetMathHull.h"
15 #include "InsetMathChar.h"
16 #include "InsetMathColor.h"
17 #include "MathExtern.h"
18 #include "MathFactory.h"
19 #include "MathStream.h"
20 #include "MathSupport.h"
23 #include "BufferParams.h"
24 #include "BufferView.h"
25 #include "CutAndPaste.h"
27 #include "FuncRequest.h"
28 #include "FuncStatus.h"
29 #include "LaTeXFeatures.h"
31 #include "MacroTable.h"
32 #include "output_xhtml.h"
34 #include "TextPainter.h"
35 #include "TocBackend.h"
37 #include "insets/InsetLabel.h"
38 #include "insets/InsetRef.h"
39 #include "insets/RenderPreview.h"
41 #include "graphics/PreviewImage.h"
42 #include "graphics/PreviewLoader.h"
44 #include "frontends/Painter.h"
46 #include "support/lassert.h"
47 #include "support/debug.h"
48 #include "support/gettext.h"
49 #include "support/lstrings.h"
54 using namespace lyx::support;
58 using cap::grabAndEraseSelection;
62 int getCols(HullType type)
79 // returns position of first relation operator in the array
80 // used for "intelligent splitting"
81 size_t firstRelOp(MathData const & ar)
83 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
85 return it - ar.begin();
90 char const * star(bool numbered)
92 return numbered ? "" : "*";
96 } // end anon namespace
99 HullType hullType(docstring const & s)
101 if (s == "none") return hullNone;
102 if (s == "simple") return hullSimple;
103 if (s == "equation") return hullEquation;
104 if (s == "eqnarray") return hullEqnArray;
105 if (s == "align") return hullAlign;
106 if (s == "alignat") return hullAlignAt;
107 if (s == "xalignat") return hullXAlignAt;
108 if (s == "xxalignat") return hullXXAlignAt;
109 if (s == "multline") return hullMultline;
110 if (s == "gather") return hullGather;
111 if (s == "flalign") return hullFlAlign;
112 if (s == "regexp") return hullRegexp;
113 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
118 docstring hullName(HullType type)
121 case hullNone: return from_ascii("none");
122 case hullSimple: return from_ascii("simple");
123 case hullEquation: return from_ascii("equation");
124 case hullEqnArray: return from_ascii("eqnarray");
125 case hullAlign: return from_ascii("align");
126 case hullAlignAt: return from_ascii("alignat");
127 case hullXAlignAt: return from_ascii("xalignat");
128 case hullXXAlignAt: return from_ascii("xxalignat");
129 case hullMultline: return from_ascii("multline");
130 case hullGather: return from_ascii("gather");
131 case hullFlAlign: return from_ascii("flalign");
132 case hullRegexp: return from_ascii("regexp");
134 lyxerr << "unknown hull type '" << type << "'" << endl;
135 return from_ascii("none");
139 static InsetLabel * dummy_pointer = 0;
141 InsetMathHull::InsetMathHull(Buffer * buf)
142 : InsetMathGrid(buf, 1, 1), type_(hullNone), nonum_(1, false),
143 label_(1, dummy_pointer), preview_(new RenderPreview(this))
145 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
146 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
147 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
148 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
155 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
156 : InsetMathGrid(buf, getCols(type), 1), type_(type), nonum_(1, false),
157 label_(1, dummy_pointer), preview_(new RenderPreview(this))
165 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
171 InsetMathHull::~InsetMathHull()
173 for (size_t i = 0; i < label_.size(); ++i)
178 Inset * InsetMathHull::clone() const
180 return new InsetMathHull(*this);
184 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
188 InsetMathGrid::operator=(other);
190 nonum_ = other.nonum_;
191 buffer_ = other.buffer_;
192 for (size_t i = 0; i < label_.size(); ++i)
194 label_ = other.label_;
195 for (size_t i = 0; i != label_.size(); ++i) {
197 label_[i] = new InsetLabel(*label_[i]);
199 preview_.reset(new RenderPreview(*other.preview_, this));
205 void InsetMathHull::setBuffer(Buffer & buffer)
207 InsetMathGrid::setBuffer(buffer);
209 for (size_t i = 0; i != label_.size(); ++i) {
211 label_[i]->setBuffer(buffer);
216 void InsetMathHull::updateLabels(ParIterator const & it, UpdateType utype)
219 //FIXME: buffer_ should be set at creation for this inset! Problem is
220 // This inset is created at too many places (see Parser::parse1() in
224 for (size_t i = 0; i != label_.size(); ++i) {
226 label_[i]->updateLabels(it, utype);
231 void InsetMathHull::addToToc(DocIterator const & pit)
234 //FIXME: buffer_ should be set at creation for this inset! Problem is
235 // This inset is created at too many places (see Parser::parse1() in
240 Toc & toc = buffer().tocBackend().toc("equation");
242 for (row_type row = 0; row != nrows(); ++row) {
246 label_[row]->addToToc(pit);
247 toc.push_back(TocItem(pit, 0, nicelabel(row)));
252 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
258 return InsetMathNest::editXY(cur, x, y);
262 InsetMath::mode_type InsetMathHull::currentMode() const
264 if (type_ == hullNone)
265 return UNDECIDED_MODE;
266 // definitely math mode ...
271 bool InsetMathHull::idxFirst(Cursor & cur) const
279 bool InsetMathHull::idxLast(Cursor & cur) const
281 cur.idx() = nargs() - 1;
282 cur.pos() = cur.lastpos();
287 char InsetMathHull::defaultColAlign(col_type col)
289 if (type_ == hullEqnArray)
291 if (type_ == hullGather)
293 if (type_ >= hullAlign)
294 return "rl"[col & 1];
299 int InsetMathHull::defaultColSpace(col_type col)
301 if (type_ == hullAlign || type_ == hullAlignAt)
303 if (type_ == hullXAlignAt)
304 return (col & 1) ? 20 : 0;
305 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
306 return (col & 1) ? 40 : 0;
311 docstring InsetMathHull::standardFont() const
313 return from_ascii(type_ == hullNone ? "lyxnochange" : "mathnormal");
317 bool InsetMathHull::previewState(BufferView * bv) const
319 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
320 graphics::PreviewImage const * pimage =
321 preview_->getPreviewImage(bv->buffer());
322 return pimage && pimage->image();
328 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
330 if (previewState(mi.base.bv)) {
331 preview_->metrics(mi, dim);
332 // insert a one pixel gap in front of the formula
335 dim.des += displayMargin();
336 // Cache the inset dimension.
337 setDimCache(mi, dim);
341 FontSetChanger dummy1(mi.base, standardFont());
342 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
344 // let the cells adjust themselves
345 InsetMathGrid::metrics(mi, dim);
348 dim.asc += displayMargin();
349 dim.des += displayMargin();
352 if (numberedType()) {
353 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
355 for (row_type row = 0; row < nrows(); ++row)
356 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
362 // make it at least as high as the current font
365 math_font_max_dim(mi.base.font, asc, des);
366 dim.asc = max(dim.asc, asc);
367 dim.des = max(dim.des, des);
368 // Cache the inset dimension.
369 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
370 setDimCache(mi, dim);
374 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
376 if (previewState(pi.base.bv))
377 return graphics::PreviewLoader::backgroundColor();
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(DocIterator const & inset_pos,
471 graphics::PreviewLoader & /*ploader*/) const
473 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
474 preparePreview(inset_pos);
479 void InsetMathHull::preparePreview(DocIterator const & pos) const
481 Buffer const * buffer = pos.buffer();
483 // collect macros at this position
485 buffer->listMacroNames(macros);
486 MacroNameSet::iterator it = macros.begin();
487 MacroNameSet::iterator end = macros.end();
488 odocstringstream macro_preamble;
489 for (; it != end; ++it) {
490 MacroData const * data = buffer->getMacro(*it, pos, true);
492 data->write(macro_preamble, true);
493 macro_preamble << endl;
497 docstring const snippet = macro_preamble.str() + latexString(*this);
498 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
499 preview_->addPreview(snippet, *buffer);
503 void InsetMathHull::reloadPreview(DocIterator const & pos) const
506 preview_->startLoading(*pos.buffer());
510 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
512 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
514 cur.updateFlags(Update::Force);
520 docstring InsetMathHull::label(row_type row) const
522 LASSERT(row < nrows(), /**/);
523 if (InsetLabel * il = label_[row])
524 return il->screenLabel();
529 void InsetMathHull::label(row_type row, docstring const & label)
531 //lyxerr << "setting label '" << label << "' for row " << row << endl;
535 label_[row] = dummy_pointer;
536 // We need an update of the Buffer reference cache.
537 // This is achieved by updateLabels().
539 buffer().updateLabels();
542 label_[row]->updateCommand(label);
544 label_[row]->setParam("name", label);
548 InsetCommandParams p(LABEL_CODE);
550 label_[row] = new InsetLabel(buffer_, p);
552 label_[row]->setBuffer(buffer());
556 void InsetMathHull::numbered(row_type row, bool num)
559 if (nonum_[row] && label_[row]) {
563 // The buffer is set at the end of readInset.
564 // When parsing the inset, buffer_ is 0.
567 // We need an update of the Buffer reference cache.
568 // This is achieved by updateLabels().
569 buffer().updateLabels();
574 bool InsetMathHull::numbered(row_type row) const
580 bool InsetMathHull::ams() const
582 return type_ == hullAlign
583 || type_ == hullFlAlign
584 || type_ == hullMultline
585 || type_ == hullGather
586 || type_ == hullAlignAt
587 || type_ == hullXAlignAt
588 || type_ == hullXXAlignAt;
592 Inset::DisplayType InsetMathHull::display() const
594 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
599 bool InsetMathHull::numberedType() const
601 if (type_ == hullNone)
603 if (type_ == hullSimple)
605 if (type_ == hullXXAlignAt)
607 if (type_ == hullRegexp)
609 for (row_type row = 0; row < nrows(); ++row)
616 void InsetMathHull::validate(LaTeXFeatures & features) const
619 features.require("amsmath");
621 // Validation is necessary only if not using AMS math.
622 // To be safe, we will always run mathedvalidate.
623 //if (features.amsstyle)
626 //features.binom = true;
628 InsetMathGrid::validate(features);
632 void InsetMathHull::header_write(WriteStream & os) const
634 bool n = numberedType();
648 os << "\\begin{equation" << star(n) << "}\n";
658 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
663 os << "\\begin{" << hullName(type_) << star(n) << '}'
664 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
668 os << "\\begin{" << hullName(type_) << '}'
669 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
677 os << "\\begin{unknown" << star(n) << '}';
683 void InsetMathHull::footer_write(WriteStream & os) const
685 bool n = numberedType();
698 os << "\\end{equation" << star(n) << "}\n";
710 os << "\\end{" << hullName(type_) << star(n) << "}\n";
714 os << "\\end{" << hullName(type_) << "}\n";
722 os << "\\end{unknown" << star(n) << '}';
728 bool InsetMathHull::rowChangeOK() const
731 type_ == hullEqnArray || type_ == hullAlign ||
732 type_ == hullFlAlign || type_ == hullAlignAt ||
733 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
734 type_ == hullGather || type_ == hullMultline;
738 bool InsetMathHull::colChangeOK() const
741 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
742 type_ == hullXAlignAt || type_ == hullXXAlignAt;
746 void InsetMathHull::addRow(row_type row)
751 bool numbered = numberedType();
753 if (type_ == hullMultline) {
754 if (row + 1 == nrows()) {
761 nonum_.insert(nonum_.begin() + row + 1, !numbered);
762 label_.insert(label_.begin() + row + 1, dummy_pointer);
765 InsetMathGrid::addRow(row);
769 void InsetMathHull::swapRow(row_type row)
773 if (row + 1 == nrows())
775 // gcc implements the standard std::vector<bool> which is *not* a container:
776 // http://www.gotw.ca/publications/N1185.pdf
777 // As a results, it doesn't like this:
778 // swap(nonum_[row], nonum_[row + 1]);
779 // so we do it manually:
780 bool const b = nonum_[row];
781 nonum_[row] = nonum_[row + 1];
783 swap(label_[row], label_[row + 1]);
784 InsetMathGrid::swapRow(row);
788 void InsetMathHull::delRow(row_type row)
790 if (nrows() <= 1 || !rowChangeOK())
792 if (row + 1 == nrows() && type_ == hullMultline) {
793 bool const b = nonum_[row - 1];
794 nonum_[row - 1] = nonum_[row];
796 swap(label_[row - 1], label_[row]);
797 InsetMathGrid::delRow(row);
800 InsetMathGrid::delRow(row);
801 // The last dummy row has no number info nor a label.
802 // Test nrows() + 1 because we have already erased the row.
803 if (row == nrows() + 1)
805 nonum_.erase(nonum_.begin() + row);
807 label_.erase(label_.begin() + row);
811 void InsetMathHull::addCol(col_type col)
815 InsetMathGrid::addCol(col);
819 void InsetMathHull::delCol(col_type col)
821 if (ncols() <= 1 || !colChangeOK())
823 InsetMathGrid::delCol(col);
827 docstring InsetMathHull::nicelabel(row_type row) const
832 return from_ascii("(#)");
833 return '(' + label_[row]->screenLabel() + from_ascii(", #)");
837 void InsetMathHull::glueall()
840 for (idx_type i = 0; i < nargs(); ++i)
842 *this = InsetMathHull(buffer_, hullSimple);
848 void InsetMathHull::splitTo2Cols()
850 LASSERT(ncols() == 1, /**/);
851 InsetMathGrid::addCol(1);
852 for (row_type row = 0; row < nrows(); ++row) {
853 idx_type const i = 2 * row;
854 pos_type pos = firstRelOp(cell(i));
855 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
856 cell(i).erase(pos, cell(i).size());
861 void InsetMathHull::splitTo3Cols()
863 LASSERT(ncols() < 3, /**/);
866 InsetMathGrid::addCol(2);
867 for (row_type row = 0; row < nrows(); ++row) {
868 idx_type const i = 3 * row + 1;
869 if (cell(i).size()) {
870 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
871 cell(i).erase(1, cell(i).size());
877 void InsetMathHull::changeCols(col_type cols)
881 else if (ncols() < cols) {
887 while (ncols() < cols)
888 InsetMathGrid::addCol(ncols());
894 for (row_type row = 0; row < nrows(); ++row) {
895 idx_type const i = row * ncols();
896 for (col_type col = cols; col < ncols(); ++col) {
897 cell(i + cols - 1).append(cell(i + col));
901 while (ncols() > cols) {
902 InsetMathGrid::delCol(ncols() - 1);
907 HullType InsetMathHull::getType() const
913 void InsetMathHull::setType(HullType type)
920 void InsetMathHull::mutate(HullType newtype)
922 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
924 // we try to move along the chain
925 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
927 // +-------------------------------------+
928 // we use eqnarray as intermediate type for mutations that are not
929 // directly supported because it handles labels and numbering for
932 if (newtype == type_) {
936 else if (newtype < hullNone) {
941 else if (type_ == hullNone) {
947 else if (type_ == hullSimple) {
948 if (newtype == hullNone) {
952 setType(hullEquation);
958 else if (type_ == hullEquation) {
959 if (newtype < type_) {
963 } else if (newtype == hullEqnArray) {
964 // split it "nicely" on the first relop
966 setType(hullEqnArray);
967 } else if (newtype == hullMultline || newtype == hullGather) {
977 else if (type_ == hullEqnArray) {
978 if (newtype < type_) {
979 // set correct (no)numbering
981 for (row_type row = 0; row < nrows(); ++row) {
988 // set first non-empty label
989 for (row_type row = 0; row < nrows(); ++row) {
991 label_[0] = label_[row];
998 } else { // align & Co.
1005 else if (type_ == hullAlign || type_ == hullAlignAt ||
1006 type_ == hullXAlignAt || type_ == hullFlAlign) {
1007 if (newtype < hullAlign) {
1009 setType(hullEqnArray);
1011 } else if (newtype == hullGather || newtype == hullMultline) {
1014 } else if (newtype == hullXXAlignAt) {
1015 for (row_type row = 0; row < nrows(); ++row)
1016 numbered(row, false);
1023 else if (type_ == hullXXAlignAt) {
1024 for (row_type row = 0; row < nrows(); ++row)
1025 numbered(row, false);
1026 if (newtype < hullAlign) {
1028 setType(hullEqnArray);
1030 } else if (newtype == hullGather || newtype == hullMultline) {
1038 else if (type_ == hullMultline || type_ == hullGather) {
1039 if (newtype == hullGather || newtype == hullMultline)
1041 else if (newtype == hullAlign || newtype == hullFlAlign ||
1042 newtype == hullAlignAt || newtype == hullXAlignAt) {
1045 } else if (newtype == hullXXAlignAt) {
1047 for (row_type row = 0; row < nrows(); ++row)
1048 numbered(row, false);
1052 setType(hullEqnArray);
1058 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1059 << "' to '" << to_utf8(hullName(newtype))
1060 << "' not implemented" << endl;
1065 docstring InsetMathHull::eolString(row_type row, bool fragile) const
1068 if (numberedType()) {
1069 if (label_[row] && !nonum_[row])
1070 res += "\\label{" + label_[row]->getParam("name") + '}';
1071 if (nonum_[row] && (type_ != hullMultline))
1072 res += "\\nonumber ";
1074 return res + InsetMathGrid::eolString(row, fragile);
1078 void InsetMathHull::write(WriteStream & os) const
1080 ModeSpecifier specifier(os, MATH_MODE);
1082 InsetMathGrid::write(os);
1087 void InsetMathHull::normalize(NormalStream & os) const
1089 os << "[formula " << hullName(type_) << ' ';
1090 InsetMathGrid::normalize(os);
1095 void InsetMathHull::mathmlize(MathStream & os) const
1097 InsetMathGrid::mathmlize(os);
1101 void InsetMathHull::infoize(odocstream & os) const
1103 os << "Type: " << hullName(type_);
1107 void InsetMathHull::check() const
1109 LASSERT(nonum_.size() == nrows(), /**/);
1110 LASSERT(label_.size() == nrows(), /**/);
1114 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1118 idocstringstream iss(func.argument());
1119 iss >> dlang >> extra;
1121 extra = from_ascii("noextra");
1122 string const lang = to_ascii(dlang);
1124 // FIXME: temporarily disabled
1125 //if (cur.selection()) {
1128 // lyxerr << "use selection: " << ar << endl;
1129 // insert(pipeThroughExtern(lang, extra, ar));
1134 eq.push_back(MathAtom(new InsetMathChar('=')));
1136 // go to first item in line
1137 cur.idx() -= cur.idx() % ncols();
1140 if (getType() == hullSimple) {
1141 size_type pos = cur.cell().find_last(eq);
1143 if (cur.inMathed() && cur.selection()) {
1144 asArray(grabAndEraseSelection(cur), ar);
1145 } else if (pos == cur.cell().size()) {
1147 lyxerr << "use whole cell: " << ar << endl;
1149 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1150 lyxerr << "use partial cell form pos: " << pos << endl;
1152 cur.cell().append(eq);
1153 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1154 cur.pos() = cur.lastpos();
1158 if (getType() == hullEquation) {
1159 lyxerr << "use equation inset" << endl;
1160 mutate(hullEqnArray);
1161 MathData & ar = cur.cell();
1162 lyxerr << "use cell: " << ar << endl;
1166 cur.cell() = pipeThroughExtern(lang, extra, ar);
1167 // move to end of line
1168 cur.pos() = cur.lastpos();
1173 lyxerr << "use eqnarray" << endl;
1174 cur.idx() += 2 - cur.idx() % ncols();
1176 MathData ar = cur.cell();
1177 lyxerr << "use cell: " << ar << endl;
1178 // FIXME: temporarily disabled
1184 cur.cell() = pipeThroughExtern(lang, extra, ar);
1185 cur.pos() = cur.lastpos();
1190 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1192 //lyxerr << "action: " << cmd.action << endl;
1193 switch (cmd.action) {
1195 case LFUN_FINISHED_BACKWARD:
1196 case LFUN_FINISHED_FORWARD:
1197 case LFUN_FINISHED_RIGHT:
1198 case LFUN_FINISHED_LEFT:
1199 //lyxerr << "action: " << cmd.action << endl;
1200 InsetMathGrid::doDispatch(cur, cmd);
1204 case LFUN_BREAK_PARAGRAPH:
1205 // just swallow this
1208 case LFUN_NEWLINE_INSERT:
1209 // some magic for the common case
1210 if (type_ == hullSimple || type_ == hullEquation) {
1211 cur.recordUndoInset();
1213 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1214 mutate(align ? hullAlign : hullEqnArray);
1215 cur.idx() = nrows() * ncols() - 1;
1216 cur.pos() = cur.lastpos();
1218 InsetMathGrid::doDispatch(cur, cmd);
1221 case LFUN_MATH_NUMBER_TOGGLE: {
1222 //lyxerr << "toggling all numbers" << endl;
1223 cur.recordUndoInset();
1224 bool old = numberedType();
1225 if (type_ == hullMultline)
1226 numbered(nrows() - 1, !old);
1228 for (row_type row = 0; row < nrows(); ++row)
1229 numbered(row, !old);
1231 cur.message(old ? _("No number") : _("Number"));
1235 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1236 cur.recordUndoInset();
1237 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1238 bool old = numbered(r);
1239 cur.message(old ? _("No number") : _("Number"));
1244 case LFUN_LABEL_INSERT: {
1245 cur.recordUndoInset();
1246 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1247 docstring old_label = label(r);
1248 docstring const default_label = from_ascii(
1249 (lyxrc.label_init_length >= 0) ? "eq:" : "");
1250 if (old_label.empty())
1251 old_label = default_label;
1253 InsetCommandParams p(LABEL_CODE);
1254 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1255 string const data = InsetCommand::params2string("label", p);
1257 if (cmd.argument().empty())
1258 cur.bv().showDialog("label", data);
1260 FuncRequest fr(LFUN_INSET_INSERT, data);
1266 case LFUN_LABEL_COPY_AS_REF: {
1268 if (cmd.argument().empty() && &cur.inset() == this)
1269 // if there is no argument and we're inside math, we retrieve
1270 // the row number from the cursor position.
1271 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1273 // if there is an argument, find the corresponding label, else
1274 // check whether there is at least one label.
1275 for (row = 0; row != nrows(); ++row)
1276 if (!nonum_[row] && label_[row]
1277 && (cmd.argument().empty() || label(row) == cmd.argument()))
1284 InsetCommandParams p(REF_CODE, "ref");
1285 p["reference"] = label(row);
1286 cap::clearSelection();
1287 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1291 case LFUN_WORD_DELETE_FORWARD:
1292 case LFUN_CHAR_DELETE_FORWARD:
1293 if (col(cur.idx()) + 1 == ncols()
1294 && cur.pos() == cur.lastpos()
1295 && !cur.selection()) {
1296 if (!label(row(cur.idx())).empty()) {
1297 cur.recordUndoInset();
1298 label(row(cur.idx()), docstring());
1299 } else if (numbered(row(cur.idx()))) {
1300 cur.recordUndoInset();
1301 numbered(row(cur.idx()), false);
1303 InsetMathGrid::doDispatch(cur, cmd);
1307 InsetMathGrid::doDispatch(cur, cmd);
1312 case LFUN_INSET_INSERT: {
1313 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1314 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1315 string const name = cmd.getArg(0);
1316 if (name == "label") {
1317 InsetCommandParams p(LABEL_CODE);
1318 InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1319 docstring str = p["name"];
1320 cur.recordUndoInset();
1321 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1325 docstring old = label(r);
1328 // The label will take care of the reference update.
1332 // Newly created inset so initialize it.
1333 label_[r]->initView();
1338 InsetMathGrid::doDispatch(cur, cmd);
1342 case LFUN_MATH_EXTERN:
1343 cur.recordUndoInset();
1347 case LFUN_MATH_MUTATE: {
1348 cur.recordUndoInset();
1349 row_type row = cur.row();
1350 col_type col = cur.col();
1351 mutate(hullType(cmd.argument()));
1352 cur.idx() = row * ncols() + col;
1353 if (cur.idx() > cur.lastidx()) {
1354 cur.idx() = cur.lastidx();
1355 cur.pos() = cur.lastpos();
1357 if (cur.pos() > cur.lastpos())
1358 cur.pos() = cur.lastpos();
1360 // FIXME: find some more clever handling of the selection,
1361 // i.e. preserve it.
1362 cur.clearSelection();
1363 //cur.dispatched(FINISHED);
1367 case LFUN_MATH_DISPLAY: {
1368 cur.recordUndoInset();
1369 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1371 cur.pos() = cur.lastpos();
1372 //cur.dispatched(FINISHED);
1377 InsetMathGrid::doDispatch(cur, cmd);
1383 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1384 FuncStatus & status) const
1386 switch (cmd.action) {
1387 case LFUN_FINISHED_BACKWARD:
1388 case LFUN_FINISHED_FORWARD:
1389 case LFUN_FINISHED_RIGHT:
1390 case LFUN_FINISHED_LEFT:
1393 case LFUN_NEWLINE_INSERT:
1394 case LFUN_MATH_EXTERN:
1395 case LFUN_MATH_DISPLAY:
1397 status.setEnabled(true);
1400 case LFUN_MATH_MUTATE: {
1401 HullType ht = hullType(cmd.argument());
1402 status.setOnOff(type_ == ht);
1403 status.setEnabled(true);
1407 case LFUN_MATH_NUMBER_TOGGLE:
1408 // FIXME: what is the right test, this or the one of
1410 status.setEnabled(display());
1411 status.setOnOff(numberedType());
1414 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1415 // FIXME: what is the right test, this or the one of
1417 bool const enable = (type_ == hullMultline)
1418 ? (nrows() - 1 == cur.row())
1419 : display() != Inline && nrows() > 1;
1420 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1421 status.setEnabled(enable);
1422 status.setOnOff(enable && numbered(r));
1426 case LFUN_LABEL_INSERT:
1427 status.setEnabled(type_ != hullSimple);
1430 case LFUN_LABEL_COPY_AS_REF: {
1431 bool enabled = false;
1433 if (cmd.argument().empty() && &cur.inset() == this) {
1434 // if there is no argument and we're inside math, we retrieve
1435 // the row number from the cursor position.
1436 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1437 enabled = numberedType() && label_[row] && !nonum_[row];
1439 // if there is an argument, find the corresponding label, else
1440 // check whether there is at least one label.
1441 for (row_type row = 0; row != nrows(); ++row) {
1442 if (!nonum_[row] && label_[row] &&
1443 (cmd.argument().empty() || label(row) == cmd.argument())) {
1449 status.setEnabled(enabled);
1453 case LFUN_INSET_INSERT:
1454 if (cmd.getArg(0) == "label") {
1455 status.setEnabled(type_ != hullSimple);
1458 return InsetMathGrid::getStatus(cur, cmd, status);
1460 case LFUN_TABULAR_FEATURE: {
1461 istringstream is(to_utf8(cmd.argument()));
1465 && (s == "append-row"
1466 || s == "delete-row"
1467 || s == "copy-row")) {
1468 status.message(bformat(
1469 from_utf8(N_("Can't change number of rows in '%1$s'")),
1471 status.setEnabled(false);
1475 && (s == "append-column"
1476 || s == "delete-column"
1477 || s == "copy-column")) {
1478 status.message(bformat(
1479 from_utf8(N_("Can't change number of columns in '%1$s'")),
1481 status.setEnabled(false);
1484 if ((type_ == hullSimple
1485 || type_ == hullEquation
1486 || type_ == hullNone) &&
1487 (s == "add-hline-above" || s == "add-hline-below")) {
1488 status.message(bformat(
1489 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1491 status.setEnabled(false);
1494 if (s == "add-vline-left" || s == "add-vline-right") {
1495 status.message(bformat(
1496 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1498 status.setEnabled(false);
1501 if (s == "valign-top" || s == "valign-middle"
1502 || s == "valign-bottom" || s == "align-left"
1503 || s == "align-center" || s == "align-right") {
1504 status.setEnabled(false);
1507 return InsetMathGrid::getStatus(cur, cmd, status);
1511 return InsetMathGrid::getStatus(cur, cmd, status);
1514 // This cannot really happen, but inserted to shut-up gcc
1515 return InsetMathGrid::getStatus(cur, cmd, status);
1519 /////////////////////////////////////////////////////////////////////
1523 // simply scrap this function if you want
1524 void InsetMathHull::mutateToText()
1527 // translate to latex
1529 latex(os, false, false);
1530 string str = os.str();
1533 Text * lt = view_->cursor().innerText();
1534 string::const_iterator cit = str.begin();
1535 string::const_iterator end = str.end();
1536 for (; cit != end; ++cit)
1537 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1540 //dispatch(LFUN_ESCAPE);
1545 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1546 docstring const & font)
1548 // this whole function is a hack and won't work for incremental font
1551 if (cur.inset().asInsetMath()->name() == font)
1552 cur.handleFont(to_utf8(font));
1554 cur.handleNest(createInsetMath(font, cur.buffer()));
1560 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1565 font.fromString(to_utf8(arg), b);
1566 if (font.fontInfo().color() != Color_inherit) {
1567 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1568 cur.handleNest(at, 0);
1573 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1576 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1577 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1578 enter_front ? idxFirst(cur) : idxLast(cur);
1579 // The inset formula dimension is not necessarily the same as the
1580 // one of the instant preview image, so we have to indicate to the
1581 // BufferView that a metrics update is needed.
1582 cur.updateFlags(Update::Force);
1586 void InsetMathHull::revealCodes(Cursor & cur) const
1588 if (!cur.inMathed())
1590 odocstringstream os;
1592 cur.message(os.str());
1594 // write something to the minibuffer
1595 // translate to latex
1599 string str = os.str();
1601 string::size_type pos = 0;
1603 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1606 else if (*it == '\0') {
1608 pos = it - str.begin();
1614 res = res.substr(pos - 30);
1615 if (res.size() > 60)
1616 res = res.substr(0, 60);
1622 /////////////////////////////////////////////////////////////////////
1626 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1629 // FIXME: completely broken
1630 static InsetMathHull * lastformula = 0;
1631 static CursorBase current = DocIterator(ibegin(nucleus()));
1633 static string laststr;
1635 if (lastformula != this || laststr != str) {
1636 //lyxerr << "reset lastformula to " << this << endl;
1639 current = ibegin(nucleus());
1641 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1645 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1647 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1648 CursorSlice & top = it.back();
1649 MathData const & a = top.asInsetMath()->cell(top.idx_);
1650 if (a.matchpart(ar, top.pos_)) {
1651 bv->cursor().setSelection(it, ar.size());
1653 top.pos_ += ar.size();
1659 //lyxerr << "not found!" << endl;
1666 void InsetMathHull::write(ostream & os) const
1668 odocstringstream oss;
1669 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1672 os << to_utf8(oss.str());
1676 void InsetMathHull::read(Lexer & lex)
1679 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1680 operator=(*at->asHullInset());
1684 bool InsetMathHull::readQuiet(Lexer & lex)
1687 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1689 operator=(*at->asHullInset());
1694 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1696 if (0 && display()) {
1700 TextPainter tpain(dim.width(), dim.height());
1701 drawT(tpain, 0, dim.ascent());
1703 // reset metrics cache to "real" values
1705 return tpain.textheight();
1707 odocstringstream oss;
1708 Encoding const * const enc = encodings.fromLyXName("utf8");
1709 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1711 if (type_ == hullRegexp)
1715 docstring const str = oss.str();
1722 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1727 if (getType() == hullSimple)
1728 name = from_ascii("inlineequation");
1730 name = from_ascii("informalequation");
1732 docstring bname = name;
1733 if (!label(0).empty())
1734 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1736 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1738 odocstringstream ls;
1739 if (runparams.flavor == OutputParams::XML) {
1740 ms << MTag("alt role='tex' ");
1741 // Workaround for db2latex: db2latex always includes equations with
1742 // \ensuremath{} or \begin{display}\end{display}
1743 // so we strip LyX' math environment
1744 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1745 InsetMathGrid::write(wi);
1746 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1751 InsetMathGrid::mathmlize(ms);
1754 ms << MTag("alt role='tex'");
1755 res = latex(ls, runparams);
1756 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1760 ms << from_ascii("<graphic fileref=\"eqn/");
1761 if (!label(0).empty())
1762 ms << sgml::cleanID(buffer(), runparams, label(0));
1764 ms << sgml::uniqueID(from_ascii("anon"));
1766 if (runparams.flavor == OutputParams::XML)
1767 ms << from_ascii("\"/>");
1769 ms << from_ascii("\">");
1771 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1773 return ms.line() + res;
1777 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const &) const
1779 if (getType() == hullSimple)
1780 xs << html::StartTag("math", "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1782 xs << html::StartTag("math",
1783 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1784 MathStream ms(xs.os());
1785 InsetMathGrid::mathmlize(ms);
1786 xs << html::EndTag("math");
1791 void InsetMathHull::tocString(odocstream & os) const
1793 plaintext(os, OutputParams(0));
1797 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1799 return from_ascii("context-math");