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);
229 InsetMathGrid::updateLabels(it, utype);
233 void InsetMathHull::addToToc(DocIterator const & pit)
236 //FIXME: buffer_ should be set at creation for this inset! Problem is
237 // This inset is created at too many places (see Parser::parse1() in
242 Toc & toc = buffer().tocBackend().toc("equation");
244 for (row_type row = 0; row != nrows(); ++row) {
248 label_[row]->addToToc(pit);
249 toc.push_back(TocItem(pit, 0, nicelabel(row)));
254 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
260 return InsetMathNest::editXY(cur, x, y);
264 InsetMath::mode_type InsetMathHull::currentMode() const
266 if (type_ == hullNone)
267 return UNDECIDED_MODE;
268 // definitely math mode ...
273 bool InsetMathHull::idxFirst(Cursor & cur) const
281 bool InsetMathHull::idxLast(Cursor & cur) const
283 cur.idx() = nargs() - 1;
284 cur.pos() = cur.lastpos();
289 char InsetMathHull::defaultColAlign(col_type col)
291 if (type_ == hullEqnArray)
293 if (type_ == hullGather)
295 if (type_ >= hullAlign)
296 return "rl"[col & 1];
301 int InsetMathHull::defaultColSpace(col_type col)
303 if (type_ == hullAlign || type_ == hullAlignAt)
305 if (type_ == hullXAlignAt)
306 return (col & 1) ? 20 : 0;
307 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
308 return (col & 1) ? 40 : 0;
313 docstring InsetMathHull::standardFont() const
315 return from_ascii(type_ == hullNone ? "lyxnochange" : "mathnormal");
319 bool InsetMathHull::previewState(BufferView * bv) const
321 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
322 graphics::PreviewImage const * pimage =
323 preview_->getPreviewImage(bv->buffer());
324 return pimage && pimage->image();
330 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
332 if (previewState(mi.base.bv)) {
333 preview_->metrics(mi, dim);
334 // insert a one pixel gap in front of the formula
337 dim.des += displayMargin();
338 // Cache the inset dimension.
339 setDimCache(mi, dim);
343 FontSetChanger dummy1(mi.base, standardFont());
344 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
346 // let the cells adjust themselves
347 InsetMathGrid::metrics(mi, dim);
350 dim.asc += displayMargin();
351 dim.des += displayMargin();
354 if (numberedType()) {
355 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
357 for (row_type row = 0; row < nrows(); ++row)
358 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
364 // make it at least as high as the current font
367 math_font_max_dim(mi.base.font, asc, des);
368 dim.asc = max(dim.asc, asc);
369 dim.des = max(dim.des, des);
370 // Cache the inset dimension.
371 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
372 setDimCache(mi, dim);
376 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
378 if (previewState(pi.base.bv))
379 return graphics::PreviewLoader::backgroundColor();
384 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
386 Dimension const dim = dimension(*pi.base.bv);
387 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
388 dim.asc + dim.des - 1, pi.backgroundColor(this));
392 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
394 use_preview_ = previewState(pi.base.bv);
397 // one pixel gap in front
398 preview_->draw(pi, x + 1, y);
399 setPosCache(pi, x, y);
403 FontSetChanger dummy1(pi.base, standardFont());
404 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
405 InsetMathGrid::draw(pi, x + 1, y);
407 if (numberedType()) {
408 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
409 for (row_type row = 0; row < nrows(); ++row) {
410 int const yy = y + rowinfo_[row].offset_;
411 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
412 docstring const nl = nicelabel(row);
416 setPosCache(pi, x, y);
420 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
423 InsetMathGrid::metricsT(mi, dim);
426 WriteStream wi(os, false, true, WriteStream::wsDefault);
428 dim.wid = os.str().size();
435 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
438 InsetMathGrid::drawT(pain, x, y);
441 WriteStream wi(os, false, true, WriteStream::wsDefault);
443 pain.draw(x, y, os.str().c_str());
448 static docstring latexString(InsetMathHull const & inset)
451 // This has to be static, because a preview snippet or a math
452 // macro containing math in text mode (such as $\text{$\phi$}$ or
453 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
454 // first time as a whole, and the second time only the inner math.
455 // In this last case inset.buffer() would be invalid.
456 static Encoding const * encoding = 0;
457 if (inset.isBufferValid())
458 encoding = &(inset.buffer().params().encoding());
459 WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
465 void InsetMathHull::initUnicodeMath() const
467 // Trigger classification of the unicode symbols in this inset
468 docstring const dummy = latexString(*this);
472 void InsetMathHull::addPreview(DocIterator const & inset_pos,
473 graphics::PreviewLoader & /*ploader*/) const
475 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
476 preparePreview(inset_pos);
481 void InsetMathHull::preparePreview(DocIterator const & pos) const
483 Buffer const * buffer = pos.buffer();
485 // collect macros at this position
487 buffer->listMacroNames(macros);
488 MacroNameSet::iterator it = macros.begin();
489 MacroNameSet::iterator end = macros.end();
490 odocstringstream macro_preamble;
491 for (; it != end; ++it) {
492 MacroData const * data = buffer->getMacro(*it, pos, true);
494 data->write(macro_preamble, true);
495 macro_preamble << endl;
499 docstring const snippet = macro_preamble.str() + latexString(*this);
500 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
501 preview_->addPreview(snippet, *buffer);
505 void InsetMathHull::reloadPreview(DocIterator const & pos) const
508 preview_->startLoading(*pos.buffer());
512 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
514 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
516 cur.updateFlags(Update::Force);
522 docstring InsetMathHull::label(row_type row) const
524 LASSERT(row < nrows(), /**/);
525 if (InsetLabel * il = label_[row])
526 return il->screenLabel();
531 void InsetMathHull::label(row_type row, docstring const & label)
533 //lyxerr << "setting label '" << label << "' for row " << row << endl;
537 label_[row] = dummy_pointer;
538 // We need an update of the Buffer reference cache.
539 // This is achieved by updateLabels().
541 buffer().updateLabels();
544 label_[row]->updateCommand(label);
546 label_[row]->setParam("name", label);
550 InsetCommandParams p(LABEL_CODE);
552 label_[row] = new InsetLabel(buffer_, p);
554 label_[row]->setBuffer(buffer());
558 void InsetMathHull::numbered(row_type row, bool num)
561 if (nonum_[row] && label_[row]) {
565 // The buffer is set at the end of readInset.
566 // When parsing the inset, buffer_ is 0.
569 // We need an update of the Buffer reference cache.
570 // This is achieved by updateLabels().
571 buffer().updateLabels();
576 bool InsetMathHull::numbered(row_type row) const
582 bool InsetMathHull::ams() const
584 return type_ == hullAlign
585 || type_ == hullFlAlign
586 || type_ == hullMultline
587 || type_ == hullGather
588 || type_ == hullAlignAt
589 || type_ == hullXAlignAt
590 || type_ == hullXXAlignAt;
594 Inset::DisplayType InsetMathHull::display() const
596 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
601 bool InsetMathHull::numberedType() const
603 if (type_ == hullNone)
605 if (type_ == hullSimple)
607 if (type_ == hullXXAlignAt)
609 if (type_ == hullRegexp)
611 for (row_type row = 0; row < nrows(); ++row)
618 void InsetMathHull::validate(LaTeXFeatures & features) const
621 features.require("amsmath");
623 // Validation is necessary only if not using AMS math.
624 // To be safe, we will always run mathedvalidate.
625 //if (features.amsstyle)
628 //features.binom = true;
630 InsetMathGrid::validate(features);
634 void InsetMathHull::header_write(WriteStream & os) const
636 bool n = numberedType();
650 os << "\\begin{equation" << star(n) << "}\n";
660 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
665 os << "\\begin{" << hullName(type_) << star(n) << '}'
666 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
670 os << "\\begin{" << hullName(type_) << '}'
671 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
679 os << "\\begin{unknown" << star(n) << '}';
685 void InsetMathHull::footer_write(WriteStream & os) const
687 bool n = numberedType();
700 os << "\\end{equation" << star(n) << "}\n";
712 os << "\\end{" << hullName(type_) << star(n) << "}\n";
716 os << "\\end{" << hullName(type_) << "}\n";
724 os << "\\end{unknown" << star(n) << '}';
730 bool InsetMathHull::rowChangeOK() const
733 type_ == hullEqnArray || type_ == hullAlign ||
734 type_ == hullFlAlign || type_ == hullAlignAt ||
735 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
736 type_ == hullGather || type_ == hullMultline;
740 bool InsetMathHull::colChangeOK() const
743 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
744 type_ == hullXAlignAt || type_ == hullXXAlignAt;
748 void InsetMathHull::addRow(row_type row)
753 bool numbered = numberedType();
755 if (type_ == hullMultline) {
756 if (row + 1 == nrows()) {
763 nonum_.insert(nonum_.begin() + row + 1, !numbered);
764 label_.insert(label_.begin() + row + 1, dummy_pointer);
767 InsetMathGrid::addRow(row);
771 void InsetMathHull::swapRow(row_type row)
775 if (row + 1 == nrows())
777 // gcc implements the standard std::vector<bool> which is *not* a container:
778 // http://www.gotw.ca/publications/N1185.pdf
779 // As a results, it doesn't like this:
780 // swap(nonum_[row], nonum_[row + 1]);
781 // so we do it manually:
782 bool const b = nonum_[row];
783 nonum_[row] = nonum_[row + 1];
785 swap(label_[row], label_[row + 1]);
786 InsetMathGrid::swapRow(row);
790 void InsetMathHull::delRow(row_type row)
792 if (nrows() <= 1 || !rowChangeOK())
794 if (row + 1 == nrows() && type_ == hullMultline) {
795 bool const b = nonum_[row - 1];
796 nonum_[row - 1] = nonum_[row];
798 swap(label_[row - 1], label_[row]);
799 InsetMathGrid::delRow(row);
802 InsetMathGrid::delRow(row);
803 // The last dummy row has no number info nor a label.
804 // Test nrows() + 1 because we have already erased the row.
805 if (row == nrows() + 1)
807 nonum_.erase(nonum_.begin() + row);
809 label_.erase(label_.begin() + row);
813 void InsetMathHull::addCol(col_type col)
817 InsetMathGrid::addCol(col);
821 void InsetMathHull::delCol(col_type col)
823 if (ncols() <= 1 || !colChangeOK())
825 InsetMathGrid::delCol(col);
829 docstring InsetMathHull::nicelabel(row_type row) const
834 return from_ascii("(#)");
835 return '(' + label_[row]->screenLabel() + from_ascii(", #)");
839 void InsetMathHull::glueall()
842 for (idx_type i = 0; i < nargs(); ++i)
844 *this = InsetMathHull(buffer_, hullSimple);
850 void InsetMathHull::splitTo2Cols()
852 LASSERT(ncols() == 1, /**/);
853 InsetMathGrid::addCol(1);
854 for (row_type row = 0; row < nrows(); ++row) {
855 idx_type const i = 2 * row;
856 pos_type pos = firstRelOp(cell(i));
857 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
858 cell(i).erase(pos, cell(i).size());
863 void InsetMathHull::splitTo3Cols()
865 LASSERT(ncols() < 3, /**/);
868 InsetMathGrid::addCol(2);
869 for (row_type row = 0; row < nrows(); ++row) {
870 idx_type const i = 3 * row + 1;
871 if (cell(i).size()) {
872 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
873 cell(i).erase(1, cell(i).size());
879 void InsetMathHull::changeCols(col_type cols)
883 else if (ncols() < cols) {
889 while (ncols() < cols)
890 InsetMathGrid::addCol(ncols());
896 for (row_type row = 0; row < nrows(); ++row) {
897 idx_type const i = row * ncols();
898 for (col_type col = cols; col < ncols(); ++col) {
899 cell(i + cols - 1).append(cell(i + col));
903 while (ncols() > cols) {
904 InsetMathGrid::delCol(ncols() - 1);
909 HullType InsetMathHull::getType() const
915 void InsetMathHull::setType(HullType type)
922 void InsetMathHull::mutate(HullType newtype)
924 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
926 // we try to move along the chain
927 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
929 // +-------------------------------------+
930 // we use eqnarray as intermediate type for mutations that are not
931 // directly supported because it handles labels and numbering for
934 if (newtype == type_) {
938 else if (newtype < hullNone) {
943 else if (type_ == hullNone) {
949 else if (type_ == hullSimple) {
950 if (newtype == hullNone) {
954 setType(hullEquation);
960 else if (type_ == hullEquation) {
961 if (newtype < type_) {
965 } else if (newtype == hullEqnArray) {
966 // split it "nicely" on the first relop
968 setType(hullEqnArray);
969 } else if (newtype == hullMultline || newtype == hullGather) {
979 else if (type_ == hullEqnArray) {
980 if (newtype < type_) {
981 // set correct (no)numbering
983 for (row_type row = 0; row < nrows(); ++row) {
990 // set first non-empty label
991 for (row_type row = 0; row < nrows(); ++row) {
993 label_[0] = label_[row];
1000 } else { // align & Co.
1007 else if (type_ == hullAlign || type_ == hullAlignAt ||
1008 type_ == hullXAlignAt || type_ == hullFlAlign) {
1009 if (newtype < hullAlign) {
1011 setType(hullEqnArray);
1013 } else if (newtype == hullGather || newtype == hullMultline) {
1016 } else if (newtype == hullXXAlignAt) {
1017 for (row_type row = 0; row < nrows(); ++row)
1018 numbered(row, false);
1025 else if (type_ == hullXXAlignAt) {
1026 for (row_type row = 0; row < nrows(); ++row)
1027 numbered(row, false);
1028 if (newtype < hullAlign) {
1030 setType(hullEqnArray);
1032 } else if (newtype == hullGather || newtype == hullMultline) {
1040 else if (type_ == hullMultline || type_ == hullGather) {
1041 if (newtype == hullGather || newtype == hullMultline)
1043 else if (newtype == hullAlign || newtype == hullFlAlign ||
1044 newtype == hullAlignAt || newtype == hullXAlignAt) {
1047 } else if (newtype == hullXXAlignAt) {
1049 for (row_type row = 0; row < nrows(); ++row)
1050 numbered(row, false);
1054 setType(hullEqnArray);
1060 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1061 << "' to '" << to_utf8(hullName(newtype))
1062 << "' not implemented" << endl;
1067 docstring InsetMathHull::eolString(row_type row, bool fragile) const
1070 if (numberedType()) {
1071 if (label_[row] && !nonum_[row])
1072 res += "\\label{" + label_[row]->getParam("name") + '}';
1073 if (nonum_[row] && (type_ != hullMultline))
1074 res += "\\nonumber ";
1076 return res + InsetMathGrid::eolString(row, fragile);
1080 void InsetMathHull::write(WriteStream & os) const
1082 ModeSpecifier specifier(os, MATH_MODE);
1084 InsetMathGrid::write(os);
1089 void InsetMathHull::normalize(NormalStream & os) const
1091 os << "[formula " << hullName(type_) << ' ';
1092 InsetMathGrid::normalize(os);
1097 void InsetMathHull::mathmlize(MathStream & os) const
1099 InsetMathGrid::mathmlize(os);
1103 void InsetMathHull::infoize(odocstream & os) const
1105 os << "Type: " << hullName(type_);
1109 void InsetMathHull::check() const
1111 LASSERT(nonum_.size() == nrows(), /**/);
1112 LASSERT(label_.size() == nrows(), /**/);
1116 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1120 idocstringstream iss(func.argument());
1121 iss >> dlang >> extra;
1123 extra = from_ascii("noextra");
1124 string const lang = to_ascii(dlang);
1126 // FIXME: temporarily disabled
1127 //if (cur.selection()) {
1130 // lyxerr << "use selection: " << ar << endl;
1131 // insert(pipeThroughExtern(lang, extra, ar));
1136 eq.push_back(MathAtom(new InsetMathChar('=')));
1138 // go to first item in line
1139 cur.idx() -= cur.idx() % ncols();
1142 if (getType() == hullSimple) {
1143 size_type pos = cur.cell().find_last(eq);
1145 if (cur.inMathed() && cur.selection()) {
1146 asArray(grabAndEraseSelection(cur), ar);
1147 } else if (pos == cur.cell().size()) {
1149 lyxerr << "use whole cell: " << ar << endl;
1151 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1152 lyxerr << "use partial cell form pos: " << pos << endl;
1154 cur.cell().append(eq);
1155 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1156 cur.pos() = cur.lastpos();
1160 if (getType() == hullEquation) {
1161 lyxerr << "use equation inset" << endl;
1162 mutate(hullEqnArray);
1163 MathData & ar = cur.cell();
1164 lyxerr << "use cell: " << ar << endl;
1168 cur.cell() = pipeThroughExtern(lang, extra, ar);
1169 // move to end of line
1170 cur.pos() = cur.lastpos();
1175 lyxerr << "use eqnarray" << endl;
1176 cur.idx() += 2 - cur.idx() % ncols();
1178 MathData ar = cur.cell();
1179 lyxerr << "use cell: " << ar << endl;
1180 // FIXME: temporarily disabled
1186 cur.cell() = pipeThroughExtern(lang, extra, ar);
1187 cur.pos() = cur.lastpos();
1192 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1194 //lyxerr << "action: " << cmd.action << endl;
1195 switch (cmd.action) {
1197 case LFUN_FINISHED_BACKWARD:
1198 case LFUN_FINISHED_FORWARD:
1199 case LFUN_FINISHED_RIGHT:
1200 case LFUN_FINISHED_LEFT:
1201 //lyxerr << "action: " << cmd.action << endl;
1202 InsetMathGrid::doDispatch(cur, cmd);
1206 case LFUN_BREAK_PARAGRAPH:
1207 // just swallow this
1210 case LFUN_NEWLINE_INSERT:
1211 // some magic for the common case
1212 if (type_ == hullSimple || type_ == hullEquation) {
1213 cur.recordUndoInset();
1215 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1216 mutate(align ? hullAlign : hullEqnArray);
1217 cur.idx() = nrows() * ncols() - 1;
1218 cur.pos() = cur.lastpos();
1220 InsetMathGrid::doDispatch(cur, cmd);
1223 case LFUN_MATH_NUMBER_TOGGLE: {
1224 //lyxerr << "toggling all numbers" << endl;
1225 cur.recordUndoInset();
1226 bool old = numberedType();
1227 if (type_ == hullMultline)
1228 numbered(nrows() - 1, !old);
1230 for (row_type row = 0; row < nrows(); ++row)
1231 numbered(row, !old);
1233 cur.message(old ? _("No number") : _("Number"));
1237 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1238 cur.recordUndoInset();
1239 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1240 bool old = numbered(r);
1241 cur.message(old ? _("No number") : _("Number"));
1246 case LFUN_LABEL_INSERT: {
1247 cur.recordUndoInset();
1248 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1249 docstring old_label = label(r);
1250 docstring const default_label = from_ascii(
1251 (lyxrc.label_init_length >= 0) ? "eq:" : "");
1252 if (old_label.empty())
1253 old_label = default_label;
1255 InsetCommandParams p(LABEL_CODE);
1256 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1257 string const data = InsetCommand::params2string("label", p);
1259 if (cmd.argument().empty())
1260 cur.bv().showDialog("label", data);
1262 FuncRequest fr(LFUN_INSET_INSERT, data);
1268 case LFUN_LABEL_COPY_AS_REF: {
1270 if (cmd.argument().empty() && &cur.inset() == this)
1271 // if there is no argument and we're inside math, we retrieve
1272 // the row number from the cursor position.
1273 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1275 // if there is an argument, find the corresponding label, else
1276 // check whether there is at least one label.
1277 for (row = 0; row != nrows(); ++row)
1278 if (!nonum_[row] && label_[row]
1279 && (cmd.argument().empty() || label(row) == cmd.argument()))
1286 InsetCommandParams p(REF_CODE, "ref");
1287 p["reference"] = label(row);
1288 cap::clearSelection();
1289 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1293 case LFUN_WORD_DELETE_FORWARD:
1294 case LFUN_CHAR_DELETE_FORWARD:
1295 if (col(cur.idx()) + 1 == ncols()
1296 && cur.pos() == cur.lastpos()
1297 && !cur.selection()) {
1298 if (!label(row(cur.idx())).empty()) {
1299 cur.recordUndoInset();
1300 label(row(cur.idx()), docstring());
1301 } else if (numbered(row(cur.idx()))) {
1302 cur.recordUndoInset();
1303 numbered(row(cur.idx()), false);
1305 InsetMathGrid::doDispatch(cur, cmd);
1309 InsetMathGrid::doDispatch(cur, cmd);
1314 case LFUN_INSET_INSERT: {
1315 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1316 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1317 string const name = cmd.getArg(0);
1318 if (name == "label") {
1319 InsetCommandParams p(LABEL_CODE);
1320 InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1321 docstring str = p["name"];
1322 cur.recordUndoInset();
1323 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1327 docstring old = label(r);
1330 // The label will take care of the reference update.
1334 // Newly created inset so initialize it.
1335 label_[r]->initView();
1340 InsetMathGrid::doDispatch(cur, cmd);
1344 case LFUN_MATH_EXTERN:
1345 cur.recordUndoInset();
1349 case LFUN_MATH_MUTATE: {
1350 cur.recordUndoInset();
1351 row_type row = cur.row();
1352 col_type col = cur.col();
1353 mutate(hullType(cmd.argument()));
1354 cur.idx() = row * ncols() + col;
1355 if (cur.idx() > cur.lastidx()) {
1356 cur.idx() = cur.lastidx();
1357 cur.pos() = cur.lastpos();
1359 if (cur.pos() > cur.lastpos())
1360 cur.pos() = cur.lastpos();
1362 // FIXME: find some more clever handling of the selection,
1363 // i.e. preserve it.
1364 cur.clearSelection();
1365 //cur.dispatched(FINISHED);
1369 case LFUN_MATH_DISPLAY: {
1370 cur.recordUndoInset();
1371 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1373 cur.pos() = cur.lastpos();
1374 //cur.dispatched(FINISHED);
1379 InsetMathGrid::doDispatch(cur, cmd);
1385 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1386 FuncStatus & status) const
1388 switch (cmd.action) {
1389 case LFUN_FINISHED_BACKWARD:
1390 case LFUN_FINISHED_FORWARD:
1391 case LFUN_FINISHED_RIGHT:
1392 case LFUN_FINISHED_LEFT:
1395 case LFUN_NEWLINE_INSERT:
1396 case LFUN_MATH_EXTERN:
1397 case LFUN_MATH_DISPLAY:
1399 status.setEnabled(true);
1402 case LFUN_MATH_MUTATE: {
1403 HullType ht = hullType(cmd.argument());
1404 status.setOnOff(type_ == ht);
1405 status.setEnabled(true);
1409 case LFUN_MATH_NUMBER_TOGGLE:
1410 // FIXME: what is the right test, this or the one of
1412 status.setEnabled(display());
1413 status.setOnOff(numberedType());
1416 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1417 // FIXME: what is the right test, this or the one of
1419 bool const enable = (type_ == hullMultline)
1420 ? (nrows() - 1 == cur.row())
1421 : display() != Inline && nrows() > 1;
1422 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1423 status.setEnabled(enable);
1424 status.setOnOff(enable && numbered(r));
1428 case LFUN_LABEL_INSERT:
1429 status.setEnabled(type_ != hullSimple);
1432 case LFUN_LABEL_COPY_AS_REF: {
1433 bool enabled = false;
1435 if (cmd.argument().empty() && &cur.inset() == this) {
1436 // if there is no argument and we're inside math, we retrieve
1437 // the row number from the cursor position.
1438 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1439 enabled = numberedType() && label_[row] && !nonum_[row];
1441 // if there is an argument, find the corresponding label, else
1442 // check whether there is at least one label.
1443 for (row_type row = 0; row != nrows(); ++row) {
1444 if (!nonum_[row] && label_[row] &&
1445 (cmd.argument().empty() || label(row) == cmd.argument())) {
1451 status.setEnabled(enabled);
1455 case LFUN_INSET_INSERT:
1456 if (cmd.getArg(0) == "label") {
1457 status.setEnabled(type_ != hullSimple);
1460 return InsetMathGrid::getStatus(cur, cmd, status);
1462 case LFUN_TABULAR_FEATURE: {
1463 istringstream is(to_utf8(cmd.argument()));
1467 && (s == "append-row"
1468 || s == "delete-row"
1469 || s == "copy-row")) {
1470 status.message(bformat(
1471 from_utf8(N_("Can't change number of rows in '%1$s'")),
1473 status.setEnabled(false);
1477 && (s == "append-column"
1478 || s == "delete-column"
1479 || s == "copy-column")) {
1480 status.message(bformat(
1481 from_utf8(N_("Can't change number of columns in '%1$s'")),
1483 status.setEnabled(false);
1486 if ((type_ == hullSimple
1487 || type_ == hullEquation
1488 || type_ == hullNone) &&
1489 (s == "add-hline-above" || s == "add-hline-below")) {
1490 status.message(bformat(
1491 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1493 status.setEnabled(false);
1496 if (s == "add-vline-left" || s == "add-vline-right") {
1497 status.message(bformat(
1498 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1500 status.setEnabled(false);
1503 if (s == "valign-top" || s == "valign-middle"
1504 || s == "valign-bottom" || s == "align-left"
1505 || s == "align-center" || s == "align-right") {
1506 status.setEnabled(false);
1509 return InsetMathGrid::getStatus(cur, cmd, status);
1513 return InsetMathGrid::getStatus(cur, cmd, status);
1516 // This cannot really happen, but inserted to shut-up gcc
1517 return InsetMathGrid::getStatus(cur, cmd, status);
1521 /////////////////////////////////////////////////////////////////////
1525 // simply scrap this function if you want
1526 void InsetMathHull::mutateToText()
1529 // translate to latex
1531 latex(os, false, false);
1532 string str = os.str();
1535 Text * lt = view_->cursor().innerText();
1536 string::const_iterator cit = str.begin();
1537 string::const_iterator end = str.end();
1538 for (; cit != end; ++cit)
1539 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1542 //dispatch(LFUN_ESCAPE);
1547 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1548 docstring const & font)
1550 // this whole function is a hack and won't work for incremental font
1553 if (cur.inset().asInsetMath()->name() == font)
1554 cur.handleFont(to_utf8(font));
1556 cur.handleNest(createInsetMath(font, cur.buffer()));
1562 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1567 font.fromString(to_utf8(arg), b);
1568 if (font.fontInfo().color() != Color_inherit) {
1569 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1570 cur.handleNest(at, 0);
1575 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1578 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1579 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1580 enter_front ? idxFirst(cur) : idxLast(cur);
1581 // The inset formula dimension is not necessarily the same as the
1582 // one of the instant preview image, so we have to indicate to the
1583 // BufferView that a metrics update is needed.
1584 cur.updateFlags(Update::Force);
1588 void InsetMathHull::revealCodes(Cursor & cur) const
1590 if (!cur.inMathed())
1592 odocstringstream os;
1594 cur.message(os.str());
1596 // write something to the minibuffer
1597 // translate to latex
1601 string str = os.str();
1603 string::size_type pos = 0;
1605 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1608 else if (*it == '\0') {
1610 pos = it - str.begin();
1616 res = res.substr(pos - 30);
1617 if (res.size() > 60)
1618 res = res.substr(0, 60);
1624 /////////////////////////////////////////////////////////////////////
1628 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1631 // FIXME: completely broken
1632 static InsetMathHull * lastformula = 0;
1633 static CursorBase current = DocIterator(ibegin(nucleus()));
1635 static string laststr;
1637 if (lastformula != this || laststr != str) {
1638 //lyxerr << "reset lastformula to " << this << endl;
1641 current = ibegin(nucleus());
1643 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1647 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1649 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1650 CursorSlice & top = it.back();
1651 MathData const & a = top.asInsetMath()->cell(top.idx_);
1652 if (a.matchpart(ar, top.pos_)) {
1653 bv->cursor().setSelection(it, ar.size());
1655 top.pos_ += ar.size();
1661 //lyxerr << "not found!" << endl;
1668 void InsetMathHull::write(ostream & os) const
1670 odocstringstream oss;
1671 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1674 os << to_utf8(oss.str());
1678 void InsetMathHull::read(Lexer & lex)
1681 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1682 operator=(*at->asHullInset());
1686 bool InsetMathHull::readQuiet(Lexer & lex)
1689 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1691 operator=(*at->asHullInset());
1696 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1698 if (0 && display()) {
1702 TextPainter tpain(dim.width(), dim.height());
1703 drawT(tpain, 0, dim.ascent());
1705 // reset metrics cache to "real" values
1707 return tpain.textheight();
1709 odocstringstream oss;
1710 Encoding const * const enc = encodings.fromLyXName("utf8");
1711 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1713 if (type_ == hullRegexp)
1717 docstring const str = oss.str();
1724 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1729 if (getType() == hullSimple)
1730 name = from_ascii("inlineequation");
1732 name = from_ascii("informalequation");
1734 docstring bname = name;
1735 if (!label(0).empty())
1736 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1738 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1740 odocstringstream ls;
1741 if (runparams.flavor == OutputParams::XML) {
1742 ms << MTag("alt role='tex' ");
1743 // Workaround for db2latex: db2latex always includes equations with
1744 // \ensuremath{} or \begin{display}\end{display}
1745 // so we strip LyX' math environment
1746 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1747 InsetMathGrid::write(wi);
1748 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1753 InsetMathGrid::mathmlize(ms);
1756 ms << MTag("alt role='tex'");
1757 res = latex(ls, runparams);
1758 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1762 ms << from_ascii("<graphic fileref=\"eqn/");
1763 if (!label(0).empty())
1764 ms << sgml::cleanID(buffer(), runparams, label(0));
1766 ms << sgml::uniqueID(from_ascii("anon"));
1768 if (runparams.flavor == OutputParams::XML)
1769 ms << from_ascii("\"/>");
1771 ms << from_ascii("\">");
1773 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1775 return ms.line() + res;
1779 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const &) const
1781 if (getType() == hullSimple)
1782 xs << html::StartTag("math", "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1784 xs << html::StartTag("math",
1785 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1786 MathStream ms(xs.os());
1787 InsetMathGrid::mathmlize(ms);
1788 xs << html::EndTag("math");
1793 void InsetMathHull::tocString(odocstream & os) const
1795 plaintext(os, OutputParams(0));
1799 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1801 return from_ascii("context-math");