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"
32 #include "LaTeXFeatures.h"
34 #include "MacroTable.h"
35 #include "output_xhtml.h"
36 #include "Paragraph.h"
37 #include "ParIterator.h"
39 #include "TextClass.h"
40 #include "TextPainter.h"
41 #include "TocBackend.h"
43 #include "insets/InsetLabel.h"
44 #include "insets/InsetRef.h"
45 #include "insets/RenderPreview.h"
47 #include "graphics/PreviewImage.h"
48 #include "graphics/PreviewLoader.h"
50 #include "frontends/alert.h"
51 #include "frontends/Painter.h"
53 #include "support/convert.h"
54 #include "support/lassert.h"
55 #include "support/debug.h"
56 #include "support/filetools.h"
57 #include "support/gettext.h"
58 #include "support/lstrings.h"
63 using namespace lyx::support;
67 using cap::grabAndEraseSelection;
71 int getCols(HullType type)
88 // returns position of first relation operator in the array
89 // used for "intelligent splitting"
90 size_t firstRelOp(MathData const & ar)
92 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
94 return it - ar.begin();
99 char const * star(bool numbered)
101 return numbered ? "" : "*";
105 } // end anon namespace
108 HullType hullType(docstring const & s)
110 if (s == "none") return hullNone;
111 if (s == "simple") return hullSimple;
112 if (s == "equation") return hullEquation;
113 if (s == "eqnarray") return hullEqnArray;
114 if (s == "align") return hullAlign;
115 if (s == "alignat") return hullAlignAt;
116 if (s == "xalignat") return hullXAlignAt;
117 if (s == "xxalignat") return hullXXAlignAt;
118 if (s == "multline") return hullMultline;
119 if (s == "gather") return hullGather;
120 if (s == "flalign") return hullFlAlign;
121 if (s == "regexp") return hullRegexp;
122 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
127 docstring hullName(HullType type)
130 case hullNone: return from_ascii("none");
131 case hullSimple: return from_ascii("simple");
132 case hullEquation: return from_ascii("equation");
133 case hullEqnArray: return from_ascii("eqnarray");
134 case hullAlign: return from_ascii("align");
135 case hullAlignAt: return from_ascii("alignat");
136 case hullXAlignAt: return from_ascii("xalignat");
137 case hullXXAlignAt: return from_ascii("xxalignat");
138 case hullMultline: return from_ascii("multline");
139 case hullGather: return from_ascii("gather");
140 case hullFlAlign: return from_ascii("flalign");
141 case hullRegexp: return from_ascii("regexp");
143 lyxerr << "unknown hull type '" << type << "'" << endl;
144 return from_ascii("none");
148 static InsetLabel * dummy_pointer = 0;
150 InsetMathHull::InsetMathHull(Buffer * buf)
151 : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, true),
152 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
153 preview_(new RenderPreview(this))
155 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
156 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
157 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
158 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
165 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
166 : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, true),
167 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
168 preview_(new RenderPreview(this))
176 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
182 InsetMathHull::~InsetMathHull()
184 for (size_t i = 0; i < label_.size(); ++i)
189 Inset * InsetMathHull::clone() const
191 return new InsetMathHull(*this);
195 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
199 InsetMathGrid::operator=(other);
201 numbered_ = other.numbered_;
202 numbers_ = other.numbers_;
203 buffer_ = other.buffer_;
204 for (size_t i = 0; i < label_.size(); ++i)
206 label_ = other.label_;
207 for (size_t i = 0; i != label_.size(); ++i) {
209 label_[i] = new InsetLabel(*label_[i]);
211 preview_.reset(new RenderPreview(*other.preview_, this));
217 void InsetMathHull::setBuffer(Buffer & buffer)
219 InsetMathGrid::setBuffer(buffer);
221 for (size_t i = 0; i != label_.size(); ++i) {
223 label_[i]->setBuffer(buffer);
229 const char * counters_to_save[] = {"section", "chapter"};
230 unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
234 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
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 // if any of the equations are numbered, then we want to save the values
244 // of some of the counters.
246 BufferParams const & bp = buffer_->params();
247 string const & lang = it->getParLanguage(bp)->code();
249 buffer_->masterBuffer()->params().documentClass().counters();
251 // right now, we only need to do this at export time
252 if (utype == OutputUpdate) {
253 for (size_t i = 0; i < numcnts; ++i) {
254 docstring const cnt = from_ascii(counters_to_save[i]);
255 if (cnts.hasCounter(cnt))
256 counter_map[cnt] = cnts.value(cnt);
260 // this has to be done separately
261 docstring const eqstr = from_ascii("equation");
262 if (cnts.hasCounter(eqstr)) {
263 if (utype == OutputUpdate)
264 counter_map[eqstr] = cnts.value(eqstr);
265 for (size_t i = 0; i != label_.size(); ++i) {
267 cnts.step(eqstr, utype);
268 numbers_[i] = cnts.theCounter(eqstr, lang);
270 numbers_[i] = empty_docstring();
276 for (size_t i = 0; i != label_.size(); ++i) {
278 label_[i]->updateBuffer(it, utype);
281 InsetMathGrid::updateBuffer(it, utype);
285 void InsetMathHull::addToToc(DocIterator const & pit) const
288 //FIXME: buffer_ should be set at creation for this inset! Problem is
289 // This inset is created at too many places (see Parser::parse1() in
294 Toc & toc = buffer().tocBackend().toc("equation");
296 for (row_type row = 0; row != nrows(); ++row) {
300 label_[row]->addToToc(pit);
301 toc.push_back(TocItem(pit, 0, nicelabel(row)));
306 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
312 return InsetMathNest::editXY(cur, x, y);
316 InsetMath::mode_type InsetMathHull::currentMode() const
318 if (type_ == hullNone)
319 return UNDECIDED_MODE;
320 // definitely math mode ...
325 bool InsetMathHull::idxFirst(Cursor & cur) const
333 bool InsetMathHull::idxLast(Cursor & cur) const
335 cur.idx() = nargs() - 1;
336 cur.pos() = cur.lastpos();
341 char InsetMathHull::defaultColAlign(col_type col)
343 if (type_ == hullEqnArray)
345 if (type_ == hullGather)
347 if (type_ >= hullAlign)
348 return "rl"[col & 1];
353 int InsetMathHull::defaultColSpace(col_type col)
355 if (type_ == hullAlign || type_ == hullAlignAt)
357 if (type_ == hullXAlignAt)
358 return (col & 1) ? 20 : 0;
359 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
360 return (col & 1) ? 40 : 0;
365 docstring InsetMathHull::standardFont() const
370 font_name = from_ascii("texttt");
373 font_name = from_ascii("lyxnochange");
376 font_name = from_ascii("mathnormal");
382 ColorCode InsetMathHull::standardColor() const
388 color = Color_foreground;
397 bool InsetMathHull::previewState(BufferView * bv) const
399 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
400 graphics::PreviewImage const * pimage =
401 preview_->getPreviewImage(bv->buffer());
402 return pimage && pimage->image();
408 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
410 if (previewState(mi.base.bv)) {
411 preview_->metrics(mi, dim);
412 // insert a one pixel gap in front of the formula
415 dim.des += displayMargin();
416 // Cache the inset dimension.
417 setDimCache(mi, dim);
421 FontSetChanger dummy1(mi.base, standardFont());
422 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
424 // let the cells adjust themselves
425 InsetMathGrid::metrics(mi, dim);
428 dim.asc += displayMargin();
429 dim.des += displayMargin();
432 if (numberedType()) {
433 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
435 for (row_type row = 0; row < nrows(); ++row)
436 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
442 if (type_ == hullRegexp)
444 // make it at least as high as the current font
447 math_font_max_dim(mi.base.font, asc, des);
448 dim.asc = max(dim.asc, asc);
449 dim.des = max(dim.des, des);
450 // Cache the inset dimension.
451 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
452 setDimCache(mi, dim);
456 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
458 if (previewState(pi.base.bv))
459 return graphics::PreviewLoader::backgroundColor();
464 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
466 Dimension const dim = dimension(*pi.base.bv);
467 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
468 dim.asc + dim.des - 1, pi.backgroundColor(this));
472 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
474 use_preview_ = previewState(pi.base.bv);
476 if (type_ == hullRegexp) {
477 Dimension const dim = dimension(*pi.base.bv);
478 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
479 dim.width() - 2, dim.height() - 2, Color_regexpframe);
482 // one pixel gap in front
483 preview_->draw(pi, x + 1, y);
484 setPosCache(pi, x, y);
488 ColorCode color = pi.selected && lyxrc.use_system_colors
489 ? Color_selectiontext : standardColor();
490 bool const really_change_color = pi.base.font.color() == Color_none;
491 ColorChanger dummy0(pi.base.font, color, really_change_color);
492 FontSetChanger dummy1(pi.base, standardFont());
493 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
495 InsetMathGrid::draw(pi, x + 1, y);
497 if (numberedType()) {
498 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
499 for (row_type row = 0; row < nrows(); ++row) {
500 int const yy = y + rowinfo_[row].offset_;
501 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
502 docstring const nl = nicelabel(row);
506 setPosCache(pi, x, y);
510 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
513 InsetMathGrid::metricsT(mi, dim);
516 WriteStream wi(os, false, true, WriteStream::wsDefault);
518 dim.wid = os.str().size();
525 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
528 InsetMathGrid::drawT(pain, x, y);
531 WriteStream wi(os, false, true, WriteStream::wsDefault);
533 pain.draw(x, y, os.str().c_str());
538 static docstring latexString(InsetMathHull const & inset)
541 // This has to be static, because a preview snippet or a math
542 // macro containing math in text mode (such as $\text{$\phi$}$ or
543 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
544 // first time as a whole, and the second time only the inner math.
545 // In this last case inset.buffer() would be invalid.
546 static Encoding const * encoding = 0;
547 if (inset.isBufferValid())
548 encoding = &(inset.buffer().params().encoding());
549 WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
555 void InsetMathHull::initUnicodeMath() const
557 // Trigger classification of the unicode symbols in this inset
558 docstring const dummy = latexString(*this);
562 void InsetMathHull::addPreview(DocIterator const & inset_pos,
563 graphics::PreviewLoader & /*ploader*/) const
565 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
566 preparePreview(inset_pos);
571 void InsetMathHull::preparePreview(DocIterator const & pos,
572 bool forexport) const
574 // there is no need to do all the macro stuff if we're not
575 // actually going to generate the preview.
576 if (RenderPreview::status() != LyXRC::PREVIEW_ON && !forexport)
579 Buffer const * buffer = pos.buffer();
581 // collect macros at this position
583 buffer->listMacroNames(macros);
584 MacroNameSet::iterator it = macros.begin();
585 MacroNameSet::iterator end = macros.end();
586 odocstringstream macro_preamble;
587 for (; it != end; ++it) {
588 MacroData const * data = buffer->getMacro(*it, pos, true);
590 data->write(macro_preamble, true);
591 macro_preamble << endl;
596 if (forexport && haveNumbers()) {
597 docstring eqstr = from_ascii("equation");
598 CounterMap::const_iterator it = counter_map.find(eqstr);
599 if (it != counter_map.end()) {
600 int num = it->second;
602 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
603 '{' + convert<docstring>(num) + '}' + '\n';
605 for (size_t i = 0; i != numcnts; ++i) {
606 docstring cnt = from_ascii(counters_to_save[i]);
607 it = counter_map.find(cnt);
608 if (it == counter_map.end())
610 int num = it->second;
612 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
613 '{' + convert<docstring>(num) + '}';
616 docstring const snippet = macro_preamble.str() +
617 setcnt + latexString(*this);
618 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
619 preview_->addPreview(snippet, *buffer, forexport);
623 void InsetMathHull::reloadPreview(DocIterator const & pos) const
626 preview_->startLoading(*pos.buffer());
630 void InsetMathHull::loadPreview(DocIterator const & pos) const
632 bool const forexport = true;
633 preparePreview(pos, forexport);
634 preview_->startLoading(*pos.buffer(), forexport);
638 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
640 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
642 cur.screenUpdateFlags(Update::Force);
648 docstring InsetMathHull::label(row_type row) const
650 LASSERT(row < nrows(), /**/);
651 if (InsetLabel * il = label_[row])
652 return il->screenLabel();
657 void InsetMathHull::label(row_type row, docstring const & label)
659 //lyxerr << "setting label '" << label << "' for row " << row << endl;
663 label_[row] = dummy_pointer;
666 label_[row]->updateLabelAndRefs(label);
668 label_[row]->setParam("name", label);
672 InsetCommandParams p(LABEL_CODE);
674 label_[row] = new InsetLabel(buffer_, p);
676 label_[row]->setBuffer(buffer());
680 void InsetMathHull::numbered(row_type row, bool num)
682 numbered_[row] = num;
683 if (!numbered_[row] && label_[row]) {
690 bool InsetMathHull::numbered(row_type row) const
692 return numbered_[row];
696 bool InsetMathHull::ams() const
698 return type_ == hullAlign
699 || type_ == hullFlAlign
700 || type_ == hullMultline
701 || type_ == hullGather
702 || type_ == hullAlignAt
703 || type_ == hullXAlignAt
704 || type_ == hullXXAlignAt;
708 Inset::DisplayType InsetMathHull::display() const
710 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
715 bool InsetMathHull::numberedType() const
717 if (type_ == hullNone)
719 if (type_ == hullSimple)
721 if (type_ == hullXXAlignAt)
723 if (type_ == hullRegexp)
725 for (row_type row = 0; row < nrows(); ++row)
732 void InsetMathHull::validate(LaTeXFeatures & features) const
734 if (features.runparams().isLaTeX()) {
736 features.require("amsmath");
738 if (type_ == hullRegexp) {
739 features.require("color");
740 string frcol = lcolor.getLaTeXName(Color_regexpframe);
741 string bgcol = "white";
742 features.addPreambleSnippet(
743 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
744 + frcol + string("}{")
745 + bgcol + string("}{\\ensuremath{\\mathtt{#1}}}}"));
748 // Validation is necessary only if not using AMS math.
749 // To be safe, we will always run mathedvalidate.
750 //if (features.amsstyle)
753 //features.binom = true;
754 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
755 // it would be better to do this elsewhere, but we can't validate in
756 // InsetMathMatrix and we have no way, outside MathExtern, to know if
757 // we even have any matrices.
758 features.addPreambleSnippet("<style type=\"text/css\">\n"
759 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
760 "table.matrix td{padding: 0.25px;}\n"
761 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
762 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}\n"
765 InsetMathGrid::validate(features);
769 void InsetMathHull::header_write(WriteStream & os) const
771 bool n = numberedType();
785 os << "\n\\begin{equation" << star(n) << "}\n";
795 os << "\n\\begin{" << hullName(type_) << star(n) << "}\n";
800 os << "\n\\begin{" << hullName(type_) << star(n) << '}'
801 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
805 os << "\n\\begin{" << hullName(type_) << '}'
806 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
814 os << "\n\\begin{unknown" << star(n) << "}\n";
820 void InsetMathHull::footer_write(WriteStream & os) const
822 bool n = numberedType();
835 os << "\n\\end{equation" << star(n) << "}\n";
847 os << "\n\\end{" << hullName(type_) << star(n) << "}\n";
851 os << "\n\\end{" << hullName(type_) << "}\n";
859 os << "\n\\end{unknown" << star(n) << "}\n";
865 bool InsetMathHull::rowChangeOK() const
868 type_ == hullEqnArray || type_ == hullAlign ||
869 type_ == hullFlAlign || type_ == hullAlignAt ||
870 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
871 type_ == hullGather || type_ == hullMultline;
875 bool InsetMathHull::colChangeOK() const
878 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
879 type_ == hullXAlignAt || type_ == hullXXAlignAt;
883 void InsetMathHull::addRow(row_type row)
888 bool numbered = numberedType();
889 // Move the number and raw pointer, do not call label() (bug 7511)
890 InsetLabel * label = dummy_pointer;
891 docstring number = empty_docstring();
892 if (type_ == hullMultline) {
893 if (row + 1 == nrows()) {
894 numbered_[row] = false;
895 swap(label, label_[row]);
896 swap(number, numbers_[row]);
901 numbered_.insert(numbered_.begin() + row + 1, numbered);
902 numbers_.insert(numbers_.begin() + row + 1, number);
903 label_.insert(label_.begin() + row + 1, label);
904 InsetMathGrid::addRow(row);
908 void InsetMathHull::swapRow(row_type row)
912 if (row + 1 == nrows())
914 // gcc implements the standard std::vector<bool> which is *not* a container:
915 // http://www.gotw.ca/publications/N1185.pdf
916 // As a results, it doesn't like this:
917 // swap(numbered_[row], numbered_[row + 1]);
918 // so we do it manually:
919 bool const b = numbered_[row];
920 numbered_[row] = numbered_[row + 1];
921 numbered_[row + 1] = b;
922 swap(numbers_[row], numbers_[row + 1]);
923 swap(label_[row], label_[row + 1]);
924 InsetMathGrid::swapRow(row);
928 void InsetMathHull::delRow(row_type row)
930 if (nrows() <= 1 || !rowChangeOK())
932 if (row + 1 == nrows() && type_ == hullMultline) {
933 bool const b = numbered_[row - 1];
934 numbered_[row - 1] = numbered_[row];
936 swap(numbers_[row - 1], numbers_[row]);
937 swap(label_[row - 1], label_[row]);
938 InsetMathGrid::delRow(row);
941 InsetMathGrid::delRow(row);
942 // The last dummy row has no number info nor a label.
943 // Test nrows() + 1 because we have already erased the row.
944 if (row == nrows() + 1)
946 numbered_.erase(numbered_.begin() + row);
947 numbers_.erase(numbers_.begin() + row);
949 label_.erase(label_.begin() + row);
953 void InsetMathHull::addCol(col_type col)
957 InsetMathGrid::addCol(col);
961 void InsetMathHull::delCol(col_type col)
963 if (ncols() <= 1 || !colChangeOK())
965 InsetMathGrid::delCol(col);
969 docstring InsetMathHull::nicelabel(row_type row) const
973 docstring const & val = numbers_[row];
975 return '(' + val + ')';
976 return '(' + val + ',' + label_[row]->screenLabel() + ')';
980 void InsetMathHull::glueall(HullType type)
983 for (idx_type i = 0; i < nargs(); ++i)
985 InsetLabel * label = 0;
986 if (type == hullEquation) {
987 // preserve first non-empty label
988 for (row_type row = 0; row < nrows(); ++row) {
996 *this = InsetMathHull(buffer_, hullSimple);
1003 void InsetMathHull::splitTo2Cols()
1005 LASSERT(ncols() == 1, /**/);
1006 InsetMathGrid::addCol(1);
1007 for (row_type row = 0; row < nrows(); ++row) {
1008 idx_type const i = 2 * row;
1009 pos_type pos = firstRelOp(cell(i));
1010 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1011 cell(i).erase(pos, cell(i).size());
1016 void InsetMathHull::splitTo3Cols()
1018 LASSERT(ncols() < 3, /**/);
1021 InsetMathGrid::addCol(2);
1022 for (row_type row = 0; row < nrows(); ++row) {
1023 idx_type const i = 3 * row + 1;
1024 if (cell(i).size()) {
1025 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1026 cell(i).erase(1, cell(i).size());
1032 void InsetMathHull::changeCols(col_type cols)
1034 if (ncols() == cols)
1036 else if (ncols() < cols) {
1042 while (ncols() < cols)
1043 InsetMathGrid::addCol(ncols());
1049 for (row_type row = 0; row < nrows(); ++row) {
1050 idx_type const i = row * ncols();
1051 for (col_type col = cols; col < ncols(); ++col) {
1052 cell(i + cols - 1).append(cell(i + col));
1056 while (ncols() > cols) {
1057 InsetMathGrid::delCol(ncols() - 1);
1062 HullType InsetMathHull::getType() const
1068 void InsetMathHull::setType(HullType type)
1075 void InsetMathHull::mutate(HullType newtype)
1077 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1079 // we try to move along the chain
1080 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1082 // +-------------------------------------+
1083 // we use eqnarray as intermediate type for mutations that are not
1084 // directly supported because it handles labels and numbering for
1087 if (newtype == type_) {
1091 else if (newtype < hullNone) {
1096 else if (type_ == hullNone) {
1097 setType(hullSimple);
1102 else if (type_ == hullSimple) {
1103 if (newtype == hullNone) {
1107 setType(hullEquation);
1108 numbered(0, label_[0] ? true : false);
1113 else if (type_ == hullEquation) {
1114 if (newtype < type_) {
1115 setType(hullSimple);
1118 } else if (newtype == hullEqnArray) {
1119 // split it "nicely" on the first relop
1121 setType(hullEqnArray);
1122 } else if (newtype == hullMultline || newtype == hullGather) {
1125 // split it "nicely"
1132 else if (type_ == hullEqnArray) {
1133 if (newtype < type_) {
1136 } else { // align & Co.
1143 else if (type_ == hullAlign || type_ == hullAlignAt ||
1144 type_ == hullXAlignAt || type_ == hullFlAlign) {
1145 if (newtype < hullAlign) {
1147 setType(hullEqnArray);
1149 } else if (newtype == hullGather || newtype == hullMultline) {
1152 } else if (newtype == hullXXAlignAt) {
1153 for (row_type row = 0; row < nrows(); ++row)
1154 numbered(row, false);
1161 else if (type_ == hullXXAlignAt) {
1162 for (row_type row = 0; row < nrows(); ++row)
1163 numbered(row, false);
1164 if (newtype < hullAlign) {
1166 setType(hullEqnArray);
1168 } else if (newtype == hullGather || newtype == hullMultline) {
1176 else if (type_ == hullMultline || type_ == hullGather) {
1177 if (newtype == hullGather || newtype == hullMultline)
1179 else if (newtype == hullAlign || newtype == hullFlAlign ||
1180 newtype == hullAlignAt || newtype == hullXAlignAt) {
1183 } else if (newtype == hullXXAlignAt) {
1185 for (row_type row = 0; row < nrows(); ++row)
1186 numbered(row, false);
1190 setType(hullEqnArray);
1196 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1197 << "' to '" << to_utf8(hullName(newtype))
1198 << "' not implemented" << endl;
1203 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1204 bool last_eoln) const
1207 if (numberedType()) {
1208 if (label_[row] && numbered_[row]) {
1209 docstring const name =
1210 latex ? escape(label_[row]->getParam("name"))
1211 : label_[row]->getParam("name");
1212 res += "\\label{" + name + '}';
1214 if (!numbered_[row] && (type_ != hullMultline))
1215 res += "\\nonumber ";
1217 // Never add \\ on the last empty line of eqnarray and friends
1219 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1223 void InsetMathHull::write(WriteStream & os) const
1225 ModeSpecifier specifier(os, MATH_MODE);
1227 InsetMathGrid::write(os);
1232 void InsetMathHull::normalize(NormalStream & os) const
1234 os << "[formula " << hullName(type_) << ' ';
1235 InsetMathGrid::normalize(os);
1240 void InsetMathHull::infoize(odocstream & os) const
1242 os << "Type: " << hullName(type_);
1246 void InsetMathHull::check() const
1248 LASSERT(numbered_.size() == nrows(), /**/);
1249 LASSERT(numbers_.size() == nrows(), /**/);
1250 LASSERT(label_.size() == nrows(), /**/);
1254 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1258 idocstringstream iss(func.argument());
1259 iss >> dlang >> extra;
1261 extra = from_ascii("noextra");
1262 string const lang = to_ascii(dlang);
1264 // FIXME: temporarily disabled
1265 //if (cur.selection()) {
1268 // lyxerr << "use selection: " << ar << endl;
1269 // insert(pipeThroughExtern(lang, extra, ar));
1273 // only inline, display or eqnarray math is allowed
1274 if (getType() > hullEqnArray) {
1275 frontend::Alert::warning(_("Bad math environment"),
1276 _("Computation cannot be performed for AMS "
1277 "math environments.\nChange the math "
1278 "formula type and try again."));
1283 eq.push_back(MathAtom(new InsetMathChar('=')));
1285 // go to first item in line
1286 cur.idx() -= cur.idx() % ncols();
1289 if (getType() == hullSimple) {
1290 size_type pos = cur.cell().find_last(eq);
1292 if (cur.inMathed() && cur.selection()) {
1293 asArray(grabAndEraseSelection(cur), ar);
1294 } else if (pos == cur.cell().size()) {
1296 lyxerr << "use whole cell: " << ar << endl;
1298 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1299 lyxerr << "use partial cell form pos: " << pos << endl;
1301 cur.cell().append(eq);
1302 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1303 cur.pos() = cur.lastpos();
1307 if (getType() == hullEquation) {
1308 lyxerr << "use equation inset" << endl;
1309 mutate(hullEqnArray);
1310 MathData & ar = cur.cell();
1311 lyxerr << "use cell: " << ar << endl;
1315 cur.cell() = pipeThroughExtern(lang, extra, ar);
1316 // move to end of line
1317 cur.pos() = cur.lastpos();
1322 lyxerr << "use eqnarray" << endl;
1323 cur.idx() += 2 - cur.idx() % ncols();
1325 MathData ar = cur.cell();
1326 lyxerr << "use cell: " << ar << endl;
1327 // FIXME: temporarily disabled
1333 cur.cell() = pipeThroughExtern(lang, extra, ar);
1334 cur.pos() = cur.lastpos();
1339 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1341 //lyxerr << "action: " << cmd.action() << endl;
1342 switch (cmd.action()) {
1344 case LFUN_FINISHED_BACKWARD:
1345 case LFUN_FINISHED_FORWARD:
1346 case LFUN_FINISHED_RIGHT:
1347 case LFUN_FINISHED_LEFT:
1348 //lyxerr << "action: " << cmd.action() << endl;
1349 InsetMathGrid::doDispatch(cur, cmd);
1353 case LFUN_BREAK_PARAGRAPH:
1354 // just swallow this
1357 case LFUN_NEWLINE_INSERT:
1358 // some magic for the common case
1359 if (type_ == hullSimple || type_ == hullEquation) {
1360 cur.recordUndoInset();
1362 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1363 mutate(align ? hullAlign : hullEqnArray);
1364 // mutate() may change labels and such.
1365 cur.forceBufferUpdate();
1366 cur.idx() = nrows() * ncols() - 1;
1367 cur.pos() = cur.lastpos();
1369 InsetMathGrid::doDispatch(cur, cmd);
1372 case LFUN_MATH_NUMBER_TOGGLE: {
1373 //lyxerr << "toggling all numbers" << endl;
1374 cur.recordUndoInset();
1375 bool old = numberedType();
1376 if (type_ == hullMultline)
1377 numbered(nrows() - 1, !old);
1379 for (row_type row = 0; row < nrows(); ++row)
1380 numbered(row, !old);
1382 cur.message(old ? _("No number") : _("Number"));
1383 cur.forceBufferUpdate();
1387 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1388 cur.recordUndoInset();
1389 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1390 bool old = numbered(r);
1391 cur.message(old ? _("No number") : _("Number"));
1393 cur.forceBufferUpdate();
1397 case LFUN_LABEL_INSERT: {
1398 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1399 docstring old_label = label(r);
1400 docstring const default_label = from_ascii("eq:");
1401 if (old_label.empty())
1402 old_label = default_label;
1404 InsetCommandParams p(LABEL_CODE);
1405 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1406 string const data = InsetCommand::params2string(p);
1408 if (cmd.argument().empty())
1409 cur.bv().showDialog("label", data);
1411 FuncRequest fr(LFUN_INSET_INSERT, data);
1417 case LFUN_LABEL_COPY_AS_REF: {
1419 if (cmd.argument().empty() && &cur.inset() == this)
1420 // if there is no argument and we're inside math, we retrieve
1421 // the row number from the cursor position.
1422 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1424 // if there is an argument, find the corresponding label, else
1425 // check whether there is at least one label.
1426 for (row = 0; row != nrows(); ++row)
1427 if (numbered_[row] && label_[row]
1428 && (cmd.argument().empty() || label(row) == cmd.argument()))
1435 InsetCommandParams p(REF_CODE, "ref");
1436 p["reference"] = label(row);
1437 cap::clearSelection();
1438 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1442 case LFUN_WORD_DELETE_FORWARD:
1443 case LFUN_CHAR_DELETE_FORWARD:
1444 if (col(cur.idx()) + 1 == ncols()
1445 && cur.pos() == cur.lastpos()
1446 && !cur.selection()) {
1447 if (!label(row(cur.idx())).empty()) {
1448 cur.recordUndoInset();
1449 label(row(cur.idx()), docstring());
1450 } else if (numbered(row(cur.idx()))) {
1451 cur.recordUndoInset();
1452 numbered(row(cur.idx()), false);
1453 cur.forceBufferUpdate();
1455 InsetMathGrid::doDispatch(cur, cmd);
1459 InsetMathGrid::doDispatch(cur, cmd);
1464 case LFUN_INSET_INSERT: {
1465 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1466 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1467 string const name = cmd.getArg(0);
1468 if (name == "label") {
1469 InsetCommandParams p(LABEL_CODE);
1470 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1471 docstring str = p["name"];
1472 cur.recordUndoInset();
1473 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1477 docstring old = label(r);
1480 // The label will take care of the reference update.
1484 // Newly created inset so initialize it.
1485 label_[r]->initView();
1488 cur.forceBufferUpdate();
1491 InsetMathGrid::doDispatch(cur, cmd);
1495 case LFUN_MATH_EXTERN:
1496 cur.recordUndoInset();
1500 case LFUN_MATH_MUTATE: {
1501 cur.recordUndoInset();
1502 row_type row = cur.row();
1503 col_type col = cur.col();
1504 mutate(hullType(cmd.argument()));
1505 cur.idx() = row * ncols() + col;
1506 if (cur.idx() > cur.lastidx()) {
1507 cur.idx() = cur.lastidx();
1508 cur.pos() = cur.lastpos();
1510 if (cur.pos() > cur.lastpos())
1511 cur.pos() = cur.lastpos();
1513 cur.forceBufferUpdate();
1514 // FIXME: find some more clever handling of the selection,
1515 // i.e. preserve it.
1516 cur.clearSelection();
1517 //cur.dispatched(FINISHED);
1521 case LFUN_MATH_DISPLAY: {
1522 cur.recordUndoInset();
1523 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1525 cur.pos() = cur.lastpos();
1526 //cur.dispatched(FINISHED);
1531 InsetMathGrid::doDispatch(cur, cmd);
1537 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1538 FuncStatus & status) const
1540 switch (cmd.action()) {
1541 case LFUN_FINISHED_BACKWARD:
1542 case LFUN_FINISHED_FORWARD:
1543 case LFUN_FINISHED_RIGHT:
1544 case LFUN_FINISHED_LEFT:
1547 case LFUN_NEWLINE_INSERT:
1548 case LFUN_MATH_EXTERN:
1550 status.setEnabled(true);
1553 // we never allow this in math, and we want to bind enter
1554 // to another actions in command-alternatives
1555 case LFUN_BREAK_PARAGRAPH:
1556 status.setEnabled(false);
1558 case LFUN_MATH_MUTATE: {
1559 HullType const ht = hullType(cmd.argument());
1560 status.setOnOff(type_ == ht);
1561 status.setEnabled(true);
1563 if (ht != hullSimple) {
1564 Cursor tmpcur = cur;
1565 while (!tmpcur.empty()) {
1566 InsetCode code = tmpcur.inset().lyxCode();
1567 if (code == BOX_CODE) {
1569 } else if (code == TABULAR_CODE) {
1570 FuncRequest tmpcmd(LFUN_MATH_DISPLAY);
1571 if (tmpcur.getStatus(tmpcmd, status) && !status.enabled())
1579 case LFUN_MATH_DISPLAY: {
1581 if (cur.depth() > 1) {
1582 Inset const & in = cur[cur.depth()-2].inset();
1583 if (in.lyxCode() == SCRIPT_CODE)
1584 enable = display() != Inline;
1586 status.setEnabled(enable);
1590 case LFUN_MATH_NUMBER_TOGGLE:
1591 // FIXME: what is the right test, this or the one of
1593 status.setEnabled(display() != Inline);
1594 status.setOnOff(numberedType());
1597 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1598 // FIXME: what is the right test, this or the one of
1600 bool const enable = (type_ == hullMultline)
1601 ? (nrows() - 1 == cur.row())
1602 : display() != Inline;
1603 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1604 status.setEnabled(enable);
1605 status.setOnOff(enable && numbered(r));
1609 case LFUN_LABEL_INSERT:
1610 status.setEnabled(type_ != hullSimple);
1613 case LFUN_LABEL_COPY_AS_REF: {
1614 bool enabled = false;
1616 if (cmd.argument().empty() && &cur.inset() == this) {
1617 // if there is no argument and we're inside math, we retrieve
1618 // the row number from the cursor position.
1619 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1620 enabled = numberedType() && label_[row] && numbered_[row];
1622 // if there is an argument, find the corresponding label, else
1623 // check whether there is at least one label.
1624 for (row_type row = 0; row != nrows(); ++row) {
1625 if (numbered_[row] && label_[row] &&
1626 (cmd.argument().empty() || label(row) == cmd.argument())) {
1632 status.setEnabled(enabled);
1636 case LFUN_INSET_INSERT:
1637 if (cmd.getArg(0) == "label") {
1638 status.setEnabled(type_ != hullSimple);
1641 return InsetMathGrid::getStatus(cur, cmd, status);
1643 case LFUN_INSET_MODIFY: {
1644 istringstream is(to_utf8(cmd.argument()));
1648 return InsetMathGrid::getStatus(cur, cmd, status);
1651 && (s == "append-row"
1652 || s == "delete-row"
1653 || s == "copy-row")) {
1654 status.message(bformat(
1655 from_utf8(N_("Can't change number of rows in '%1$s'")),
1657 status.setEnabled(false);
1661 && (s == "append-column"
1662 || s == "delete-column"
1663 || s == "copy-column")) {
1664 status.message(bformat(
1665 from_utf8(N_("Can't change number of columns in '%1$s'")),
1667 status.setEnabled(false);
1670 if ((type_ == hullSimple
1671 || type_ == hullEquation
1672 || type_ == hullNone) &&
1673 (s == "add-hline-above" || s == "add-hline-below")) {
1674 status.message(bformat(
1675 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1677 status.setEnabled(false);
1680 if (s == "add-vline-left" || s == "add-vline-right") {
1681 status.message(bformat(
1682 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1684 status.setEnabled(false);
1687 if (s == "valign-top" || s == "valign-middle"
1688 || s == "valign-bottom" || s == "align-left"
1689 || s == "align-center" || s == "align-right") {
1690 status.setEnabled(false);
1693 return InsetMathGrid::getStatus(cur, cmd, status);
1697 return InsetMathGrid::getStatus(cur, cmd, status);
1700 // This cannot really happen, but inserted to shut-up gcc
1701 return InsetMathGrid::getStatus(cur, cmd, status);
1705 /////////////////////////////////////////////////////////////////////
1709 // simply scrap this function if you want
1710 void InsetMathHull::mutateToText()
1713 // translate to latex
1715 latex(os, false, false);
1716 string str = os.str();
1719 Text * lt = view_->cursor().innerText();
1720 string::const_iterator cit = str.begin();
1721 string::const_iterator end = str.end();
1722 for (; cit != end; ++cit)
1723 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1726 //dispatch(LFUN_ESCAPE);
1731 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1732 docstring const & font)
1734 // this whole function is a hack and won't work for incremental font
1737 if (cur.inset().asInsetMath()->name() == font)
1738 cur.handleFont(to_utf8(font));
1740 cur.handleNest(createInsetMath(font, cur.buffer()));
1746 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1751 font.fromString(to_utf8(arg), b);
1752 if (font.fontInfo().color() != Color_inherit) {
1753 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1754 cur.handleNest(at, 0);
1759 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1762 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1763 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1764 enter_front ? idxFirst(cur) : idxLast(cur);
1765 // The inset formula dimension is not necessarily the same as the
1766 // one of the instant preview image, so we have to indicate to the
1767 // BufferView that a metrics update is needed.
1768 cur.screenUpdateFlags(Update::Force);
1772 void InsetMathHull::revealCodes(Cursor & cur) const
1774 if (!cur.inMathed())
1776 odocstringstream os;
1778 cur.message(os.str());
1780 // write something to the minibuffer
1781 // translate to latex
1785 string str = os.str();
1787 string::size_type pos = 0;
1789 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1792 else if (*it == '\0') {
1794 pos = it - str.begin();
1800 res = res.substr(pos - 30);
1801 if (res.size() > 60)
1802 res = res.substr(0, 60);
1808 /////////////////////////////////////////////////////////////////////
1812 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1815 // FIXME: completely broken
1816 static InsetMathHull * lastformula = 0;
1817 static CursorBase current = DocIterator(ibegin(nucleus()));
1819 static string laststr;
1821 if (lastformula != this || laststr != str) {
1822 //lyxerr << "reset lastformula to " << this << endl;
1825 current = ibegin(nucleus());
1827 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1831 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1833 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1834 CursorSlice & top = it.back();
1835 MathData const & a = top.asInsetMath()->cell(top.idx_);
1836 if (a.matchpart(ar, top.pos_)) {
1837 bv->cursor().setSelection(it, ar.size());
1839 top.pos_ += ar.size();
1845 //lyxerr << "not found!" << endl;
1852 void InsetMathHull::write(ostream & os) const
1854 odocstringstream oss;
1855 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1858 os << to_utf8(oss.str());
1862 void InsetMathHull::read(Lexer & lex)
1865 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1866 operator=(*at->asHullInset());
1870 bool InsetMathHull::readQuiet(Lexer & lex)
1873 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1875 operator=(*at->asHullInset());
1880 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1882 // disables ASCII-art for export of equations. See #2275.
1883 if (0 && display()) {
1887 TextPainter tpain(dim.width(), dim.height());
1888 drawT(tpain, 0, dim.ascent());
1890 // reset metrics cache to "real" values
1892 return tpain.textheight();
1894 odocstringstream oss;
1895 Encoding const * const enc = encodings.fromLyXName("utf8");
1896 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1898 if (type_ == hullRegexp)
1901 for (row_type r = 0; r < nrows(); ++r) {
1902 for (col_type c = 0; c < ncols(); ++c)
1903 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
1907 docstring const str = oss.str();
1914 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1919 if (getType() == hullSimple)
1920 name = from_ascii("inlineequation");
1922 name = from_ascii("informalequation");
1924 docstring bname = name;
1925 if (!label(0).empty())
1926 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1928 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1930 odocstringstream ls;
1931 if (runparams.flavor == OutputParams::XML) {
1932 ms << MTag("alt role='tex' ");
1933 // Workaround for db2latex: db2latex always includes equations with
1934 // \ensuremath{} or \begin{display}\end{display}
1935 // so we strip LyX' math environment
1936 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1937 InsetMathGrid::write(wi);
1938 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1943 InsetMathGrid::mathmlize(ms);
1948 otexstream ols(ls, texrow);
1949 ms << MTag("alt role='tex'");
1950 latex(ols, runparams);
1951 res = texrow.rows();
1952 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1956 ms << from_ascii("<graphic fileref=\"eqn/");
1957 if (!label(0).empty())
1958 ms << sgml::cleanID(buffer(), runparams, label(0));
1960 ms << sgml::uniqueID(from_ascii("anon"));
1962 if (runparams.flavor == OutputParams::XML)
1963 ms << from_ascii("\"/>");
1965 ms << from_ascii("\">");
1967 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1969 return ms.line() + res;
1973 bool InsetMathHull::haveNumbers() const
1975 bool havenumbers = false;
1976 // inline formulas are never numbered (bug 7351 part 3)
1977 if (getType() == hullSimple)
1979 for (size_t i = 0; i != numbered_.size(); ++i) {
1990 // We need to do something about alignment here.
1992 // This duplicates code from InsetMathGrid, but
1993 // we need access here to number information,
1994 // and we simply do not have that in InsetMathGrid.
1995 void InsetMathHull::htmlize(HtmlStream & os) const
1997 bool const havenumbers = haveNumbers();
1998 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2001 os << cell(index(0, 0));
2005 os << MTag("table", "class='mathtable'");
2006 for (row_type row = 0; row < nrows(); ++row) {
2008 for (col_type col = 0; col < ncols(); ++col) {
2010 os << cell(index(row, col));
2015 docstring const & num = numbers_[row];
2017 os << '(' << num << ')';
2022 os << ETag("table");
2026 // this duplicates code from InsetMathGrid, but
2027 // we need access here to number information,
2028 // and we simply do not have that in InsetMathGrid.
2029 void InsetMathHull::mathmlize(MathStream & os) const
2031 bool const havenumbers = haveNumbers();
2032 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2035 os << MTag("mtable");
2036 char const * const celltag = havetable ? "mtd" : "mrow";
2037 // FIXME There does not seem to be wide support at the moment
2038 // for mlabeledtr, so we have to use just mtr for now.
2039 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2040 char const * const rowtag = "mtr";
2041 for (row_type row = 0; row < nrows(); ++row) {
2044 for (col_type col = 0; col < ncols(); ++col) {
2046 << cell(index(row, col))
2052 docstring const & num = numbers_[row];
2054 os << '(' << num << ')';
2061 os << ETag("mtable");
2065 void InsetMathHull::mathAsLatex(WriteStream & os) const
2067 MathEnsurer ensurer(os, false);
2068 bool havenumbers = haveNumbers();
2069 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2072 os << cell(index(0, 0));
2076 os << "<table class='mathtable'>";
2077 for (row_type row = 0; row < nrows(); ++row) {
2079 for (col_type col = 0; col < ncols(); ++col) {
2080 os << "<td class='math'>";
2081 os << cell(index(row, col));
2086 docstring const & num = numbers_[row];
2088 os << '(' << num << ')';
2097 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2099 BufferParams::MathOutput const mathtype =
2100 buffer().params().html_math_output;
2102 bool success = false;
2104 // we output all the labels just at the beginning of the equation.
2105 // this should be fine.
2106 for (size_t i = 0; i != label_.size(); ++i) {
2107 InsetLabel const * const il = label_[i];
2113 // FIXME Eventually we would like to do this inset by inset.
2114 if (mathtype == BufferParams::MathML) {
2115 odocstringstream os;
2120 } catch (MathExportException const &) {}
2122 if (getType() == hullSimple)
2123 xs << html::StartTag("math",
2124 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2126 xs << html::StartTag("math",
2127 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2128 xs << XHTMLStream::ESCAPE_NONE
2130 << html::EndTag("math");
2132 } else if (mathtype == BufferParams::HTML) {
2133 odocstringstream os;
2138 } catch (MathExportException const &) {}
2140 string const tag = (getType() == hullSimple) ? "span" : "div";
2141 xs << html::StartTag(tag, "class='formula'", true)
2142 << XHTMLStream::ESCAPE_NONE
2144 << html::EndTag(tag);
2148 // what we actually want is this:
2150 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2152 // || mathtype == BufferParams::Images
2154 // but what follows is equivalent, since we'll enter only if either (a) we
2155 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2156 // aren't doing LaTeX, in which case we are doing Images.
2157 if (!success && mathtype != BufferParams::LaTeX) {
2158 graphics::PreviewImage const * pimage = 0;
2160 loadPreview(docit_);
2161 pimage = preview_->getPreviewImage(buffer());
2162 // FIXME Do we always have png?
2165 if (pimage || op.dryrun) {
2166 string const filename = pimage ? pimage->filename().onlyFileName()
2167 : "previewimage.png";
2169 // if we are not in the master buffer, then we need to see that the
2170 // generated image is copied there; otherwise, preview fails.
2171 Buffer const * mbuf = buffer().masterBuffer();
2172 if (mbuf != &buffer()) {
2173 string mbtmp = mbuf->temppath();
2174 FileName const mbufimg(support::addName(mbtmp, filename));
2175 pimage->filename().copyTo(mbufimg);
2177 // add the file to the list of files to be exported
2178 op.exportdata->addExternalFile("xhtml", pimage->filename());
2181 string const tag = (getType() == hullSimple) ? "span" : "div";
2183 << html::StartTag(tag)
2184 << html::CompTag("img", "src=\"" + filename + "\"")
2185 << html::EndTag(tag)
2191 // so we'll pass this test if we've failed everything else, or
2192 // if mathtype was LaTeX, since we won't have entered any of the
2194 if (!success /* || mathtype != BufferParams::LaTeX */) {
2195 // Unfortunately, we cannot use latexString() because we do not want
2196 // $...$ or whatever.
2197 odocstringstream ls;
2198 WriteStream wi(ls, false, true, WriteStream::wsPreview);
2199 ModeSpecifier specifier(wi, MATH_MODE);
2201 docstring const latex = ls.str();
2203 // class='math' allows for use of jsMath
2204 // http://www.math.union.edu/~dpvc/jsMath/
2206 // probably should allow for some kind of customization here
2207 string const tag = (getType() == hullSimple) ? "span" : "div";
2208 xs << html::StartTag(tag, "class='math'")
2210 << html::EndTag(tag)
2217 void InsetMathHull::toString(odocstream & os) const
2219 plaintext(os, OutputParams(0));
2223 void InsetMathHull::forToc(docstring & os, size_t) const
2225 odocstringstream ods;
2226 plaintext(ods, OutputParams(0));
2231 docstring InsetMathHull::contextMenuName() const
2233 return from_ascii("context-math");
2237 void InsetMathHull::recordLocation(DocIterator const & di)