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"
26 #include "CutAndPaste.h"
28 #include "FuncRequest.h"
29 #include "FuncStatus.h"
30 #include "LaTeXFeatures.h"
32 #include "MacroTable.h"
33 #include "output_xhtml.h"
35 #include "TextPainter.h"
36 #include "TocBackend.h"
38 #include "insets/InsetLabel.h"
39 #include "insets/InsetRef.h"
40 #include "insets/RenderPreview.h"
42 #include "graphics/PreviewImage.h"
43 #include "graphics/PreviewLoader.h"
45 #include "frontends/Painter.h"
47 #include "support/lassert.h"
48 #include "support/debug.h"
49 #include "support/gettext.h"
50 #include "support/lstrings.h"
55 using namespace lyx::support;
59 using cap::grabAndEraseSelection;
63 int getCols(HullType type)
80 // returns position of first relation operator in the array
81 // used for "intelligent splitting"
82 size_t firstRelOp(MathData const & ar)
84 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
86 return it - ar.begin();
91 char const * star(bool numbered)
93 return numbered ? "" : "*";
97 } // end anon namespace
100 HullType hullType(docstring const & s)
102 if (s == "none") return hullNone;
103 if (s == "simple") return hullSimple;
104 if (s == "equation") return hullEquation;
105 if (s == "eqnarray") return hullEqnArray;
106 if (s == "align") return hullAlign;
107 if (s == "alignat") return hullAlignAt;
108 if (s == "xalignat") return hullXAlignAt;
109 if (s == "xxalignat") return hullXXAlignAt;
110 if (s == "multline") return hullMultline;
111 if (s == "gather") return hullGather;
112 if (s == "flalign") return hullFlAlign;
113 if (s == "regexp") return hullRegexp;
114 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
119 docstring hullName(HullType type)
122 case hullNone: return from_ascii("none");
123 case hullSimple: return from_ascii("simple");
124 case hullEquation: return from_ascii("equation");
125 case hullEqnArray: return from_ascii("eqnarray");
126 case hullAlign: return from_ascii("align");
127 case hullAlignAt: return from_ascii("alignat");
128 case hullXAlignAt: return from_ascii("xalignat");
129 case hullXXAlignAt: return from_ascii("xxalignat");
130 case hullMultline: return from_ascii("multline");
131 case hullGather: return from_ascii("gather");
132 case hullFlAlign: return from_ascii("flalign");
133 case hullRegexp: return from_ascii("regexp");
135 lyxerr << "unknown hull type '" << type << "'" << endl;
136 return from_ascii("none");
140 static InsetLabel * dummy_pointer = 0;
142 InsetMathHull::InsetMathHull(Buffer * buf)
143 : InsetMathGrid(buf, 1, 1), type_(hullNone), nonum_(1, false),
144 label_(1, dummy_pointer), preview_(new RenderPreview(this))
146 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
147 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
148 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
149 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
156 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
157 : InsetMathGrid(buf, getCols(type), 1), type_(type), nonum_(1, false),
158 label_(1, dummy_pointer), preview_(new RenderPreview(this))
166 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
172 InsetMathHull::~InsetMathHull()
174 for (size_t i = 0; i < label_.size(); ++i)
179 Inset * InsetMathHull::clone() const
181 return new InsetMathHull(*this);
185 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
189 InsetMathGrid::operator=(other);
191 nonum_ = other.nonum_;
192 buffer_ = other.buffer_;
193 for (size_t i = 0; i < label_.size(); ++i)
195 label_ = other.label_;
196 for (size_t i = 0; i != label_.size(); ++i) {
198 label_[i] = new InsetLabel(*label_[i]);
200 preview_.reset(new RenderPreview(*other.preview_, this));
206 void InsetMathHull::setBuffer(Buffer & buffer)
208 InsetMathGrid::setBuffer(buffer);
210 for (size_t i = 0; i != label_.size(); ++i) {
212 label_[i]->setBuffer(buffer);
217 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
220 //FIXME: buffer_ should be set at creation for this inset! Problem is
221 // This inset is created at too many places (see Parser::parse1() in
225 for (size_t i = 0; i != label_.size(); ++i) {
227 label_[i]->updateBuffer(it, utype);
230 InsetMathGrid::updateBuffer(it, utype);
234 void InsetMathHull::addToToc(DocIterator const & pit)
237 //FIXME: buffer_ should be set at creation for this inset! Problem is
238 // This inset is created at too many places (see Parser::parse1() in
243 Toc & toc = buffer().tocBackend().toc("equation");
245 for (row_type row = 0; row != nrows(); ++row) {
249 label_[row]->addToToc(pit);
250 toc.push_back(TocItem(pit, 0, nicelabel(row)));
255 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
261 return InsetMathNest::editXY(cur, x, y);
265 InsetMath::mode_type InsetMathHull::currentMode() const
267 if (type_ == hullNone)
268 return UNDECIDED_MODE;
269 // definitely math mode ...
274 bool InsetMathHull::idxFirst(Cursor & cur) const
282 bool InsetMathHull::idxLast(Cursor & cur) const
284 cur.idx() = nargs() - 1;
285 cur.pos() = cur.lastpos();
290 char InsetMathHull::defaultColAlign(col_type col)
292 if (type_ == hullEqnArray)
294 if (type_ == hullGather)
296 if (type_ >= hullAlign)
297 return "rl"[col & 1];
302 int InsetMathHull::defaultColSpace(col_type col)
304 if (type_ == hullAlign || type_ == hullAlignAt)
306 if (type_ == hullXAlignAt)
307 return (col & 1) ? 20 : 0;
308 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
309 return (col & 1) ? 40 : 0;
314 docstring InsetMathHull::standardFont() const
319 font_name = from_ascii("texttt");
322 font_name = from_ascii("lyxnochange");
325 font_name = from_ascii("mathnormal");
331 docstring InsetMathHull::standardColor() const
336 color = from_ascii("foreground");
339 color = from_ascii("foreground");
342 color = from_ascii("math");
348 bool InsetMathHull::previewState(BufferView * bv) const
350 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
351 graphics::PreviewImage const * pimage =
352 preview_->getPreviewImage(bv->buffer());
353 return pimage && pimage->image();
359 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
361 if (previewState(mi.base.bv)) {
362 preview_->metrics(mi, dim);
363 // insert a one pixel gap in front of the formula
366 dim.des += displayMargin();
367 // Cache the inset dimension.
368 setDimCache(mi, dim);
372 FontSetChanger dummy1(mi.base, standardFont());
373 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
375 // let the cells adjust themselves
376 InsetMathGrid::metrics(mi, dim);
379 dim.asc += displayMargin();
380 dim.des += displayMargin();
383 if (numberedType()) {
384 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
386 for (row_type row = 0; row < nrows(); ++row)
387 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
393 // make it at least as high as the current font
396 math_font_max_dim(mi.base.font, asc, des);
397 dim.asc = max(dim.asc, asc);
398 dim.des = max(dim.des, des);
399 // Cache the inset dimension.
400 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
401 setDimCache(mi, dim);
405 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
407 if (previewState(pi.base.bv))
408 return graphics::PreviewLoader::backgroundColor();
413 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
415 Dimension const dim = dimension(*pi.base.bv);
416 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
417 dim.asc + dim.des - 1, pi.backgroundColor(this));
421 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
423 use_preview_ = previewState(pi.base.bv);
425 if (type_ == hullRegexp) {
426 Dimension const dim = dimension(*pi.base.bv);
427 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
428 dim.width() - 2, dim.height() - 2, Color_regexpframe);
431 // one pixel gap in front
432 preview_->draw(pi, x + 1, y);
433 setPosCache(pi, x, y);
437 bool const really_change_color = pi.base.font.color() == Color_none;
438 ColorChanger dummy0(pi.base.font, standardColor(), really_change_color);
439 FontSetChanger dummy1(pi.base, standardFont());
440 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
442 InsetMathGrid::draw(pi, x + 1, y);
444 if (numberedType()) {
445 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
446 for (row_type row = 0; row < nrows(); ++row) {
447 int const yy = y + rowinfo_[row].offset_;
448 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
449 docstring const nl = nicelabel(row);
453 setPosCache(pi, x, y);
457 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
460 InsetMathGrid::metricsT(mi, dim);
463 WriteStream wi(os, false, true, WriteStream::wsDefault);
465 dim.wid = os.str().size();
472 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
475 InsetMathGrid::drawT(pain, x, y);
478 WriteStream wi(os, false, true, WriteStream::wsDefault);
480 pain.draw(x, y, os.str().c_str());
485 static docstring latexString(InsetMathHull const & inset)
488 // This has to be static, because a preview snippet or a math
489 // macro containing math in text mode (such as $\text{$\phi$}$ or
490 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
491 // first time as a whole, and the second time only the inner math.
492 // In this last case inset.buffer() would be invalid.
493 static Encoding const * encoding = 0;
494 if (inset.isBufferValid())
495 encoding = &(inset.buffer().params().encoding());
496 WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
502 void InsetMathHull::initUnicodeMath() const
504 // Trigger classification of the unicode symbols in this inset
505 docstring const dummy = latexString(*this);
509 void InsetMathHull::addPreview(DocIterator const & inset_pos,
510 graphics::PreviewLoader & /*ploader*/) const
512 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
513 preparePreview(inset_pos);
518 void InsetMathHull::preparePreview(DocIterator const & pos) const
520 Buffer const * buffer = pos.buffer();
522 // collect macros at this position
524 buffer->listMacroNames(macros);
525 MacroNameSet::iterator it = macros.begin();
526 MacroNameSet::iterator end = macros.end();
527 odocstringstream macro_preamble;
528 for (; it != end; ++it) {
529 MacroData const * data = buffer->getMacro(*it, pos, true);
531 data->write(macro_preamble, true);
532 macro_preamble << endl;
536 docstring const snippet = macro_preamble.str() + latexString(*this);
537 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
538 preview_->addPreview(snippet, *buffer);
542 void InsetMathHull::reloadPreview(DocIterator const & pos) const
545 preview_->startLoading(*pos.buffer());
549 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
551 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
553 cur.updateFlags(Update::Force);
559 docstring InsetMathHull::label(row_type row) const
561 LASSERT(row < nrows(), /**/);
562 if (InsetLabel * il = label_[row])
563 return il->screenLabel();
568 void InsetMathHull::label(row_type row, docstring const & label)
570 //lyxerr << "setting label '" << label << "' for row " << row << endl;
574 label_[row] = dummy_pointer;
575 // We need an update of the Buffer reference cache.
576 // This is achieved by updateBuffer().
578 buffer().updateBuffer();
581 label_[row]->updateCommand(label);
583 label_[row]->setParam("name", label);
587 InsetCommandParams p(LABEL_CODE);
589 label_[row] = new InsetLabel(buffer_, p);
591 label_[row]->setBuffer(buffer());
595 void InsetMathHull::numbered(row_type row, bool num)
598 if (nonum_[row] && label_[row]) {
602 // The buffer is set at the end of readInset.
603 // When parsing the inset, buffer_ is 0.
606 // We need an update of the Buffer reference cache.
607 // This is achieved by updateBuffer().
608 buffer().updateBuffer();
613 bool InsetMathHull::numbered(row_type row) const
619 bool InsetMathHull::ams() const
621 return type_ == hullAlign
622 || type_ == hullFlAlign
623 || type_ == hullMultline
624 || type_ == hullGather
625 || type_ == hullAlignAt
626 || type_ == hullXAlignAt
627 || type_ == hullXXAlignAt;
631 Inset::DisplayType InsetMathHull::display() const
633 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
638 bool InsetMathHull::numberedType() const
640 if (type_ == hullNone)
642 if (type_ == hullSimple)
644 if (type_ == hullXXAlignAt)
646 if (type_ == hullRegexp)
648 for (row_type row = 0; row < nrows(); ++row)
655 void InsetMathHull::validate(LaTeXFeatures & features) const
657 if (features.runparams().isLaTeX()) {
659 features.require("amsmath");
661 if (type_ == hullRegexp) {
662 features.require("color");
663 string frcol = lcolor.getLaTeXName(Color_regexpframe);
664 string bgcol = "white";
665 features.addPreambleSnippet(
666 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
667 + frcol + string("}{")
668 + bgcol + string("}{\\texttt{#1}}}"));
671 // Validation is necessary only if not using AMS math.
672 // To be safe, we will always run mathedvalidate.
673 //if (features.amsstyle)
676 //features.binom = true;
677 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
678 // it would be better to do this elsewhere, but we can't validate in
679 // InsetMathMatrix and we have no way, outside MathExtern, to know if
680 // we even have any matrices.
681 features.addPreambleSnippet("<style type=\"text/css\">\n"
682 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
683 "table.matrix td{padding: 0.25px;}\n"
684 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
685 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}\n"
688 InsetMathGrid::validate(features);
692 void InsetMathHull::header_write(WriteStream & os) const
694 bool n = numberedType();
708 os << "\\begin{equation" << star(n) << "}\n";
718 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
723 os << "\\begin{" << hullName(type_) << star(n) << '}'
724 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
728 os << "\\begin{" << hullName(type_) << '}'
729 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
737 os << "\\begin{unknown" << star(n) << '}';
743 void InsetMathHull::footer_write(WriteStream & os) const
745 bool n = numberedType();
758 os << "\\end{equation" << star(n) << "}\n";
770 os << "\\end{" << hullName(type_) << star(n) << "}\n";
774 os << "\\end{" << hullName(type_) << "}\n";
782 os << "\\end{unknown" << star(n) << '}';
788 bool InsetMathHull::rowChangeOK() const
791 type_ == hullEqnArray || type_ == hullAlign ||
792 type_ == hullFlAlign || type_ == hullAlignAt ||
793 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
794 type_ == hullGather || type_ == hullMultline;
798 bool InsetMathHull::colChangeOK() const
801 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
802 type_ == hullXAlignAt || type_ == hullXXAlignAt;
806 void InsetMathHull::addRow(row_type row)
811 bool numbered = numberedType();
813 if (type_ == hullMultline) {
814 if (row + 1 == nrows()) {
821 nonum_.insert(nonum_.begin() + row + 1, !numbered);
822 label_.insert(label_.begin() + row + 1, dummy_pointer);
825 InsetMathGrid::addRow(row);
829 void InsetMathHull::swapRow(row_type row)
833 if (row + 1 == nrows())
835 // gcc implements the standard std::vector<bool> which is *not* a container:
836 // http://www.gotw.ca/publications/N1185.pdf
837 // As a results, it doesn't like this:
838 // swap(nonum_[row], nonum_[row + 1]);
839 // so we do it manually:
840 bool const b = nonum_[row];
841 nonum_[row] = nonum_[row + 1];
843 swap(label_[row], label_[row + 1]);
844 InsetMathGrid::swapRow(row);
848 void InsetMathHull::delRow(row_type row)
850 if (nrows() <= 1 || !rowChangeOK())
852 if (row + 1 == nrows() && type_ == hullMultline) {
853 bool const b = nonum_[row - 1];
854 nonum_[row - 1] = nonum_[row];
856 swap(label_[row - 1], label_[row]);
857 InsetMathGrid::delRow(row);
860 InsetMathGrid::delRow(row);
861 // The last dummy row has no number info nor a label.
862 // Test nrows() + 1 because we have already erased the row.
863 if (row == nrows() + 1)
865 nonum_.erase(nonum_.begin() + row);
867 label_.erase(label_.begin() + row);
871 void InsetMathHull::addCol(col_type col)
875 InsetMathGrid::addCol(col);
879 void InsetMathHull::delCol(col_type col)
881 if (ncols() <= 1 || !colChangeOK())
883 InsetMathGrid::delCol(col);
887 docstring InsetMathHull::nicelabel(row_type row) const
892 return from_ascii("(#)");
893 return '(' + label_[row]->screenLabel() + from_ascii(", #)");
897 void InsetMathHull::glueall()
900 for (idx_type i = 0; i < nargs(); ++i)
902 *this = InsetMathHull(buffer_, hullSimple);
908 void InsetMathHull::splitTo2Cols()
910 LASSERT(ncols() == 1, /**/);
911 InsetMathGrid::addCol(1);
912 for (row_type row = 0; row < nrows(); ++row) {
913 idx_type const i = 2 * row;
914 pos_type pos = firstRelOp(cell(i));
915 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
916 cell(i).erase(pos, cell(i).size());
921 void InsetMathHull::splitTo3Cols()
923 LASSERT(ncols() < 3, /**/);
926 InsetMathGrid::addCol(2);
927 for (row_type row = 0; row < nrows(); ++row) {
928 idx_type const i = 3 * row + 1;
929 if (cell(i).size()) {
930 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
931 cell(i).erase(1, cell(i).size());
937 void InsetMathHull::changeCols(col_type cols)
941 else if (ncols() < cols) {
947 while (ncols() < cols)
948 InsetMathGrid::addCol(ncols());
954 for (row_type row = 0; row < nrows(); ++row) {
955 idx_type const i = row * ncols();
956 for (col_type col = cols; col < ncols(); ++col) {
957 cell(i + cols - 1).append(cell(i + col));
961 while (ncols() > cols) {
962 InsetMathGrid::delCol(ncols() - 1);
967 HullType InsetMathHull::getType() const
973 void InsetMathHull::setType(HullType type)
980 void InsetMathHull::mutate(HullType newtype)
982 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
984 // we try to move along the chain
985 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
987 // +-------------------------------------+
988 // we use eqnarray as intermediate type for mutations that are not
989 // directly supported because it handles labels and numbering for
992 if (newtype == type_) {
996 else if (newtype < hullNone) {
1001 else if (type_ == hullNone) {
1002 setType(hullSimple);
1007 else if (type_ == hullSimple) {
1008 if (newtype == hullNone) {
1012 setType(hullEquation);
1018 else if (type_ == hullEquation) {
1019 if (newtype < type_) {
1020 setType(hullSimple);
1023 } else if (newtype == hullEqnArray) {
1024 // split it "nicely" on the first relop
1026 setType(hullEqnArray);
1027 } else if (newtype == hullMultline || newtype == hullGather) {
1030 // split it "nicely"
1037 else if (type_ == hullEqnArray) {
1038 if (newtype < type_) {
1039 // set correct (no)numbering
1041 for (row_type row = 0; row < nrows(); ++row) {
1048 // set first non-empty label
1049 for (row_type row = 0; row < nrows(); ++row) {
1051 label_[0] = label_[row];
1058 } else { // align & Co.
1065 else if (type_ == hullAlign || type_ == hullAlignAt ||
1066 type_ == hullXAlignAt || type_ == hullFlAlign) {
1067 if (newtype < hullAlign) {
1069 setType(hullEqnArray);
1071 } else if (newtype == hullGather || newtype == hullMultline) {
1074 } else if (newtype == hullXXAlignAt) {
1075 for (row_type row = 0; row < nrows(); ++row)
1076 numbered(row, false);
1083 else if (type_ == hullXXAlignAt) {
1084 for (row_type row = 0; row < nrows(); ++row)
1085 numbered(row, false);
1086 if (newtype < hullAlign) {
1088 setType(hullEqnArray);
1090 } else if (newtype == hullGather || newtype == hullMultline) {
1098 else if (type_ == hullMultline || type_ == hullGather) {
1099 if (newtype == hullGather || newtype == hullMultline)
1101 else if (newtype == hullAlign || newtype == hullFlAlign ||
1102 newtype == hullAlignAt || newtype == hullXAlignAt) {
1105 } else if (newtype == hullXXAlignAt) {
1107 for (row_type row = 0; row < nrows(); ++row)
1108 numbered(row, false);
1112 setType(hullEqnArray);
1118 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1119 << "' to '" << to_utf8(hullName(newtype))
1120 << "' not implemented" << endl;
1125 docstring InsetMathHull::eolString(row_type row, bool fragile) const
1128 if (numberedType()) {
1129 if (label_[row] && !nonum_[row])
1131 escape(label_[row]->getParam("name")) + '}';
1132 if (nonum_[row] && (type_ != hullMultline))
1133 res += "\\nonumber ";
1135 return res + InsetMathGrid::eolString(row, fragile);
1139 void InsetMathHull::write(WriteStream & os) const
1141 ModeSpecifier specifier(os, MATH_MODE);
1143 InsetMathGrid::write(os);
1148 void InsetMathHull::normalize(NormalStream & os) const
1150 os << "[formula " << hullName(type_) << ' ';
1151 InsetMathGrid::normalize(os);
1156 void InsetMathHull::mathmlize(MathStream & os) const
1158 InsetMathGrid::mathmlize(os);
1162 void InsetMathHull::infoize(odocstream & os) const
1164 os << "Type: " << hullName(type_);
1168 void InsetMathHull::check() const
1170 LASSERT(nonum_.size() == nrows(), /**/);
1171 LASSERT(label_.size() == nrows(), /**/);
1175 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1179 idocstringstream iss(func.argument());
1180 iss >> dlang >> extra;
1182 extra = from_ascii("noextra");
1183 string const lang = to_ascii(dlang);
1185 // FIXME: temporarily disabled
1186 //if (cur.selection()) {
1189 // lyxerr << "use selection: " << ar << endl;
1190 // insert(pipeThroughExtern(lang, extra, ar));
1195 eq.push_back(MathAtom(new InsetMathChar('=')));
1197 // go to first item in line
1198 cur.idx() -= cur.idx() % ncols();
1201 if (getType() == hullSimple) {
1202 size_type pos = cur.cell().find_last(eq);
1204 if (cur.inMathed() && cur.selection()) {
1205 asArray(grabAndEraseSelection(cur), ar);
1206 } else if (pos == cur.cell().size()) {
1208 lyxerr << "use whole cell: " << ar << endl;
1210 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1211 lyxerr << "use partial cell form pos: " << pos << endl;
1213 cur.cell().append(eq);
1214 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1215 cur.pos() = cur.lastpos();
1219 if (getType() == hullEquation) {
1220 lyxerr << "use equation inset" << endl;
1221 mutate(hullEqnArray);
1222 MathData & ar = cur.cell();
1223 lyxerr << "use cell: " << ar << endl;
1227 cur.cell() = pipeThroughExtern(lang, extra, ar);
1228 // move to end of line
1229 cur.pos() = cur.lastpos();
1234 lyxerr << "use eqnarray" << endl;
1235 cur.idx() += 2 - cur.idx() % ncols();
1237 MathData ar = cur.cell();
1238 lyxerr << "use cell: " << ar << endl;
1239 // FIXME: temporarily disabled
1245 cur.cell() = pipeThroughExtern(lang, extra, ar);
1246 cur.pos() = cur.lastpos();
1251 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1253 //lyxerr << "action: " << cmd.action() << endl;
1254 switch (cmd.action()) {
1256 case LFUN_FINISHED_BACKWARD:
1257 case LFUN_FINISHED_FORWARD:
1258 case LFUN_FINISHED_RIGHT:
1259 case LFUN_FINISHED_LEFT:
1260 //lyxerr << "action: " << cmd.action() << endl;
1261 InsetMathGrid::doDispatch(cur, cmd);
1265 case LFUN_BREAK_PARAGRAPH:
1266 // just swallow this
1269 case LFUN_NEWLINE_INSERT:
1270 // some magic for the common case
1271 if (type_ == hullSimple || type_ == hullEquation) {
1272 cur.recordUndoInset();
1274 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1275 mutate(align ? hullAlign : hullEqnArray);
1276 cur.idx() = nrows() * ncols() - 1;
1277 cur.pos() = cur.lastpos();
1279 InsetMathGrid::doDispatch(cur, cmd);
1282 case LFUN_MATH_NUMBER_TOGGLE: {
1283 //lyxerr << "toggling all numbers" << endl;
1284 cur.recordUndoInset();
1285 bool old = numberedType();
1286 if (type_ == hullMultline)
1287 numbered(nrows() - 1, !old);
1289 for (row_type row = 0; row < nrows(); ++row)
1290 numbered(row, !old);
1292 cur.message(old ? _("No number") : _("Number"));
1296 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1297 cur.recordUndoInset();
1298 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1299 bool old = numbered(r);
1300 cur.message(old ? _("No number") : _("Number"));
1305 case LFUN_LABEL_INSERT: {
1306 cur.recordUndoInset();
1307 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1308 docstring old_label = label(r);
1310 // Allow customization of this separator
1311 docstring const default_label = from_ascii("eq:");
1312 if (old_label.empty())
1313 old_label = default_label;
1315 InsetCommandParams p(LABEL_CODE);
1316 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1317 string const data = InsetCommand::params2string("label", p);
1319 if (cmd.argument().empty())
1320 cur.bv().showDialog("label", data);
1322 FuncRequest fr(LFUN_INSET_INSERT, data);
1328 case LFUN_LABEL_COPY_AS_REF: {
1330 if (cmd.argument().empty() && &cur.inset() == this)
1331 // if there is no argument and we're inside math, we retrieve
1332 // the row number from the cursor position.
1333 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1335 // if there is an argument, find the corresponding label, else
1336 // check whether there is at least one label.
1337 for (row = 0; row != nrows(); ++row)
1338 if (!nonum_[row] && label_[row]
1339 && (cmd.argument().empty() || label(row) == cmd.argument()))
1346 InsetCommandParams p(REF_CODE, "ref");
1347 p["reference"] = label(row);
1348 cap::clearSelection();
1349 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1353 case LFUN_WORD_DELETE_FORWARD:
1354 case LFUN_CHAR_DELETE_FORWARD:
1355 if (col(cur.idx()) + 1 == ncols()
1356 && cur.pos() == cur.lastpos()
1357 && !cur.selection()) {
1358 if (!label(row(cur.idx())).empty()) {
1359 cur.recordUndoInset();
1360 label(row(cur.idx()), docstring());
1361 } else if (numbered(row(cur.idx()))) {
1362 cur.recordUndoInset();
1363 numbered(row(cur.idx()), false);
1365 InsetMathGrid::doDispatch(cur, cmd);
1369 InsetMathGrid::doDispatch(cur, cmd);
1374 case LFUN_INSET_INSERT: {
1375 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1376 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1377 string const name = cmd.getArg(0);
1378 if (name == "label") {
1379 InsetCommandParams p(LABEL_CODE);
1380 InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1381 docstring str = p["name"];
1382 cur.recordUndoInset();
1383 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1387 docstring old = label(r);
1390 // The label will take care of the reference update.
1394 // Newly created inset so initialize it.
1395 label_[r]->initView();
1400 InsetMathGrid::doDispatch(cur, cmd);
1404 case LFUN_MATH_EXTERN:
1405 cur.recordUndoInset();
1409 case LFUN_MATH_MUTATE: {
1410 cur.recordUndoInset();
1411 row_type row = cur.row();
1412 col_type col = cur.col();
1413 mutate(hullType(cmd.argument()));
1414 cur.idx() = row * ncols() + col;
1415 if (cur.idx() > cur.lastidx()) {
1416 cur.idx() = cur.lastidx();
1417 cur.pos() = cur.lastpos();
1419 if (cur.pos() > cur.lastpos())
1420 cur.pos() = cur.lastpos();
1422 // FIXME: find some more clever handling of the selection,
1423 // i.e. preserve it.
1424 cur.clearSelection();
1425 //cur.dispatched(FINISHED);
1429 case LFUN_MATH_DISPLAY: {
1430 cur.recordUndoInset();
1431 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1433 cur.pos() = cur.lastpos();
1434 //cur.dispatched(FINISHED);
1439 InsetMathGrid::doDispatch(cur, cmd);
1445 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1446 FuncStatus & status) const
1448 switch (cmd.action()) {
1449 case LFUN_FINISHED_BACKWARD:
1450 case LFUN_FINISHED_FORWARD:
1451 case LFUN_FINISHED_RIGHT:
1452 case LFUN_FINISHED_LEFT:
1455 case LFUN_NEWLINE_INSERT:
1456 case LFUN_MATH_EXTERN:
1457 case LFUN_MATH_DISPLAY:
1459 status.setEnabled(true);
1462 case LFUN_MATH_MUTATE: {
1463 HullType ht = hullType(cmd.argument());
1464 status.setOnOff(type_ == ht);
1465 status.setEnabled(true);
1469 case LFUN_MATH_NUMBER_TOGGLE:
1470 // FIXME: what is the right test, this or the one of
1472 status.setEnabled(display());
1473 status.setOnOff(numberedType());
1476 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1477 // FIXME: what is the right test, this or the one of
1479 bool const enable = (type_ == hullMultline)
1480 ? (nrows() - 1 == cur.row())
1481 : display() != Inline && nrows() > 1;
1482 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1483 status.setEnabled(enable);
1484 status.setOnOff(enable && numbered(r));
1488 case LFUN_LABEL_INSERT:
1489 status.setEnabled(type_ != hullSimple);
1492 case LFUN_LABEL_COPY_AS_REF: {
1493 bool enabled = false;
1495 if (cmd.argument().empty() && &cur.inset() == this) {
1496 // if there is no argument and we're inside math, we retrieve
1497 // the row number from the cursor position.
1498 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1499 enabled = numberedType() && label_[row] && !nonum_[row];
1501 // if there is an argument, find the corresponding label, else
1502 // check whether there is at least one label.
1503 for (row_type row = 0; row != nrows(); ++row) {
1504 if (!nonum_[row] && label_[row] &&
1505 (cmd.argument().empty() || label(row) == cmd.argument())) {
1511 status.setEnabled(enabled);
1515 case LFUN_INSET_INSERT:
1516 if (cmd.getArg(0) == "label") {
1517 status.setEnabled(type_ != hullSimple);
1520 return InsetMathGrid::getStatus(cur, cmd, status);
1522 case LFUN_INSET_MODIFY: {
1523 istringstream is(to_utf8(cmd.argument()));
1527 return InsetMathGrid::getStatus(cur, cmd, status);
1530 && (s == "append-row"
1531 || s == "delete-row"
1532 || s == "copy-row")) {
1533 status.message(bformat(
1534 from_utf8(N_("Can't change number of rows in '%1$s'")),
1536 status.setEnabled(false);
1540 && (s == "append-column"
1541 || s == "delete-column"
1542 || s == "copy-column")) {
1543 status.message(bformat(
1544 from_utf8(N_("Can't change number of columns in '%1$s'")),
1546 status.setEnabled(false);
1549 if ((type_ == hullSimple
1550 || type_ == hullEquation
1551 || type_ == hullNone) &&
1552 (s == "add-hline-above" || s == "add-hline-below")) {
1553 status.message(bformat(
1554 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1556 status.setEnabled(false);
1559 if (s == "add-vline-left" || s == "add-vline-right") {
1560 status.message(bformat(
1561 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1563 status.setEnabled(false);
1566 if (s == "valign-top" || s == "valign-middle"
1567 || s == "valign-bottom" || s == "align-left"
1568 || s == "align-center" || s == "align-right") {
1569 status.setEnabled(false);
1572 return InsetMathGrid::getStatus(cur, cmd, status);
1576 return InsetMathGrid::getStatus(cur, cmd, status);
1579 // This cannot really happen, but inserted to shut-up gcc
1580 return InsetMathGrid::getStatus(cur, cmd, status);
1584 /////////////////////////////////////////////////////////////////////
1588 // simply scrap this function if you want
1589 void InsetMathHull::mutateToText()
1592 // translate to latex
1594 latex(os, false, false);
1595 string str = os.str();
1598 Text * lt = view_->cursor().innerText();
1599 string::const_iterator cit = str.begin();
1600 string::const_iterator end = str.end();
1601 for (; cit != end; ++cit)
1602 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1605 //dispatch(LFUN_ESCAPE);
1610 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1611 docstring const & font)
1613 // this whole function is a hack and won't work for incremental font
1616 if (cur.inset().asInsetMath()->name() == font)
1617 cur.handleFont(to_utf8(font));
1619 cur.handleNest(createInsetMath(font, cur.buffer()));
1625 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1630 font.fromString(to_utf8(arg), b);
1631 if (font.fontInfo().color() != Color_inherit) {
1632 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1633 cur.handleNest(at, 0);
1638 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1641 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1642 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1643 enter_front ? idxFirst(cur) : idxLast(cur);
1644 // The inset formula dimension is not necessarily the same as the
1645 // one of the instant preview image, so we have to indicate to the
1646 // BufferView that a metrics update is needed.
1647 cur.updateFlags(Update::Force);
1651 void InsetMathHull::revealCodes(Cursor & cur) const
1653 if (!cur.inMathed())
1655 odocstringstream os;
1657 cur.message(os.str());
1659 // write something to the minibuffer
1660 // translate to latex
1664 string str = os.str();
1666 string::size_type pos = 0;
1668 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1671 else if (*it == '\0') {
1673 pos = it - str.begin();
1679 res = res.substr(pos - 30);
1680 if (res.size() > 60)
1681 res = res.substr(0, 60);
1687 /////////////////////////////////////////////////////////////////////
1691 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1694 // FIXME: completely broken
1695 static InsetMathHull * lastformula = 0;
1696 static CursorBase current = DocIterator(ibegin(nucleus()));
1698 static string laststr;
1700 if (lastformula != this || laststr != str) {
1701 //lyxerr << "reset lastformula to " << this << endl;
1704 current = ibegin(nucleus());
1706 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1710 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1712 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1713 CursorSlice & top = it.back();
1714 MathData const & a = top.asInsetMath()->cell(top.idx_);
1715 if (a.matchpart(ar, top.pos_)) {
1716 bv->cursor().setSelection(it, ar.size());
1718 top.pos_ += ar.size();
1724 //lyxerr << "not found!" << endl;
1731 void InsetMathHull::write(ostream & os) const
1733 odocstringstream oss;
1734 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1737 os << to_utf8(oss.str());
1741 void InsetMathHull::read(Lexer & lex)
1744 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1745 operator=(*at->asHullInset());
1749 bool InsetMathHull::readQuiet(Lexer & lex)
1752 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1754 operator=(*at->asHullInset());
1759 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1761 if (0 && display()) {
1765 TextPainter tpain(dim.width(), dim.height());
1766 drawT(tpain, 0, dim.ascent());
1768 // reset metrics cache to "real" values
1770 return tpain.textheight();
1772 odocstringstream oss;
1773 Encoding const * const enc = encodings.fromLyXName("utf8");
1774 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1776 if (type_ == hullRegexp)
1780 docstring const str = oss.str();
1787 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1792 if (getType() == hullSimple)
1793 name = from_ascii("inlineequation");
1795 name = from_ascii("informalequation");
1797 docstring bname = name;
1798 if (!label(0).empty())
1799 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1801 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1803 odocstringstream ls;
1804 if (runparams.flavor == OutputParams::XML) {
1805 ms << MTag("alt role='tex' ");
1806 // Workaround for db2latex: db2latex always includes equations with
1807 // \ensuremath{} or \begin{display}\end{display}
1808 // so we strip LyX' math environment
1809 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1810 InsetMathGrid::write(wi);
1811 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1816 InsetMathGrid::mathmlize(ms);
1819 ms << MTag("alt role='tex'");
1820 res = latex(ls, runparams);
1821 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1825 ms << from_ascii("<graphic fileref=\"eqn/");
1826 if (!label(0).empty())
1827 ms << sgml::cleanID(buffer(), runparams, label(0));
1829 ms << sgml::uniqueID(from_ascii("anon"));
1831 if (runparams.flavor == OutputParams::XML)
1832 ms << from_ascii("\"/>");
1834 ms << from_ascii("\">");
1836 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1838 return ms.line() + res;
1842 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const &) const
1844 BufferParams::MathOutput mathtype = buffer().params().html_math_output;
1845 // FIXME Eventually we would like to do this inset by inset.
1847 case BufferParams::MathML: {
1848 if (getType() == hullSimple)
1849 xs << html::StartTag("math",
1850 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1852 xs << html::StartTag("math",
1853 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1854 MathStream ms(xs.os());
1855 InsetMathGrid::mathmlize(ms);
1856 xs << html::EndTag("math");
1859 case BufferParams::HTML: {
1860 string tag = (getType() == hullSimple) ? "span" : "div";
1861 xs << html::StartTag(tag, "class='formula'", true);
1862 HtmlStream ms(xs.os());
1863 InsetMathGrid::htmlize(ms);
1864 xs << html::EndTag(tag);
1867 case BufferParams::Images: {
1868 LYXERR0("Image output for math presently unsupported.");
1871 case BufferParams::LaTeX: {
1872 // FIXME Obviously, the only real question is how to wrap this.
1873 LYXERR0("LaTeX output for math presently unsupported.");
1880 void InsetMathHull::tocString(odocstream & os) const
1882 plaintext(os, OutputParams(0));
1886 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1888 return from_ascii("context-math");