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])
1073 escape(label_[row]->getParam("name")) + '}';
1074 if (nonum_[row] && (type_ != hullMultline))
1075 res += "\\nonumber ";
1077 return res + InsetMathGrid::eolString(row, fragile);
1081 void InsetMathHull::write(WriteStream & os) const
1083 ModeSpecifier specifier(os, MATH_MODE);
1085 InsetMathGrid::write(os);
1090 void InsetMathHull::normalize(NormalStream & os) const
1092 os << "[formula " << hullName(type_) << ' ';
1093 InsetMathGrid::normalize(os);
1098 void InsetMathHull::mathmlize(MathStream & os) const
1100 InsetMathGrid::mathmlize(os);
1104 void InsetMathHull::infoize(odocstream & os) const
1106 os << "Type: " << hullName(type_);
1110 void InsetMathHull::check() const
1112 LASSERT(nonum_.size() == nrows(), /**/);
1113 LASSERT(label_.size() == nrows(), /**/);
1117 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1121 idocstringstream iss(func.argument());
1122 iss >> dlang >> extra;
1124 extra = from_ascii("noextra");
1125 string const lang = to_ascii(dlang);
1127 // FIXME: temporarily disabled
1128 //if (cur.selection()) {
1131 // lyxerr << "use selection: " << ar << endl;
1132 // insert(pipeThroughExtern(lang, extra, ar));
1137 eq.push_back(MathAtom(new InsetMathChar('=')));
1139 // go to first item in line
1140 cur.idx() -= cur.idx() % ncols();
1143 if (getType() == hullSimple) {
1144 size_type pos = cur.cell().find_last(eq);
1146 if (cur.inMathed() && cur.selection()) {
1147 asArray(grabAndEraseSelection(cur), ar);
1148 } else if (pos == cur.cell().size()) {
1150 lyxerr << "use whole cell: " << ar << endl;
1152 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1153 lyxerr << "use partial cell form pos: " << pos << endl;
1155 cur.cell().append(eq);
1156 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1157 cur.pos() = cur.lastpos();
1161 if (getType() == hullEquation) {
1162 lyxerr << "use equation inset" << endl;
1163 mutate(hullEqnArray);
1164 MathData & ar = cur.cell();
1165 lyxerr << "use cell: " << ar << endl;
1169 cur.cell() = pipeThroughExtern(lang, extra, ar);
1170 // move to end of line
1171 cur.pos() = cur.lastpos();
1176 lyxerr << "use eqnarray" << endl;
1177 cur.idx() += 2 - cur.idx() % ncols();
1179 MathData ar = cur.cell();
1180 lyxerr << "use cell: " << ar << endl;
1181 // FIXME: temporarily disabled
1187 cur.cell() = pipeThroughExtern(lang, extra, ar);
1188 cur.pos() = cur.lastpos();
1193 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1195 //lyxerr << "action: " << cmd.action << endl;
1196 switch (cmd.action) {
1198 case LFUN_FINISHED_BACKWARD:
1199 case LFUN_FINISHED_FORWARD:
1200 case LFUN_FINISHED_RIGHT:
1201 case LFUN_FINISHED_LEFT:
1202 //lyxerr << "action: " << cmd.action << endl;
1203 InsetMathGrid::doDispatch(cur, cmd);
1207 case LFUN_BREAK_PARAGRAPH:
1208 // just swallow this
1211 case LFUN_NEWLINE_INSERT:
1212 // some magic for the common case
1213 if (type_ == hullSimple || type_ == hullEquation) {
1214 cur.recordUndoInset();
1216 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1217 mutate(align ? hullAlign : hullEqnArray);
1218 cur.idx() = nrows() * ncols() - 1;
1219 cur.pos() = cur.lastpos();
1221 InsetMathGrid::doDispatch(cur, cmd);
1224 case LFUN_MATH_NUMBER_TOGGLE: {
1225 //lyxerr << "toggling all numbers" << endl;
1226 cur.recordUndoInset();
1227 bool old = numberedType();
1228 if (type_ == hullMultline)
1229 numbered(nrows() - 1, !old);
1231 for (row_type row = 0; row < nrows(); ++row)
1232 numbered(row, !old);
1234 cur.message(old ? _("No number") : _("Number"));
1238 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1239 cur.recordUndoInset();
1240 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1241 bool old = numbered(r);
1242 cur.message(old ? _("No number") : _("Number"));
1247 case LFUN_LABEL_INSERT: {
1248 cur.recordUndoInset();
1249 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1250 docstring old_label = label(r);
1251 docstring const default_label = from_ascii(
1252 (lyxrc.label_init_length >= 0) ? "eq:" : "");
1253 if (old_label.empty())
1254 old_label = default_label;
1256 InsetCommandParams p(LABEL_CODE);
1257 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1258 string const data = InsetCommand::params2string("label", p);
1260 if (cmd.argument().empty())
1261 cur.bv().showDialog("label", data);
1263 FuncRequest fr(LFUN_INSET_INSERT, data);
1269 case LFUN_LABEL_COPY_AS_REF: {
1271 if (cmd.argument().empty() && &cur.inset() == this)
1272 // if there is no argument and we're inside math, we retrieve
1273 // the row number from the cursor position.
1274 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1276 // if there is an argument, find the corresponding label, else
1277 // check whether there is at least one label.
1278 for (row = 0; row != nrows(); ++row)
1279 if (!nonum_[row] && label_[row]
1280 && (cmd.argument().empty() || label(row) == cmd.argument()))
1287 InsetCommandParams p(REF_CODE, "ref");
1288 p["reference"] = label(row);
1289 cap::clearSelection();
1290 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1294 case LFUN_WORD_DELETE_FORWARD:
1295 case LFUN_CHAR_DELETE_FORWARD:
1296 if (col(cur.idx()) + 1 == ncols()
1297 && cur.pos() == cur.lastpos()
1298 && !cur.selection()) {
1299 if (!label(row(cur.idx())).empty()) {
1300 cur.recordUndoInset();
1301 label(row(cur.idx()), docstring());
1302 } else if (numbered(row(cur.idx()))) {
1303 cur.recordUndoInset();
1304 numbered(row(cur.idx()), false);
1306 InsetMathGrid::doDispatch(cur, cmd);
1310 InsetMathGrid::doDispatch(cur, cmd);
1315 case LFUN_INSET_INSERT: {
1316 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1317 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1318 string const name = cmd.getArg(0);
1319 if (name == "label") {
1320 InsetCommandParams p(LABEL_CODE);
1321 InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1322 docstring str = p["name"];
1323 cur.recordUndoInset();
1324 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1328 docstring old = label(r);
1331 // The label will take care of the reference update.
1335 // Newly created inset so initialize it.
1336 label_[r]->initView();
1341 InsetMathGrid::doDispatch(cur, cmd);
1345 case LFUN_MATH_EXTERN:
1346 cur.recordUndoInset();
1350 case LFUN_MATH_MUTATE: {
1351 cur.recordUndoInset();
1352 row_type row = cur.row();
1353 col_type col = cur.col();
1354 mutate(hullType(cmd.argument()));
1355 cur.idx() = row * ncols() + col;
1356 if (cur.idx() > cur.lastidx()) {
1357 cur.idx() = cur.lastidx();
1358 cur.pos() = cur.lastpos();
1360 if (cur.pos() > cur.lastpos())
1361 cur.pos() = cur.lastpos();
1363 // FIXME: find some more clever handling of the selection,
1364 // i.e. preserve it.
1365 cur.clearSelection();
1366 //cur.dispatched(FINISHED);
1370 case LFUN_MATH_DISPLAY: {
1371 cur.recordUndoInset();
1372 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1374 cur.pos() = cur.lastpos();
1375 //cur.dispatched(FINISHED);
1380 InsetMathGrid::doDispatch(cur, cmd);
1386 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1387 FuncStatus & status) const
1389 switch (cmd.action) {
1390 case LFUN_FINISHED_BACKWARD:
1391 case LFUN_FINISHED_FORWARD:
1392 case LFUN_FINISHED_RIGHT:
1393 case LFUN_FINISHED_LEFT:
1396 case LFUN_NEWLINE_INSERT:
1397 case LFUN_MATH_EXTERN:
1398 case LFUN_MATH_DISPLAY:
1400 status.setEnabled(true);
1403 case LFUN_MATH_MUTATE: {
1404 HullType ht = hullType(cmd.argument());
1405 status.setOnOff(type_ == ht);
1406 status.setEnabled(true);
1410 case LFUN_MATH_NUMBER_TOGGLE:
1411 // FIXME: what is the right test, this or the one of
1413 status.setEnabled(display());
1414 status.setOnOff(numberedType());
1417 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1418 // FIXME: what is the right test, this or the one of
1420 bool const enable = (type_ == hullMultline)
1421 ? (nrows() - 1 == cur.row())
1422 : display() != Inline && nrows() > 1;
1423 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1424 status.setEnabled(enable);
1425 status.setOnOff(enable && numbered(r));
1429 case LFUN_LABEL_INSERT:
1430 status.setEnabled(type_ != hullSimple);
1433 case LFUN_LABEL_COPY_AS_REF: {
1434 bool enabled = false;
1436 if (cmd.argument().empty() && &cur.inset() == this) {
1437 // if there is no argument and we're inside math, we retrieve
1438 // the row number from the cursor position.
1439 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1440 enabled = numberedType() && label_[row] && !nonum_[row];
1442 // if there is an argument, find the corresponding label, else
1443 // check whether there is at least one label.
1444 for (row_type row = 0; row != nrows(); ++row) {
1445 if (!nonum_[row] && label_[row] &&
1446 (cmd.argument().empty() || label(row) == cmd.argument())) {
1452 status.setEnabled(enabled);
1456 case LFUN_INSET_INSERT:
1457 if (cmd.getArg(0) == "label") {
1458 status.setEnabled(type_ != hullSimple);
1461 return InsetMathGrid::getStatus(cur, cmd, status);
1463 case LFUN_TABULAR_FEATURE: {
1464 istringstream is(to_utf8(cmd.argument()));
1468 && (s == "append-row"
1469 || s == "delete-row"
1470 || s == "copy-row")) {
1471 status.message(bformat(
1472 from_utf8(N_("Can't change number of rows in '%1$s'")),
1474 status.setEnabled(false);
1478 && (s == "append-column"
1479 || s == "delete-column"
1480 || s == "copy-column")) {
1481 status.message(bformat(
1482 from_utf8(N_("Can't change number of columns in '%1$s'")),
1484 status.setEnabled(false);
1487 if ((type_ == hullSimple
1488 || type_ == hullEquation
1489 || type_ == hullNone) &&
1490 (s == "add-hline-above" || s == "add-hline-below")) {
1491 status.message(bformat(
1492 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1494 status.setEnabled(false);
1497 if (s == "add-vline-left" || s == "add-vline-right") {
1498 status.message(bformat(
1499 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1501 status.setEnabled(false);
1504 if (s == "valign-top" || s == "valign-middle"
1505 || s == "valign-bottom" || s == "align-left"
1506 || s == "align-center" || s == "align-right") {
1507 status.setEnabled(false);
1510 return InsetMathGrid::getStatus(cur, cmd, status);
1514 return InsetMathGrid::getStatus(cur, cmd, status);
1517 // This cannot really happen, but inserted to shut-up gcc
1518 return InsetMathGrid::getStatus(cur, cmd, status);
1522 /////////////////////////////////////////////////////////////////////
1526 // simply scrap this function if you want
1527 void InsetMathHull::mutateToText()
1530 // translate to latex
1532 latex(os, false, false);
1533 string str = os.str();
1536 Text * lt = view_->cursor().innerText();
1537 string::const_iterator cit = str.begin();
1538 string::const_iterator end = str.end();
1539 for (; cit != end; ++cit)
1540 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1543 //dispatch(LFUN_ESCAPE);
1548 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1549 docstring const & font)
1551 // this whole function is a hack and won't work for incremental font
1554 if (cur.inset().asInsetMath()->name() == font)
1555 cur.handleFont(to_utf8(font));
1557 cur.handleNest(createInsetMath(font, cur.buffer()));
1563 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1568 font.fromString(to_utf8(arg), b);
1569 if (font.fontInfo().color() != Color_inherit) {
1570 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1571 cur.handleNest(at, 0);
1576 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1579 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1580 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1581 enter_front ? idxFirst(cur) : idxLast(cur);
1582 // The inset formula dimension is not necessarily the same as the
1583 // one of the instant preview image, so we have to indicate to the
1584 // BufferView that a metrics update is needed.
1585 cur.updateFlags(Update::Force);
1589 void InsetMathHull::revealCodes(Cursor & cur) const
1591 if (!cur.inMathed())
1593 odocstringstream os;
1595 cur.message(os.str());
1597 // write something to the minibuffer
1598 // translate to latex
1602 string str = os.str();
1604 string::size_type pos = 0;
1606 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1609 else if (*it == '\0') {
1611 pos = it - str.begin();
1617 res = res.substr(pos - 30);
1618 if (res.size() > 60)
1619 res = res.substr(0, 60);
1625 /////////////////////////////////////////////////////////////////////
1629 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1632 // FIXME: completely broken
1633 static InsetMathHull * lastformula = 0;
1634 static CursorBase current = DocIterator(ibegin(nucleus()));
1636 static string laststr;
1638 if (lastformula != this || laststr != str) {
1639 //lyxerr << "reset lastformula to " << this << endl;
1642 current = ibegin(nucleus());
1644 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1648 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1650 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1651 CursorSlice & top = it.back();
1652 MathData const & a = top.asInsetMath()->cell(top.idx_);
1653 if (a.matchpart(ar, top.pos_)) {
1654 bv->cursor().setSelection(it, ar.size());
1656 top.pos_ += ar.size();
1662 //lyxerr << "not found!" << endl;
1669 void InsetMathHull::write(ostream & os) const
1671 odocstringstream oss;
1672 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1675 os << to_utf8(oss.str());
1679 void InsetMathHull::read(Lexer & lex)
1682 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1683 operator=(*at->asHullInset());
1687 bool InsetMathHull::readQuiet(Lexer & lex)
1690 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1692 operator=(*at->asHullInset());
1697 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1699 if (0 && display()) {
1703 TextPainter tpain(dim.width(), dim.height());
1704 drawT(tpain, 0, dim.ascent());
1706 // reset metrics cache to "real" values
1708 return tpain.textheight();
1710 odocstringstream oss;
1711 Encoding const * const enc = encodings.fromLyXName("utf8");
1712 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1714 if (type_ == hullRegexp)
1718 docstring const str = oss.str();
1725 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1730 if (getType() == hullSimple)
1731 name = from_ascii("inlineequation");
1733 name = from_ascii("informalequation");
1735 docstring bname = name;
1736 if (!label(0).empty())
1737 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1739 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1741 odocstringstream ls;
1742 if (runparams.flavor == OutputParams::XML) {
1743 ms << MTag("alt role='tex' ");
1744 // Workaround for db2latex: db2latex always includes equations with
1745 // \ensuremath{} or \begin{display}\end{display}
1746 // so we strip LyX' math environment
1747 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1748 InsetMathGrid::write(wi);
1749 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1754 InsetMathGrid::mathmlize(ms);
1757 ms << MTag("alt role='tex'");
1758 res = latex(ls, runparams);
1759 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1763 ms << from_ascii("<graphic fileref=\"eqn/");
1764 if (!label(0).empty())
1765 ms << sgml::cleanID(buffer(), runparams, label(0));
1767 ms << sgml::uniqueID(from_ascii("anon"));
1769 if (runparams.flavor == OutputParams::XML)
1770 ms << from_ascii("\"/>");
1772 ms << from_ascii("\">");
1774 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1776 return ms.line() + res;
1780 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const &) const
1782 if (getType() == hullSimple)
1783 xs << html::StartTag("math", "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1785 xs << html::StartTag("math",
1786 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1787 MathStream ms(xs.os());
1788 InsetMathGrid::mathmlize(ms);
1789 xs << html::EndTag("math");
1794 void InsetMathHull::tocString(odocstream & os) const
1796 plaintext(os, OutputParams(0));
1800 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1802 return from_ascii("context-math");