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.screenUpdateFlags(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, bool last_eoln) 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 // Never add \\ on the last empty line of eqnarray and friends
1137 return res + InsetMathGrid::eolString(row, fragile, last_eoln);
1141 void InsetMathHull::write(WriteStream & os) const
1143 ModeSpecifier specifier(os, MATH_MODE);
1145 InsetMathGrid::write(os);
1150 void InsetMathHull::normalize(NormalStream & os) const
1152 os << "[formula " << hullName(type_) << ' ';
1153 InsetMathGrid::normalize(os);
1158 void InsetMathHull::mathmlize(MathStream & os) const
1160 InsetMathGrid::mathmlize(os);
1164 void InsetMathHull::infoize(odocstream & os) const
1166 os << "Type: " << hullName(type_);
1170 void InsetMathHull::check() const
1172 LASSERT(nonum_.size() == nrows(), /**/);
1173 LASSERT(label_.size() == nrows(), /**/);
1177 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1181 idocstringstream iss(func.argument());
1182 iss >> dlang >> extra;
1184 extra = from_ascii("noextra");
1185 string const lang = to_ascii(dlang);
1187 // FIXME: temporarily disabled
1188 //if (cur.selection()) {
1191 // lyxerr << "use selection: " << ar << endl;
1192 // insert(pipeThroughExtern(lang, extra, ar));
1197 eq.push_back(MathAtom(new InsetMathChar('=')));
1199 // go to first item in line
1200 cur.idx() -= cur.idx() % ncols();
1203 if (getType() == hullSimple) {
1204 size_type pos = cur.cell().find_last(eq);
1206 if (cur.inMathed() && cur.selection()) {
1207 asArray(grabAndEraseSelection(cur), ar);
1208 } else if (pos == cur.cell().size()) {
1210 lyxerr << "use whole cell: " << ar << endl;
1212 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1213 lyxerr << "use partial cell form pos: " << pos << endl;
1215 cur.cell().append(eq);
1216 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1217 cur.pos() = cur.lastpos();
1221 if (getType() == hullEquation) {
1222 lyxerr << "use equation inset" << endl;
1223 mutate(hullEqnArray);
1224 MathData & ar = cur.cell();
1225 lyxerr << "use cell: " << ar << endl;
1229 cur.cell() = pipeThroughExtern(lang, extra, ar);
1230 // move to end of line
1231 cur.pos() = cur.lastpos();
1236 lyxerr << "use eqnarray" << endl;
1237 cur.idx() += 2 - cur.idx() % ncols();
1239 MathData ar = cur.cell();
1240 lyxerr << "use cell: " << ar << endl;
1241 // FIXME: temporarily disabled
1247 cur.cell() = pipeThroughExtern(lang, extra, ar);
1248 cur.pos() = cur.lastpos();
1253 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1255 //lyxerr << "action: " << cmd.action() << endl;
1256 switch (cmd.action()) {
1258 case LFUN_FINISHED_BACKWARD:
1259 case LFUN_FINISHED_FORWARD:
1260 case LFUN_FINISHED_RIGHT:
1261 case LFUN_FINISHED_LEFT:
1262 //lyxerr << "action: " << cmd.action() << endl;
1263 InsetMathGrid::doDispatch(cur, cmd);
1267 case LFUN_BREAK_PARAGRAPH:
1268 // just swallow this
1271 case LFUN_NEWLINE_INSERT:
1272 // some magic for the common case
1273 if (type_ == hullSimple || type_ == hullEquation) {
1274 cur.recordUndoInset();
1276 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1277 mutate(align ? hullAlign : hullEqnArray);
1278 cur.idx() = nrows() * ncols() - 1;
1279 cur.pos() = cur.lastpos();
1281 InsetMathGrid::doDispatch(cur, cmd);
1284 case LFUN_MATH_NUMBER_TOGGLE: {
1285 //lyxerr << "toggling all numbers" << endl;
1286 cur.recordUndoInset();
1287 bool old = numberedType();
1288 if (type_ == hullMultline)
1289 numbered(nrows() - 1, !old);
1291 for (row_type row = 0; row < nrows(); ++row)
1292 numbered(row, !old);
1294 cur.message(old ? _("No number") : _("Number"));
1298 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1299 cur.recordUndoInset();
1300 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1301 bool old = numbered(r);
1302 cur.message(old ? _("No number") : _("Number"));
1307 case LFUN_LABEL_INSERT: {
1308 cur.recordUndoInset();
1309 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1310 docstring old_label = label(r);
1312 // Allow customization of this separator
1313 docstring const default_label = from_ascii("eq:");
1314 if (old_label.empty())
1315 old_label = default_label;
1317 InsetCommandParams p(LABEL_CODE);
1318 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1319 string const data = InsetCommand::params2string("label", p);
1321 if (cmd.argument().empty())
1322 cur.bv().showDialog("label", data);
1324 FuncRequest fr(LFUN_INSET_INSERT, data);
1330 case LFUN_LABEL_COPY_AS_REF: {
1332 if (cmd.argument().empty() && &cur.inset() == this)
1333 // if there is no argument and we're inside math, we retrieve
1334 // the row number from the cursor position.
1335 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1337 // if there is an argument, find the corresponding label, else
1338 // check whether there is at least one label.
1339 for (row = 0; row != nrows(); ++row)
1340 if (!nonum_[row] && label_[row]
1341 && (cmd.argument().empty() || label(row) == cmd.argument()))
1348 InsetCommandParams p(REF_CODE, "ref");
1349 p["reference"] = label(row);
1350 cap::clearSelection();
1351 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1355 case LFUN_WORD_DELETE_FORWARD:
1356 case LFUN_CHAR_DELETE_FORWARD:
1357 if (col(cur.idx()) + 1 == ncols()
1358 && cur.pos() == cur.lastpos()
1359 && !cur.selection()) {
1360 if (!label(row(cur.idx())).empty()) {
1361 cur.recordUndoInset();
1362 label(row(cur.idx()), docstring());
1363 } else if (numbered(row(cur.idx()))) {
1364 cur.recordUndoInset();
1365 numbered(row(cur.idx()), false);
1367 InsetMathGrid::doDispatch(cur, cmd);
1371 InsetMathGrid::doDispatch(cur, cmd);
1376 case LFUN_INSET_INSERT: {
1377 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1378 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1379 string const name = cmd.getArg(0);
1380 if (name == "label") {
1381 InsetCommandParams p(LABEL_CODE);
1382 InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1383 docstring str = p["name"];
1384 cur.recordUndoInset();
1385 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1389 docstring old = label(r);
1392 // The label will take care of the reference update.
1396 // Newly created inset so initialize it.
1397 label_[r]->initView();
1402 InsetMathGrid::doDispatch(cur, cmd);
1406 case LFUN_MATH_EXTERN:
1407 cur.recordUndoInset();
1411 case LFUN_MATH_MUTATE: {
1412 cur.recordUndoInset();
1413 row_type row = cur.row();
1414 col_type col = cur.col();
1415 mutate(hullType(cmd.argument()));
1416 cur.idx() = row * ncols() + col;
1417 if (cur.idx() > cur.lastidx()) {
1418 cur.idx() = cur.lastidx();
1419 cur.pos() = cur.lastpos();
1421 if (cur.pos() > cur.lastpos())
1422 cur.pos() = cur.lastpos();
1424 // FIXME: find some more clever handling of the selection,
1425 // i.e. preserve it.
1426 cur.clearSelection();
1427 //cur.dispatched(FINISHED);
1431 case LFUN_MATH_DISPLAY: {
1432 cur.recordUndoInset();
1433 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1435 cur.pos() = cur.lastpos();
1436 //cur.dispatched(FINISHED);
1441 InsetMathGrid::doDispatch(cur, cmd);
1447 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1448 FuncStatus & status) const
1450 switch (cmd.action()) {
1451 case LFUN_FINISHED_BACKWARD:
1452 case LFUN_FINISHED_FORWARD:
1453 case LFUN_FINISHED_RIGHT:
1454 case LFUN_FINISHED_LEFT:
1457 case LFUN_NEWLINE_INSERT:
1458 case LFUN_MATH_EXTERN:
1459 case LFUN_MATH_DISPLAY:
1461 status.setEnabled(true);
1464 case LFUN_MATH_MUTATE: {
1465 HullType ht = hullType(cmd.argument());
1466 status.setOnOff(type_ == ht);
1467 status.setEnabled(true);
1471 case LFUN_MATH_NUMBER_TOGGLE:
1472 // FIXME: what is the right test, this or the one of
1474 status.setEnabled(display() != Inline);
1475 status.setOnOff(numberedType());
1478 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1479 // FIXME: what is the right test, this or the one of
1481 bool const enable = (type_ == hullMultline)
1482 ? (nrows() - 1 == cur.row())
1483 : display() != Inline && nrows() > 1;
1484 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1485 status.setEnabled(enable);
1486 status.setOnOff(enable && numbered(r));
1490 case LFUN_LABEL_INSERT:
1491 status.setEnabled(type_ != hullSimple);
1494 case LFUN_LABEL_COPY_AS_REF: {
1495 bool enabled = false;
1497 if (cmd.argument().empty() && &cur.inset() == this) {
1498 // if there is no argument and we're inside math, we retrieve
1499 // the row number from the cursor position.
1500 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1501 enabled = numberedType() && label_[row] && !nonum_[row];
1503 // if there is an argument, find the corresponding label, else
1504 // check whether there is at least one label.
1505 for (row_type row = 0; row != nrows(); ++row) {
1506 if (!nonum_[row] && label_[row] &&
1507 (cmd.argument().empty() || label(row) == cmd.argument())) {
1513 status.setEnabled(enabled);
1517 case LFUN_INSET_INSERT:
1518 if (cmd.getArg(0) == "label") {
1519 status.setEnabled(type_ != hullSimple);
1522 return InsetMathGrid::getStatus(cur, cmd, status);
1524 case LFUN_INSET_MODIFY: {
1525 istringstream is(to_utf8(cmd.argument()));
1529 return InsetMathGrid::getStatus(cur, cmd, status);
1532 && (s == "append-row"
1533 || s == "delete-row"
1534 || s == "copy-row")) {
1535 status.message(bformat(
1536 from_utf8(N_("Can't change number of rows in '%1$s'")),
1538 status.setEnabled(false);
1542 && (s == "append-column"
1543 || s == "delete-column"
1544 || s == "copy-column")) {
1545 status.message(bformat(
1546 from_utf8(N_("Can't change number of columns in '%1$s'")),
1548 status.setEnabled(false);
1551 if ((type_ == hullSimple
1552 || type_ == hullEquation
1553 || type_ == hullNone) &&
1554 (s == "add-hline-above" || s == "add-hline-below")) {
1555 status.message(bformat(
1556 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1558 status.setEnabled(false);
1561 if (s == "add-vline-left" || s == "add-vline-right") {
1562 status.message(bformat(
1563 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1565 status.setEnabled(false);
1568 if (s == "valign-top" || s == "valign-middle"
1569 || s == "valign-bottom" || s == "align-left"
1570 || s == "align-center" || s == "align-right") {
1571 status.setEnabled(false);
1574 return InsetMathGrid::getStatus(cur, cmd, status);
1578 return InsetMathGrid::getStatus(cur, cmd, status);
1581 // This cannot really happen, but inserted to shut-up gcc
1582 return InsetMathGrid::getStatus(cur, cmd, status);
1586 /////////////////////////////////////////////////////////////////////
1590 // simply scrap this function if you want
1591 void InsetMathHull::mutateToText()
1594 // translate to latex
1596 latex(os, false, false);
1597 string str = os.str();
1600 Text * lt = view_->cursor().innerText();
1601 string::const_iterator cit = str.begin();
1602 string::const_iterator end = str.end();
1603 for (; cit != end; ++cit)
1604 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1607 //dispatch(LFUN_ESCAPE);
1612 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1613 docstring const & font)
1615 // this whole function is a hack and won't work for incremental font
1618 if (cur.inset().asInsetMath()->name() == font)
1619 cur.handleFont(to_utf8(font));
1621 cur.handleNest(createInsetMath(font, cur.buffer()));
1627 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1632 font.fromString(to_utf8(arg), b);
1633 if (font.fontInfo().color() != Color_inherit) {
1634 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1635 cur.handleNest(at, 0);
1640 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1643 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1644 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1645 enter_front ? idxFirst(cur) : idxLast(cur);
1646 // The inset formula dimension is not necessarily the same as the
1647 // one of the instant preview image, so we have to indicate to the
1648 // BufferView that a metrics update is needed.
1649 cur.screenUpdateFlags(Update::Force);
1653 void InsetMathHull::revealCodes(Cursor & cur) const
1655 if (!cur.inMathed())
1657 odocstringstream os;
1659 cur.message(os.str());
1661 // write something to the minibuffer
1662 // translate to latex
1666 string str = os.str();
1668 string::size_type pos = 0;
1670 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1673 else if (*it == '\0') {
1675 pos = it - str.begin();
1681 res = res.substr(pos - 30);
1682 if (res.size() > 60)
1683 res = res.substr(0, 60);
1689 /////////////////////////////////////////////////////////////////////
1693 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1696 // FIXME: completely broken
1697 static InsetMathHull * lastformula = 0;
1698 static CursorBase current = DocIterator(ibegin(nucleus()));
1700 static string laststr;
1702 if (lastformula != this || laststr != str) {
1703 //lyxerr << "reset lastformula to " << this << endl;
1706 current = ibegin(nucleus());
1708 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1712 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1714 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1715 CursorSlice & top = it.back();
1716 MathData const & a = top.asInsetMath()->cell(top.idx_);
1717 if (a.matchpart(ar, top.pos_)) {
1718 bv->cursor().setSelection(it, ar.size());
1720 top.pos_ += ar.size();
1726 //lyxerr << "not found!" << endl;
1733 void InsetMathHull::write(ostream & os) const
1735 odocstringstream oss;
1736 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1739 os << to_utf8(oss.str());
1743 void InsetMathHull::read(Lexer & lex)
1746 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1747 operator=(*at->asHullInset());
1751 bool InsetMathHull::readQuiet(Lexer & lex)
1754 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1756 operator=(*at->asHullInset());
1761 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1763 if (0 && display()) {
1767 TextPainter tpain(dim.width(), dim.height());
1768 drawT(tpain, 0, dim.ascent());
1770 // reset metrics cache to "real" values
1772 return tpain.textheight();
1774 odocstringstream oss;
1775 Encoding const * const enc = encodings.fromLyXName("utf8");
1776 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1778 if (type_ == hullRegexp)
1782 docstring const str = oss.str();
1789 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1794 if (getType() == hullSimple)
1795 name = from_ascii("inlineequation");
1797 name = from_ascii("informalequation");
1799 docstring bname = name;
1800 if (!label(0).empty())
1801 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1803 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1805 odocstringstream ls;
1806 if (runparams.flavor == OutputParams::XML) {
1807 ms << MTag("alt role='tex' ");
1808 // Workaround for db2latex: db2latex always includes equations with
1809 // \ensuremath{} or \begin{display}\end{display}
1810 // so we strip LyX' math environment
1811 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1812 InsetMathGrid::write(wi);
1813 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1818 InsetMathGrid::mathmlize(ms);
1821 ms << MTag("alt role='tex'");
1822 res = latex(ls, runparams);
1823 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1827 ms << from_ascii("<graphic fileref=\"eqn/");
1828 if (!label(0).empty())
1829 ms << sgml::cleanID(buffer(), runparams, label(0));
1831 ms << sgml::uniqueID(from_ascii("anon"));
1833 if (runparams.flavor == OutputParams::XML)
1834 ms << from_ascii("\"/>");
1836 ms << from_ascii("\">");
1838 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1840 return ms.line() + res;
1844 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const &) const
1846 BufferParams::MathOutput mathtype = buffer().params().html_math_output;
1847 // FIXME Eventually we would like to do this inset by inset.
1849 case BufferParams::MathML: {
1850 if (getType() == hullSimple)
1851 xs << html::StartTag("math",
1852 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1854 xs << html::StartTag("math",
1855 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1856 MathStream ms(xs.os());
1857 InsetMathGrid::mathmlize(ms);
1858 xs << html::EndTag("math");
1861 case BufferParams::HTML: {
1862 string tag = (getType() == hullSimple) ? "span" : "div";
1863 xs << html::StartTag(tag, "class='formula'", true);
1864 HtmlStream ms(xs.os());
1865 InsetMathGrid::htmlize(ms);
1866 xs << html::EndTag(tag);
1869 case BufferParams::Images: {
1870 LYXERR0("Image output for math presently unsupported.");
1873 case BufferParams::LaTeX: {
1874 // FIXME Obviously, the only real question is how to wrap this.
1875 LYXERR0("LaTeX output for math presently unsupported.");
1882 void InsetMathHull::tocString(odocstream & os) const
1884 plaintext(os, OutputParams(0));
1888 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1890 return from_ascii("context-math");