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"
29 #include "FuncRequest.h"
30 #include "FuncStatus.h"
31 #include "LaTeXFeatures.h"
33 #include "MacroTable.h"
34 #include "output_xhtml.h"
36 #include "TextPainter.h"
37 #include "TocBackend.h"
39 #include "insets/InsetLabel.h"
40 #include "insets/InsetRef.h"
41 #include "insets/RenderPreview.h"
43 #include "graphics/PreviewImage.h"
44 #include "graphics/PreviewLoader.h"
46 #include "frontends/Painter.h"
48 #include "support/lassert.h"
49 #include "support/debug.h"
50 #include "support/gettext.h"
51 #include "support/lstrings.h"
56 using namespace lyx::support;
60 using cap::grabAndEraseSelection;
64 int getCols(HullType type)
81 // returns position of first relation operator in the array
82 // used for "intelligent splitting"
83 size_t firstRelOp(MathData const & ar)
85 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
87 return it - ar.begin();
92 char const * star(bool numbered)
94 return numbered ? "" : "*";
98 } // end anon namespace
101 HullType hullType(docstring const & s)
103 if (s == "none") return hullNone;
104 if (s == "simple") return hullSimple;
105 if (s == "equation") return hullEquation;
106 if (s == "eqnarray") return hullEqnArray;
107 if (s == "align") return hullAlign;
108 if (s == "alignat") return hullAlignAt;
109 if (s == "xalignat") return hullXAlignAt;
110 if (s == "xxalignat") return hullXXAlignAt;
111 if (s == "multline") return hullMultline;
112 if (s == "gather") return hullGather;
113 if (s == "flalign") return hullFlAlign;
114 if (s == "regexp") return hullRegexp;
115 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
120 docstring hullName(HullType type)
123 case hullNone: return from_ascii("none");
124 case hullSimple: return from_ascii("simple");
125 case hullEquation: return from_ascii("equation");
126 case hullEqnArray: return from_ascii("eqnarray");
127 case hullAlign: return from_ascii("align");
128 case hullAlignAt: return from_ascii("alignat");
129 case hullXAlignAt: return from_ascii("xalignat");
130 case hullXXAlignAt: return from_ascii("xxalignat");
131 case hullMultline: return from_ascii("multline");
132 case hullGather: return from_ascii("gather");
133 case hullFlAlign: return from_ascii("flalign");
134 case hullRegexp: return from_ascii("regexp");
136 lyxerr << "unknown hull type '" << type << "'" << endl;
137 return from_ascii("none");
141 static InsetLabel * dummy_pointer = 0;
143 InsetMathHull::InsetMathHull(Buffer * buf)
144 : InsetMathGrid(buf, 1, 1), type_(hullNone), nonum_(1, false),
145 label_(1, dummy_pointer), preview_(new RenderPreview(this))
147 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
148 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
149 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
150 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
157 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
158 : InsetMathGrid(buf, getCols(type), 1), type_(type), nonum_(1, false),
159 label_(1, dummy_pointer), preview_(new RenderPreview(this))
167 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
173 InsetMathHull::~InsetMathHull()
175 for (size_t i = 0; i < label_.size(); ++i)
180 Inset * InsetMathHull::clone() const
182 return new InsetMathHull(*this);
186 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
190 InsetMathGrid::operator=(other);
192 nonum_ = other.nonum_;
193 buffer_ = other.buffer_;
194 for (size_t i = 0; i < label_.size(); ++i)
196 label_ = other.label_;
197 for (size_t i = 0; i != label_.size(); ++i) {
199 label_[i] = new InsetLabel(*label_[i]);
201 preview_.reset(new RenderPreview(*other.preview_, this));
207 void InsetMathHull::setBuffer(Buffer & buffer)
209 InsetMathGrid::setBuffer(buffer);
211 for (size_t i = 0; i != label_.size(); ++i) {
213 label_[i]->setBuffer(buffer);
218 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
221 //FIXME: buffer_ should be set at creation for this inset! Problem is
222 // This inset is created at too many places (see Parser::parse1() in
226 for (size_t i = 0; i != label_.size(); ++i) {
228 label_[i]->updateBuffer(it, utype);
231 InsetMathGrid::updateBuffer(it, utype);
235 void InsetMathHull::addToToc(DocIterator const & pit)
238 //FIXME: buffer_ should be set at creation for this inset! Problem is
239 // This inset is created at too many places (see Parser::parse1() in
244 Toc & toc = buffer().tocBackend().toc("equation");
246 for (row_type row = 0; row != nrows(); ++row) {
250 label_[row]->addToToc(pit);
251 toc.push_back(TocItem(pit, 0, nicelabel(row)));
256 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
262 return InsetMathNest::editXY(cur, x, y);
266 InsetMath::mode_type InsetMathHull::currentMode() const
268 if (type_ == hullNone)
269 return UNDECIDED_MODE;
270 // definitely math mode ...
275 bool InsetMathHull::idxFirst(Cursor & cur) const
283 bool InsetMathHull::idxLast(Cursor & cur) const
285 cur.idx() = nargs() - 1;
286 cur.pos() = cur.lastpos();
291 char InsetMathHull::defaultColAlign(col_type col)
293 if (type_ == hullEqnArray)
295 if (type_ == hullGather)
297 if (type_ >= hullAlign)
298 return "rl"[col & 1];
303 int InsetMathHull::defaultColSpace(col_type col)
305 if (type_ == hullAlign || type_ == hullAlignAt)
307 if (type_ == hullXAlignAt)
308 return (col & 1) ? 20 : 0;
309 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
310 return (col & 1) ? 40 : 0;
315 docstring InsetMathHull::standardFont() const
320 font_name = from_ascii("texttt");
323 font_name = from_ascii("lyxnochange");
326 font_name = from_ascii("mathnormal");
332 docstring InsetMathHull::standardColor() const
337 color = from_ascii("foreground");
340 color = from_ascii("foreground");
343 color = from_ascii("math");
349 bool InsetMathHull::previewState(BufferView * bv) const
351 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
352 graphics::PreviewImage const * pimage =
353 preview_->getPreviewImage(bv->buffer());
354 return pimage && pimage->image();
360 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
362 if (previewState(mi.base.bv)) {
363 preview_->metrics(mi, dim);
364 // insert a one pixel gap in front of the formula
367 dim.des += displayMargin();
368 // Cache the inset dimension.
369 setDimCache(mi, dim);
373 FontSetChanger dummy1(mi.base, standardFont());
374 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
376 // let the cells adjust themselves
377 InsetMathGrid::metrics(mi, dim);
380 dim.asc += displayMargin();
381 dim.des += displayMargin();
384 if (numberedType()) {
385 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
387 for (row_type row = 0; row < nrows(); ++row)
388 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
394 // make it at least as high as the current font
397 math_font_max_dim(mi.base.font, asc, des);
398 dim.asc = max(dim.asc, asc);
399 dim.des = max(dim.des, des);
400 // Cache the inset dimension.
401 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
402 setDimCache(mi, dim);
406 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
408 if (previewState(pi.base.bv))
409 return graphics::PreviewLoader::backgroundColor();
414 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
416 Dimension const dim = dimension(*pi.base.bv);
417 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
418 dim.asc + dim.des - 1, pi.backgroundColor(this));
422 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
424 use_preview_ = previewState(pi.base.bv);
426 if (type_ == hullRegexp) {
427 Dimension const dim = dimension(*pi.base.bv);
428 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
429 dim.width() - 2, dim.height() - 2, Color_regexpframe);
432 // one pixel gap in front
433 preview_->draw(pi, x + 1, y);
434 setPosCache(pi, x, y);
438 bool const really_change_color = pi.base.font.color() == Color_none;
439 ColorChanger dummy0(pi.base.font, standardColor(), really_change_color);
440 FontSetChanger dummy1(pi.base, standardFont());
441 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
443 InsetMathGrid::draw(pi, x + 1, y);
445 if (numberedType()) {
446 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
447 for (row_type row = 0; row < nrows(); ++row) {
448 int const yy = y + rowinfo_[row].offset_;
449 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
450 docstring const nl = nicelabel(row);
454 setPosCache(pi, x, y);
458 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
461 InsetMathGrid::metricsT(mi, dim);
464 WriteStream wi(os, false, true, WriteStream::wsDefault);
466 dim.wid = os.str().size();
473 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
476 InsetMathGrid::drawT(pain, x, y);
479 WriteStream wi(os, false, true, WriteStream::wsDefault);
481 pain.draw(x, y, os.str().c_str());
486 static docstring latexString(InsetMathHull const & inset)
489 // This has to be static, because a preview snippet or a math
490 // macro containing math in text mode (such as $\text{$\phi$}$ or
491 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
492 // first time as a whole, and the second time only the inner math.
493 // In this last case inset.buffer() would be invalid.
494 static Encoding const * encoding = 0;
495 if (inset.isBufferValid())
496 encoding = &(inset.buffer().params().encoding());
497 WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
503 void InsetMathHull::initUnicodeMath() const
505 // Trigger classification of the unicode symbols in this inset
506 docstring const dummy = latexString(*this);
510 void InsetMathHull::addPreview(DocIterator const & inset_pos,
511 graphics::PreviewLoader & /*ploader*/) const
513 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
514 preparePreview(inset_pos);
519 void InsetMathHull::preparePreview(DocIterator const & pos,
520 bool forexport) const
522 // there is no need to do all the macro stuff if we're not
523 // actually going to generate the preview.
524 if (RenderPreview::status() != LyXRC::PREVIEW_ON && !forexport)
527 Buffer const * buffer = pos.buffer();
529 // collect macros at this position
531 buffer->listMacroNames(macros);
532 MacroNameSet::iterator it = macros.begin();
533 MacroNameSet::iterator end = macros.end();
534 odocstringstream macro_preamble;
535 for (; it != end; ++it) {
536 MacroData const * data = buffer->getMacro(*it, pos, true);
538 data->write(macro_preamble, true);
539 macro_preamble << endl;
543 docstring const snippet = macro_preamble.str() + latexString(*this);
544 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
545 preview_->addPreview(snippet, *buffer, forexport);
549 void InsetMathHull::reloadPreview(DocIterator const & pos) const
552 preview_->startLoading(*pos.buffer());
556 void InsetMathHull::loadPreview(DocIterator const & pos) const
558 bool const forexport = true;
559 preparePreview(pos, forexport);
560 preview_->startLoading(*pos.buffer(), forexport);
564 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
566 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
568 cur.screenUpdateFlags(Update::Force);
574 docstring InsetMathHull::label(row_type row) const
576 LASSERT(row < nrows(), /**/);
577 if (InsetLabel * il = label_[row])
578 return il->screenLabel();
583 void InsetMathHull::label(row_type row, docstring const & label)
585 //lyxerr << "setting label '" << label << "' for row " << row << endl;
589 label_[row] = dummy_pointer;
592 label_[row]->updateCommand(label);
594 label_[row]->setParam("name", label);
598 InsetCommandParams p(LABEL_CODE);
600 label_[row] = new InsetLabel(buffer_, p);
602 label_[row]->setBuffer(buffer());
606 void InsetMathHull::numbered(row_type row, bool num)
609 if (nonum_[row] && label_[row]) {
616 bool InsetMathHull::numbered(row_type row) const
622 bool InsetMathHull::ams() const
624 return type_ == hullAlign
625 || type_ == hullFlAlign
626 || type_ == hullMultline
627 || type_ == hullGather
628 || type_ == hullAlignAt
629 || type_ == hullXAlignAt
630 || type_ == hullXXAlignAt;
634 Inset::DisplayType InsetMathHull::display() const
636 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
641 bool InsetMathHull::numberedType() const
643 if (type_ == hullNone)
645 if (type_ == hullSimple)
647 if (type_ == hullXXAlignAt)
649 if (type_ == hullRegexp)
651 for (row_type row = 0; row < nrows(); ++row)
658 void InsetMathHull::validate(LaTeXFeatures & features) const
660 if (features.runparams().isLaTeX()) {
662 features.require("amsmath");
664 if (type_ == hullRegexp) {
665 features.require("color");
666 string frcol = lcolor.getLaTeXName(Color_regexpframe);
667 string bgcol = "white";
668 features.addPreambleSnippet(
669 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
670 + frcol + string("}{")
671 + bgcol + string("}{\\texttt{#1}}}"));
674 // Validation is necessary only if not using AMS math.
675 // To be safe, we will always run mathedvalidate.
676 //if (features.amsstyle)
679 //features.binom = true;
680 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
681 // it would be better to do this elsewhere, but we can't validate in
682 // InsetMathMatrix and we have no way, outside MathExtern, to know if
683 // we even have any matrices.
684 features.addPreambleSnippet("<style type=\"text/css\">\n"
685 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
686 "table.matrix td{padding: 0.25px;}\n"
687 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
688 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}\n"
691 InsetMathGrid::validate(features);
695 void InsetMathHull::header_write(WriteStream & os) const
697 bool n = numberedType();
711 os << "\\begin{equation" << star(n) << "}\n";
721 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
726 os << "\\begin{" << hullName(type_) << star(n) << '}'
727 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
731 os << "\\begin{" << hullName(type_) << '}'
732 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
740 os << "\\begin{unknown" << star(n) << '}';
746 void InsetMathHull::footer_write(WriteStream & os) const
748 bool n = numberedType();
761 os << "\\end{equation" << star(n) << "}\n";
773 os << "\\end{" << hullName(type_) << star(n) << "}\n";
777 os << "\\end{" << hullName(type_) << "}\n";
785 os << "\\end{unknown" << star(n) << '}';
791 bool InsetMathHull::rowChangeOK() const
794 type_ == hullEqnArray || type_ == hullAlign ||
795 type_ == hullFlAlign || type_ == hullAlignAt ||
796 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
797 type_ == hullGather || type_ == hullMultline;
801 bool InsetMathHull::colChangeOK() const
804 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
805 type_ == hullXAlignAt || type_ == hullXXAlignAt;
809 void InsetMathHull::addRow(row_type row)
814 bool numbered = numberedType();
816 if (type_ == hullMultline) {
817 if (row + 1 == nrows()) {
824 nonum_.insert(nonum_.begin() + row + 1, !numbered);
825 label_.insert(label_.begin() + row + 1, dummy_pointer);
828 InsetMathGrid::addRow(row);
832 void InsetMathHull::swapRow(row_type row)
836 if (row + 1 == nrows())
838 // gcc implements the standard std::vector<bool> which is *not* a container:
839 // http://www.gotw.ca/publications/N1185.pdf
840 // As a results, it doesn't like this:
841 // swap(nonum_[row], nonum_[row + 1]);
842 // so we do it manually:
843 bool const b = nonum_[row];
844 nonum_[row] = nonum_[row + 1];
846 swap(label_[row], label_[row + 1]);
847 InsetMathGrid::swapRow(row);
851 void InsetMathHull::delRow(row_type row)
853 if (nrows() <= 1 || !rowChangeOK())
855 if (row + 1 == nrows() && type_ == hullMultline) {
856 bool const b = nonum_[row - 1];
857 nonum_[row - 1] = nonum_[row];
859 swap(label_[row - 1], label_[row]);
860 InsetMathGrid::delRow(row);
863 InsetMathGrid::delRow(row);
864 // The last dummy row has no number info nor a label.
865 // Test nrows() + 1 because we have already erased the row.
866 if (row == nrows() + 1)
868 nonum_.erase(nonum_.begin() + row);
870 label_.erase(label_.begin() + row);
874 void InsetMathHull::addCol(col_type col)
878 InsetMathGrid::addCol(col);
882 void InsetMathHull::delCol(col_type col)
884 if (ncols() <= 1 || !colChangeOK())
886 InsetMathGrid::delCol(col);
890 docstring InsetMathHull::nicelabel(row_type row) const
895 return from_ascii("(#)");
896 return '(' + label_[row]->screenLabel() + from_ascii(", #)");
900 void InsetMathHull::glueall(HullType type)
903 for (idx_type i = 0; i < nargs(); ++i)
905 InsetLabel * label = 0;
906 if (type == hullEquation) {
907 // preserve the label
911 *this = InsetMathHull(buffer_, hullSimple);
919 void InsetMathHull::splitTo2Cols()
921 LASSERT(ncols() == 1, /**/);
922 InsetMathGrid::addCol(1);
923 for (row_type row = 0; row < nrows(); ++row) {
924 idx_type const i = 2 * row;
925 pos_type pos = firstRelOp(cell(i));
926 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
927 cell(i).erase(pos, cell(i).size());
932 void InsetMathHull::splitTo3Cols()
934 LASSERT(ncols() < 3, /**/);
937 InsetMathGrid::addCol(2);
938 for (row_type row = 0; row < nrows(); ++row) {
939 idx_type const i = 3 * row + 1;
940 if (cell(i).size()) {
941 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
942 cell(i).erase(1, cell(i).size());
948 void InsetMathHull::changeCols(col_type cols)
952 else if (ncols() < cols) {
958 while (ncols() < cols)
959 InsetMathGrid::addCol(ncols());
965 for (row_type row = 0; row < nrows(); ++row) {
966 idx_type const i = row * ncols();
967 for (col_type col = cols; col < ncols(); ++col) {
968 cell(i + cols - 1).append(cell(i + col));
972 while (ncols() > cols) {
973 InsetMathGrid::delCol(ncols() - 1);
978 HullType InsetMathHull::getType() const
984 void InsetMathHull::setType(HullType type)
991 void InsetMathHull::mutate(HullType newtype)
993 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
995 // we try to move along the chain
996 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
998 // +-------------------------------------+
999 // we use eqnarray as intermediate type for mutations that are not
1000 // directly supported because it handles labels and numbering for
1003 if (newtype == type_) {
1007 else if (newtype < hullNone) {
1012 else if (type_ == hullNone) {
1013 setType(hullSimple);
1018 else if (type_ == hullSimple) {
1019 if (newtype == hullNone) {
1023 setType(hullEquation);
1028 else if (type_ == hullEquation) {
1029 if (newtype < type_) {
1030 setType(hullSimple);
1033 } else if (newtype == hullEqnArray) {
1034 // split it "nicely" on the first relop
1036 setType(hullEqnArray);
1037 } else if (newtype == hullMultline || newtype == hullGather) {
1040 // split it "nicely"
1047 else if (type_ == hullEqnArray) {
1048 if (newtype < type_) {
1049 // set first non-empty label
1050 for (row_type row = 0; row < nrows(); ++row) {
1053 label_[0] = label_[row];
1061 } else { // align & Co.
1068 else if (type_ == hullAlign || type_ == hullAlignAt ||
1069 type_ == hullXAlignAt || type_ == hullFlAlign) {
1070 if (newtype < hullAlign) {
1072 setType(hullEqnArray);
1074 } else if (newtype == hullGather || newtype == hullMultline) {
1077 } else if (newtype == hullXXAlignAt) {
1078 for (row_type row = 0; row < nrows(); ++row)
1079 numbered(row, false);
1086 else if (type_ == hullXXAlignAt) {
1087 for (row_type row = 0; row < nrows(); ++row)
1088 numbered(row, false);
1089 if (newtype < hullAlign) {
1091 setType(hullEqnArray);
1093 } else if (newtype == hullGather || newtype == hullMultline) {
1101 else if (type_ == hullMultline || type_ == hullGather) {
1102 if (newtype == hullGather || newtype == hullMultline)
1104 else if (newtype == hullAlign || newtype == hullFlAlign ||
1105 newtype == hullAlignAt || newtype == hullXAlignAt) {
1108 } else if (newtype == hullXXAlignAt) {
1110 for (row_type row = 0; row < nrows(); ++row)
1111 numbered(row, false);
1115 setType(hullEqnArray);
1121 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1122 << "' to '" << to_utf8(hullName(newtype))
1123 << "' not implemented" << endl;
1128 docstring InsetMathHull::eolString(row_type row, bool fragile, bool last_eoln) const
1131 if (numberedType()) {
1132 if (label_[row] && !nonum_[row])
1134 escape(label_[row]->getParam("name")) + '}';
1135 if (nonum_[row] && (type_ != hullMultline))
1136 res += "\\nonumber ";
1138 // Never add \\ on the last empty line of eqnarray and friends
1140 return res + InsetMathGrid::eolString(row, fragile, last_eoln);
1144 void InsetMathHull::write(WriteStream & os) const
1146 ModeSpecifier specifier(os, MATH_MODE);
1148 InsetMathGrid::write(os);
1153 void InsetMathHull::normalize(NormalStream & os) const
1155 os << "[formula " << hullName(type_) << ' ';
1156 InsetMathGrid::normalize(os);
1161 void InsetMathHull::mathmlize(MathStream & os) const
1163 InsetMathGrid::mathmlize(os);
1167 void InsetMathHull::infoize(odocstream & os) const
1169 os << "Type: " << hullName(type_);
1173 void InsetMathHull::check() const
1175 LASSERT(nonum_.size() == nrows(), /**/);
1176 LASSERT(label_.size() == nrows(), /**/);
1180 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1184 idocstringstream iss(func.argument());
1185 iss >> dlang >> extra;
1187 extra = from_ascii("noextra");
1188 string const lang = to_ascii(dlang);
1190 // FIXME: temporarily disabled
1191 //if (cur.selection()) {
1194 // lyxerr << "use selection: " << ar << endl;
1195 // insert(pipeThroughExtern(lang, extra, ar));
1200 eq.push_back(MathAtom(new InsetMathChar('=')));
1202 // go to first item in line
1203 cur.idx() -= cur.idx() % ncols();
1206 if (getType() == hullSimple) {
1207 size_type pos = cur.cell().find_last(eq);
1209 if (cur.inMathed() && cur.selection()) {
1210 asArray(grabAndEraseSelection(cur), ar);
1211 } else if (pos == cur.cell().size()) {
1213 lyxerr << "use whole cell: " << ar << endl;
1215 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1216 lyxerr << "use partial cell form pos: " << pos << endl;
1218 cur.cell().append(eq);
1219 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1220 cur.pos() = cur.lastpos();
1224 if (getType() == hullEquation) {
1225 lyxerr << "use equation inset" << endl;
1226 mutate(hullEqnArray);
1227 MathData & ar = cur.cell();
1228 lyxerr << "use cell: " << ar << endl;
1232 cur.cell() = pipeThroughExtern(lang, extra, ar);
1233 // move to end of line
1234 cur.pos() = cur.lastpos();
1239 lyxerr << "use eqnarray" << endl;
1240 cur.idx() += 2 - cur.idx() % ncols();
1242 MathData ar = cur.cell();
1243 lyxerr << "use cell: " << ar << endl;
1244 // FIXME: temporarily disabled
1250 cur.cell() = pipeThroughExtern(lang, extra, ar);
1251 cur.pos() = cur.lastpos();
1256 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1258 //lyxerr << "action: " << cmd.action() << endl;
1259 switch (cmd.action()) {
1261 case LFUN_FINISHED_BACKWARD:
1262 case LFUN_FINISHED_FORWARD:
1263 case LFUN_FINISHED_RIGHT:
1264 case LFUN_FINISHED_LEFT:
1265 //lyxerr << "action: " << cmd.action() << endl;
1266 InsetMathGrid::doDispatch(cur, cmd);
1270 case LFUN_BREAK_PARAGRAPH:
1271 // just swallow this
1274 case LFUN_NEWLINE_INSERT:
1275 // some magic for the common case
1276 if (type_ == hullSimple || type_ == hullEquation) {
1277 cur.recordUndoInset();
1279 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1280 mutate(align ? hullAlign : hullEqnArray);
1281 // mutate() may change labels and such.
1282 cur.forceBufferUpdate();
1283 cur.idx() = nrows() * ncols() - 1;
1284 cur.pos() = cur.lastpos();
1286 InsetMathGrid::doDispatch(cur, cmd);
1289 case LFUN_MATH_NUMBER_TOGGLE: {
1290 //lyxerr << "toggling all numbers" << endl;
1291 cur.recordUndoInset();
1292 bool old = numberedType();
1293 if (type_ == hullMultline)
1294 numbered(nrows() - 1, !old);
1296 for (row_type row = 0; row < nrows(); ++row)
1297 numbered(row, !old);
1299 cur.message(old ? _("No number") : _("Number"));
1300 cur.forceBufferUpdate();
1304 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1305 cur.recordUndoInset();
1306 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1307 bool old = numbered(r);
1308 cur.message(old ? _("No number") : _("Number"));
1310 cur.forceBufferUpdate();
1314 case LFUN_LABEL_INSERT: {
1315 cur.recordUndoInset();
1316 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1317 docstring old_label = label(r);
1319 // Allow customization of this separator
1320 docstring const default_label = from_ascii("eq:");
1321 if (old_label.empty())
1322 old_label = default_label;
1324 InsetCommandParams p(LABEL_CODE);
1325 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1326 string const data = InsetCommand::params2string("label", p);
1328 if (cmd.argument().empty())
1329 cur.bv().showDialog("label", data);
1331 FuncRequest fr(LFUN_INSET_INSERT, data);
1337 case LFUN_LABEL_COPY_AS_REF: {
1339 if (cmd.argument().empty() && &cur.inset() == this)
1340 // if there is no argument and we're inside math, we retrieve
1341 // the row number from the cursor position.
1342 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1344 // if there is an argument, find the corresponding label, else
1345 // check whether there is at least one label.
1346 for (row = 0; row != nrows(); ++row)
1347 if (!nonum_[row] && label_[row]
1348 && (cmd.argument().empty() || label(row) == cmd.argument()))
1355 InsetCommandParams p(REF_CODE, "ref");
1356 p["reference"] = label(row);
1357 cap::clearSelection();
1358 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1362 case LFUN_WORD_DELETE_FORWARD:
1363 case LFUN_CHAR_DELETE_FORWARD:
1364 if (col(cur.idx()) + 1 == ncols()
1365 && cur.pos() == cur.lastpos()
1366 && !cur.selection()) {
1367 if (!label(row(cur.idx())).empty()) {
1368 cur.recordUndoInset();
1369 label(row(cur.idx()), docstring());
1370 } else if (numbered(row(cur.idx()))) {
1371 cur.recordUndoInset();
1372 numbered(row(cur.idx()), false);
1373 cur.forceBufferUpdate();
1375 InsetMathGrid::doDispatch(cur, cmd);
1379 InsetMathGrid::doDispatch(cur, cmd);
1384 case LFUN_INSET_INSERT: {
1385 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1386 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1387 string const name = cmd.getArg(0);
1388 if (name == "label") {
1389 InsetCommandParams p(LABEL_CODE);
1390 InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1391 docstring str = p["name"];
1392 cur.recordUndoInset();
1393 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1397 docstring old = label(r);
1400 // The label will take care of the reference update.
1404 // Newly created inset so initialize it.
1405 label_[r]->initView();
1408 cur.forceBufferUpdate();
1411 InsetMathGrid::doDispatch(cur, cmd);
1415 case LFUN_MATH_EXTERN:
1416 cur.recordUndoInset();
1420 case LFUN_MATH_MUTATE: {
1421 cur.recordUndoInset();
1422 row_type row = cur.row();
1423 col_type col = cur.col();
1424 mutate(hullType(cmd.argument()));
1425 cur.idx() = row * ncols() + col;
1426 if (cur.idx() > cur.lastidx()) {
1427 cur.idx() = cur.lastidx();
1428 cur.pos() = cur.lastpos();
1430 if (cur.pos() > cur.lastpos())
1431 cur.pos() = cur.lastpos();
1433 cur.forceBufferUpdate();
1434 // FIXME: find some more clever handling of the selection,
1435 // i.e. preserve it.
1436 cur.clearSelection();
1437 //cur.dispatched(FINISHED);
1441 case LFUN_MATH_DISPLAY: {
1442 cur.recordUndoInset();
1443 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1445 cur.pos() = cur.lastpos();
1446 //cur.dispatched(FINISHED);
1451 InsetMathGrid::doDispatch(cur, cmd);
1457 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1458 FuncStatus & status) const
1460 switch (cmd.action()) {
1461 case LFUN_FINISHED_BACKWARD:
1462 case LFUN_FINISHED_FORWARD:
1463 case LFUN_FINISHED_RIGHT:
1464 case LFUN_FINISHED_LEFT:
1467 case LFUN_NEWLINE_INSERT:
1468 case LFUN_MATH_EXTERN:
1469 case LFUN_MATH_DISPLAY:
1471 status.setEnabled(true);
1474 case LFUN_MATH_MUTATE: {
1475 HullType ht = hullType(cmd.argument());
1476 status.setOnOff(type_ == ht);
1477 status.setEnabled(true);
1481 case LFUN_MATH_NUMBER_TOGGLE:
1482 // FIXME: what is the right test, this or the one of
1484 status.setEnabled(display() != Inline);
1485 status.setOnOff(numberedType());
1488 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1489 // FIXME: what is the right test, this or the one of
1491 bool const enable = (type_ == hullMultline)
1492 ? (nrows() - 1 == cur.row())
1493 : display() != Inline && nrows() > 1;
1494 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1495 status.setEnabled(enable);
1496 status.setOnOff(enable && numbered(r));
1500 case LFUN_LABEL_INSERT:
1501 status.setEnabled(type_ != hullSimple);
1504 case LFUN_LABEL_COPY_AS_REF: {
1505 bool enabled = false;
1507 if (cmd.argument().empty() && &cur.inset() == this) {
1508 // if there is no argument and we're inside math, we retrieve
1509 // the row number from the cursor position.
1510 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1511 enabled = numberedType() && label_[row] && !nonum_[row];
1513 // if there is an argument, find the corresponding label, else
1514 // check whether there is at least one label.
1515 for (row_type row = 0; row != nrows(); ++row) {
1516 if (!nonum_[row] && label_[row] &&
1517 (cmd.argument().empty() || label(row) == cmd.argument())) {
1523 status.setEnabled(enabled);
1527 case LFUN_INSET_INSERT:
1528 if (cmd.getArg(0) == "label") {
1529 status.setEnabled(type_ != hullSimple);
1532 return InsetMathGrid::getStatus(cur, cmd, status);
1534 case LFUN_INSET_MODIFY: {
1535 istringstream is(to_utf8(cmd.argument()));
1539 return InsetMathGrid::getStatus(cur, cmd, status);
1542 && (s == "append-row"
1543 || s == "delete-row"
1544 || s == "copy-row")) {
1545 status.message(bformat(
1546 from_utf8(N_("Can't change number of rows in '%1$s'")),
1548 status.setEnabled(false);
1552 && (s == "append-column"
1553 || s == "delete-column"
1554 || s == "copy-column")) {
1555 status.message(bformat(
1556 from_utf8(N_("Can't change number of columns in '%1$s'")),
1558 status.setEnabled(false);
1561 if ((type_ == hullSimple
1562 || type_ == hullEquation
1563 || type_ == hullNone) &&
1564 (s == "add-hline-above" || s == "add-hline-below")) {
1565 status.message(bformat(
1566 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1568 status.setEnabled(false);
1571 if (s == "add-vline-left" || s == "add-vline-right") {
1572 status.message(bformat(
1573 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1575 status.setEnabled(false);
1578 if (s == "valign-top" || s == "valign-middle"
1579 || s == "valign-bottom" || s == "align-left"
1580 || s == "align-center" || s == "align-right") {
1581 status.setEnabled(false);
1584 return InsetMathGrid::getStatus(cur, cmd, status);
1588 return InsetMathGrid::getStatus(cur, cmd, status);
1591 // This cannot really happen, but inserted to shut-up gcc
1592 return InsetMathGrid::getStatus(cur, cmd, status);
1596 /////////////////////////////////////////////////////////////////////
1600 // simply scrap this function if you want
1601 void InsetMathHull::mutateToText()
1604 // translate to latex
1606 latex(os, false, false);
1607 string str = os.str();
1610 Text * lt = view_->cursor().innerText();
1611 string::const_iterator cit = str.begin();
1612 string::const_iterator end = str.end();
1613 for (; cit != end; ++cit)
1614 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1617 //dispatch(LFUN_ESCAPE);
1622 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1623 docstring const & font)
1625 // this whole function is a hack and won't work for incremental font
1628 if (cur.inset().asInsetMath()->name() == font)
1629 cur.handleFont(to_utf8(font));
1631 cur.handleNest(createInsetMath(font, cur.buffer()));
1637 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1642 font.fromString(to_utf8(arg), b);
1643 if (font.fontInfo().color() != Color_inherit) {
1644 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1645 cur.handleNest(at, 0);
1650 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1653 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1654 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1655 enter_front ? idxFirst(cur) : idxLast(cur);
1656 // The inset formula dimension is not necessarily the same as the
1657 // one of the instant preview image, so we have to indicate to the
1658 // BufferView that a metrics update is needed.
1659 cur.screenUpdateFlags(Update::Force);
1663 void InsetMathHull::revealCodes(Cursor & cur) const
1665 if (!cur.inMathed())
1667 odocstringstream os;
1669 cur.message(os.str());
1671 // write something to the minibuffer
1672 // translate to latex
1676 string str = os.str();
1678 string::size_type pos = 0;
1680 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1683 else if (*it == '\0') {
1685 pos = it - str.begin();
1691 res = res.substr(pos - 30);
1692 if (res.size() > 60)
1693 res = res.substr(0, 60);
1699 /////////////////////////////////////////////////////////////////////
1703 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1706 // FIXME: completely broken
1707 static InsetMathHull * lastformula = 0;
1708 static CursorBase current = DocIterator(ibegin(nucleus()));
1710 static string laststr;
1712 if (lastformula != this || laststr != str) {
1713 //lyxerr << "reset lastformula to " << this << endl;
1716 current = ibegin(nucleus());
1718 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1722 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1724 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1725 CursorSlice & top = it.back();
1726 MathData const & a = top.asInsetMath()->cell(top.idx_);
1727 if (a.matchpart(ar, top.pos_)) {
1728 bv->cursor().setSelection(it, ar.size());
1730 top.pos_ += ar.size();
1736 //lyxerr << "not found!" << endl;
1743 void InsetMathHull::write(ostream & os) const
1745 odocstringstream oss;
1746 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1749 os << to_utf8(oss.str());
1753 void InsetMathHull::read(Lexer & lex)
1756 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1757 operator=(*at->asHullInset());
1761 bool InsetMathHull::readQuiet(Lexer & lex)
1764 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1766 operator=(*at->asHullInset());
1771 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1773 // disables ASCII-art for export of equations. See #2275.
1774 if (0 && display()) {
1778 TextPainter tpain(dim.width(), dim.height());
1779 drawT(tpain, 0, dim.ascent());
1781 // reset metrics cache to "real" values
1783 return tpain.textheight();
1785 odocstringstream oss;
1786 Encoding const * const enc = encodings.fromLyXName("utf8");
1787 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1789 if (type_ == hullRegexp)
1793 docstring const str = oss.str();
1800 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1805 if (getType() == hullSimple)
1806 name = from_ascii("inlineequation");
1808 name = from_ascii("informalequation");
1810 docstring bname = name;
1811 if (!label(0).empty())
1812 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1814 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1816 odocstringstream ls;
1817 if (runparams.flavor == OutputParams::XML) {
1818 ms << MTag("alt role='tex' ");
1819 // Workaround for db2latex: db2latex always includes equations with
1820 // \ensuremath{} or \begin{display}\end{display}
1821 // so we strip LyX' math environment
1822 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1823 InsetMathGrid::write(wi);
1824 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1829 InsetMathGrid::mathmlize(ms);
1832 ms << MTag("alt role='tex'");
1833 res = latex(ls, runparams);
1834 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1838 ms << from_ascii("<graphic fileref=\"eqn/");
1839 if (!label(0).empty())
1840 ms << sgml::cleanID(buffer(), runparams, label(0));
1842 ms << sgml::uniqueID(from_ascii("anon"));
1844 if (runparams.flavor == OutputParams::XML)
1845 ms << from_ascii("\"/>");
1847 ms << from_ascii("\">");
1849 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1851 return ms.line() + res;
1855 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
1857 BufferParams::MathOutput const mathtype =
1858 buffer().params().html_math_output;
1860 bool success = false;
1861 // FIXME Eventually we would like to do this inset by inset.
1862 if (mathtype == BufferParams::MathML) {
1863 odocstringstream os;
1866 InsetMathGrid::mathmlize(ms);
1868 } catch (MathExportException const &) {}
1870 if (getType() == hullSimple)
1871 xs << html::StartTag("math",
1872 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1874 xs << html::StartTag("math",
1875 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1876 xs << XHTMLStream::NextRaw()
1878 << html::EndTag("math");
1880 } else if (mathtype == BufferParams::HTML) {
1881 odocstringstream os;
1884 InsetMathGrid::htmlize(ms);
1886 } catch (MathExportException const &) {}
1888 string const tag = (getType() == hullSimple) ? "span" : "div";
1889 xs << html::StartTag(tag, "class='formula'", true)
1890 << XHTMLStream::NextRaw()
1892 << html::EndTag(tag);
1896 // what we actually want is this:
1898 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
1900 // || mathtype == BufferParams::Images
1902 // but what follows is equivalent, since we'll enter only if either (a) we
1903 // tried and failed with MathML or HTML or (b) didn't try yet at all but
1904 // aren't doing LaTeX, in which case we are doing Images.
1905 if (!success && mathtype != BufferParams::LaTeX) {
1906 loadPreview(docit_);
1907 graphics::PreviewImage const * pimage = preview_->getPreviewImage(buffer());
1909 // FIXME Do we always have png?
1910 string const tag = (getType() == hullSimple) ? "span" : "div";
1911 FileName const & mathimg = pimage->filename();
1912 xs << html::StartTag(tag)
1913 << html::CompTag("img", "src=\"" + mathimg.onlyFileName() + "\"")
1914 << html::EndTag(tag);
1916 // add the file to the list of files to be exported
1917 op.exportdata->addExternalFile("xhtml", mathimg);
1922 // so we'll pass this test if we've failed everything else, or
1923 // if mathtype was LaTeX, since we won't have entered any of the
1925 if (!success /* || mathtype != BufferParams::LaTeX */) {
1926 string const tag = (getType() == hullSimple) ? "span" : "div";
1927 // Unfortunately, we cannot use latexString() because we do not want
1928 // $...$ or whatever.
1929 odocstringstream ls;
1930 WriteStream wi(ls, false, true, WriteStream::wsPreview);
1931 ModeSpecifier specifier(wi, MATH_MODE);
1932 InsetMathGrid::write(wi);
1933 docstring const latex = ls.str();
1935 // class='math' allows for use of jsMath
1936 // http://www.math.union.edu/~dpvc/jsMath/
1938 // probably should allow for some kind of customization here
1939 xs << html::StartTag(tag, "class='math'")
1941 << html::EndTag(tag);
1948 void InsetMathHull::tocString(odocstream & os) const
1950 plaintext(os, OutputParams(0));
1954 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1956 return from_ascii("context-math");
1960 void InsetMathHull::recordLocation(DocIterator const & di)