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/gettext.h"
57 #include "support/lstrings.h"
62 using namespace lyx::support;
66 using cap::grabAndEraseSelection;
70 int getCols(HullType type)
87 // returns position of first relation operator in the array
88 // used for "intelligent splitting"
89 size_t firstRelOp(MathData const & ar)
91 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
93 return it - ar.begin();
98 char const * star(bool numbered)
100 return numbered ? "" : "*";
104 } // end anon namespace
107 HullType hullType(docstring const & s)
109 if (s == "none") return hullNone;
110 if (s == "simple") return hullSimple;
111 if (s == "equation") return hullEquation;
112 if (s == "eqnarray") return hullEqnArray;
113 if (s == "align") return hullAlign;
114 if (s == "alignat") return hullAlignAt;
115 if (s == "xalignat") return hullXAlignAt;
116 if (s == "xxalignat") return hullXXAlignAt;
117 if (s == "multline") return hullMultline;
118 if (s == "gather") return hullGather;
119 if (s == "flalign") return hullFlAlign;
120 if (s == "regexp") return hullRegexp;
121 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
126 docstring hullName(HullType type)
129 case hullNone: return from_ascii("none");
130 case hullSimple: return from_ascii("simple");
131 case hullEquation: return from_ascii("equation");
132 case hullEqnArray: return from_ascii("eqnarray");
133 case hullAlign: return from_ascii("align");
134 case hullAlignAt: return from_ascii("alignat");
135 case hullXAlignAt: return from_ascii("xalignat");
136 case hullXXAlignAt: return from_ascii("xxalignat");
137 case hullMultline: return from_ascii("multline");
138 case hullGather: return from_ascii("gather");
139 case hullFlAlign: return from_ascii("flalign");
140 case hullRegexp: return from_ascii("regexp");
142 lyxerr << "unknown hull type '" << type << "'" << endl;
143 return from_ascii("none");
147 static InsetLabel * dummy_pointer = 0;
149 InsetMathHull::InsetMathHull(Buffer * buf)
150 : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, true),
151 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
152 preview_(new RenderPreview(this))
154 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
155 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
156 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
157 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
164 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
165 : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, true),
166 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
167 preview_(new RenderPreview(this))
175 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
181 InsetMathHull::~InsetMathHull()
183 for (size_t i = 0; i < label_.size(); ++i)
188 Inset * InsetMathHull::clone() const
190 return new InsetMathHull(*this);
194 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
198 InsetMathGrid::operator=(other);
200 numbered_ = other.numbered_;
201 numbers_ = other.numbers_;
202 buffer_ = other.buffer_;
203 for (size_t i = 0; i < label_.size(); ++i)
205 label_ = other.label_;
206 for (size_t i = 0; i != label_.size(); ++i) {
208 label_[i] = new InsetLabel(*label_[i]);
210 preview_.reset(new RenderPreview(*other.preview_, this));
216 void InsetMathHull::setBuffer(Buffer & buffer)
218 InsetMathGrid::setBuffer(buffer);
220 for (size_t i = 0; i != label_.size(); ++i) {
222 label_[i]->setBuffer(buffer);
228 const char * counters_to_save[] = {"section", "chapter"};
229 unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
233 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
236 //FIXME: buffer_ should be set at creation for this inset! Problem is
237 // This inset is created at too many places (see Parser::parse1() in
242 // if any of the equations are numbered, then we want to save the values
243 // of some of the counters.
245 BufferParams const & bp = buffer_->params();
246 string const & lang = it->getParLanguage(bp)->code();
247 Counters & cnts = bp.documentClass().counters();
249 // right now, we only need to do this at export time
250 if (utype == OutputUpdate) {
251 for (size_t i = 0; i < numcnts; ++i) {
252 docstring const cnt = from_ascii(counters_to_save[i]);
253 if (cnts.hasCounter(cnt))
254 counter_map[cnt] = cnts.value(cnt);
258 // this has to be done separately
259 docstring const eqstr = from_ascii("equation");
260 if (cnts.hasCounter(eqstr)) {
261 if (utype == OutputUpdate)
262 counter_map[eqstr] = cnts.value(eqstr);
263 for (size_t i = 0; i != label_.size(); ++i) {
265 cnts.step(eqstr, utype);
266 numbers_[i] = cnts.theCounter(eqstr, lang);
268 numbers_[i] = empty_docstring();
274 for (size_t i = 0; i != label_.size(); ++i) {
276 label_[i]->updateBuffer(it, utype);
279 InsetMathGrid::updateBuffer(it, utype);
283 void InsetMathHull::addToToc(DocIterator const & pit) const
286 //FIXME: buffer_ should be set at creation for this inset! Problem is
287 // This inset is created at too many places (see Parser::parse1() in
292 Toc & toc = buffer().tocBackend().toc("equation");
294 for (row_type row = 0; row != nrows(); ++row) {
298 label_[row]->addToToc(pit);
299 toc.push_back(TocItem(pit, 0, nicelabel(row)));
304 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
310 return InsetMathNest::editXY(cur, x, y);
314 InsetMath::mode_type InsetMathHull::currentMode() const
316 if (type_ == hullNone)
317 return UNDECIDED_MODE;
318 // definitely math mode ...
323 bool InsetMathHull::idxFirst(Cursor & cur) const
331 bool InsetMathHull::idxLast(Cursor & cur) const
333 cur.idx() = nargs() - 1;
334 cur.pos() = cur.lastpos();
339 char InsetMathHull::defaultColAlign(col_type col)
341 if (type_ == hullEqnArray)
343 if (type_ == hullGather)
345 if (type_ >= hullAlign)
346 return "rl"[col & 1];
351 int InsetMathHull::defaultColSpace(col_type col)
353 if (type_ == hullAlign || type_ == hullAlignAt)
355 if (type_ == hullXAlignAt)
356 return (col & 1) ? 20 : 0;
357 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
358 return (col & 1) ? 40 : 0;
363 docstring InsetMathHull::standardFont() const
368 font_name = from_ascii("texttt");
371 font_name = from_ascii("lyxnochange");
374 font_name = from_ascii("mathnormal");
380 ColorCode InsetMathHull::standardColor() const
386 color = Color_foreground;
395 bool InsetMathHull::previewState(BufferView * bv) const
397 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
398 graphics::PreviewImage const * pimage =
399 preview_->getPreviewImage(bv->buffer());
400 return pimage && pimage->image();
406 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
408 if (previewState(mi.base.bv)) {
409 preview_->metrics(mi, dim);
410 // insert a one pixel gap in front of the formula
413 dim.des += displayMargin();
414 // Cache the inset dimension.
415 setDimCache(mi, dim);
419 FontSetChanger dummy1(mi.base, standardFont());
420 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
422 // let the cells adjust themselves
423 InsetMathGrid::metrics(mi, dim);
426 dim.asc += displayMargin();
427 dim.des += displayMargin();
430 if (numberedType()) {
431 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
433 for (row_type row = 0; row < nrows(); ++row)
434 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
440 // make it at least as high as the current font
443 math_font_max_dim(mi.base.font, asc, des);
444 dim.asc = max(dim.asc, asc);
445 dim.des = max(dim.des, des);
446 // Cache the inset dimension.
447 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
448 setDimCache(mi, dim);
452 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
454 if (previewState(pi.base.bv))
455 return graphics::PreviewLoader::backgroundColor();
460 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
462 Dimension const dim = dimension(*pi.base.bv);
463 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
464 dim.asc + dim.des - 1, pi.backgroundColor(this));
468 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
470 use_preview_ = previewState(pi.base.bv);
472 if (type_ == hullRegexp) {
473 Dimension const dim = dimension(*pi.base.bv);
474 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
475 dim.width() - 2, dim.height() - 2, Color_regexpframe);
478 // one pixel gap in front
479 preview_->draw(pi, x + 1, y);
480 setPosCache(pi, x, y);
484 ColorCode color = pi.selected && lyxrc.use_system_colors
485 ? Color_selectiontext : standardColor();
486 bool const really_change_color = pi.base.font.color() == Color_none;
487 ColorChanger dummy0(pi.base.font, color, really_change_color);
488 FontSetChanger dummy1(pi.base, standardFont());
489 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
491 InsetMathGrid::draw(pi, x + 1, y);
493 if (numberedType()) {
494 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
495 for (row_type row = 0; row < nrows(); ++row) {
496 int const yy = y + rowinfo_[row].offset_;
497 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
498 docstring const nl = nicelabel(row);
502 setPosCache(pi, x, y);
506 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
509 InsetMathGrid::metricsT(mi, dim);
512 WriteStream wi(os, false, true, WriteStream::wsDefault);
514 dim.wid = os.str().size();
521 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
524 InsetMathGrid::drawT(pain, x, y);
527 WriteStream wi(os, false, true, WriteStream::wsDefault);
529 pain.draw(x, y, os.str().c_str());
534 static docstring latexString(InsetMathHull const & inset)
537 // This has to be static, because a preview snippet or a math
538 // macro containing math in text mode (such as $\text{$\phi$}$ or
539 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
540 // first time as a whole, and the second time only the inner math.
541 // In this last case inset.buffer() would be invalid.
542 static Encoding const * encoding = 0;
543 if (inset.isBufferValid())
544 encoding = &(inset.buffer().params().encoding());
545 WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
551 void InsetMathHull::initUnicodeMath() const
553 // Trigger classification of the unicode symbols in this inset
554 docstring const dummy = latexString(*this);
558 void InsetMathHull::addPreview(DocIterator const & inset_pos,
559 graphics::PreviewLoader & /*ploader*/) const
561 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
562 preparePreview(inset_pos);
567 void InsetMathHull::preparePreview(DocIterator const & pos,
568 bool forexport) const
570 // there is no need to do all the macro stuff if we're not
571 // actually going to generate the preview.
572 if (RenderPreview::status() != LyXRC::PREVIEW_ON && !forexport)
575 Buffer const * buffer = pos.buffer();
577 // collect macros at this position
579 buffer->listMacroNames(macros);
580 MacroNameSet::iterator it = macros.begin();
581 MacroNameSet::iterator end = macros.end();
582 odocstringstream macro_preamble;
583 for (; it != end; ++it) {
584 MacroData const * data = buffer->getMacro(*it, pos, true);
586 data->write(macro_preamble, true);
587 macro_preamble << endl;
592 if (forexport && haveNumbers()) {
593 docstring eqstr = from_ascii("equation");
594 CounterMap::const_iterator it = counter_map.find(eqstr);
595 if (it != counter_map.end()) {
596 int num = it->second;
598 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
599 '{' + convert<docstring>(num) + '}' + '\n';
601 for (size_t i = 0; i != numcnts; ++i) {
602 docstring cnt = from_ascii(counters_to_save[i]);
603 it = counter_map.find(cnt);
604 if (it == counter_map.end())
606 int num = it->second;
608 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
609 '{' + convert<docstring>(num) + '}';
612 docstring const snippet = macro_preamble.str() +
613 setcnt + latexString(*this);
614 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
615 preview_->addPreview(snippet, *buffer, forexport);
619 void InsetMathHull::reloadPreview(DocIterator const & pos) const
622 preview_->startLoading(*pos.buffer());
626 void InsetMathHull::loadPreview(DocIterator const & pos) const
628 bool const forexport = true;
629 preparePreview(pos, forexport);
630 preview_->startLoading(*pos.buffer(), forexport);
634 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
636 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
638 cur.screenUpdateFlags(Update::Force);
644 docstring InsetMathHull::label(row_type row) const
646 LASSERT(row < nrows(), /**/);
647 if (InsetLabel * il = label_[row])
648 return il->screenLabel();
653 void InsetMathHull::label(row_type row, docstring const & label)
655 //lyxerr << "setting label '" << label << "' for row " << row << endl;
659 label_[row] = dummy_pointer;
662 label_[row]->updateCommand(label);
664 label_[row]->setParam("name", label);
668 InsetCommandParams p(LABEL_CODE);
670 label_[row] = new InsetLabel(buffer_, p);
672 label_[row]->setBuffer(buffer());
676 void InsetMathHull::numbered(row_type row, bool num)
678 numbered_[row] = num;
679 if (!numbered_[row] && label_[row]) {
686 bool InsetMathHull::numbered(row_type row) const
688 return numbered_[row];
692 bool InsetMathHull::ams() const
694 return type_ == hullAlign
695 || type_ == hullFlAlign
696 || type_ == hullMultline
697 || type_ == hullGather
698 || type_ == hullAlignAt
699 || type_ == hullXAlignAt
700 || type_ == hullXXAlignAt;
704 Inset::DisplayType InsetMathHull::display() const
706 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
711 bool InsetMathHull::numberedType() const
713 if (type_ == hullNone)
715 if (type_ == hullSimple)
717 if (type_ == hullXXAlignAt)
719 if (type_ == hullRegexp)
721 for (row_type row = 0; row < nrows(); ++row)
728 void InsetMathHull::validate(LaTeXFeatures & features) const
730 if (features.runparams().isLaTeX()) {
732 features.require("amsmath");
734 if (type_ == hullRegexp) {
735 features.require("color");
736 string frcol = lcolor.getLaTeXName(Color_regexpframe);
737 string bgcol = "white";
738 features.addPreambleSnippet(
739 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
740 + frcol + string("}{")
741 + bgcol + string("}{\\texttt{#1}}}"));
744 // Validation is necessary only if not using AMS math.
745 // To be safe, we will always run mathedvalidate.
746 //if (features.amsstyle)
749 //features.binom = true;
750 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
751 // it would be better to do this elsewhere, but we can't validate in
752 // InsetMathMatrix and we have no way, outside MathExtern, to know if
753 // we even have any matrices.
754 features.addPreambleSnippet("<style type=\"text/css\">\n"
755 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
756 "table.matrix td{padding: 0.25px;}\n"
757 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
758 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}\n"
761 InsetMathGrid::validate(features);
765 void InsetMathHull::header_write(WriteStream & os) const
767 bool n = numberedType();
781 os << "\n\\begin{equation" << star(n) << "}\n";
791 os << "\n\\begin{" << hullName(type_) << star(n) << "}\n";
796 os << "\n\\begin{" << hullName(type_) << star(n) << '}'
797 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
801 os << "\n\\begin{" << hullName(type_) << '}'
802 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
810 os << "\n\\begin{unknown" << star(n) << "}\n";
816 void InsetMathHull::footer_write(WriteStream & os) const
818 bool n = numberedType();
831 os << "\n\\end{equation" << star(n) << "}\n";
843 os << "\n\\end{" << hullName(type_) << star(n) << "}\n";
847 os << "\n\\end{" << hullName(type_) << "}\n";
855 os << "\n\\end{unknown" << star(n) << "}\n";
861 bool InsetMathHull::rowChangeOK() const
864 type_ == hullEqnArray || type_ == hullAlign ||
865 type_ == hullFlAlign || type_ == hullAlignAt ||
866 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
867 type_ == hullGather || type_ == hullMultline;
871 bool InsetMathHull::colChangeOK() const
874 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
875 type_ == hullXAlignAt || type_ == hullXXAlignAt;
879 void InsetMathHull::addRow(row_type row)
884 bool numbered = numberedType();
886 if (type_ == hullMultline) {
887 if (row + 1 == nrows()) {
888 numbered_[row] = false;
894 numbered_.insert(numbered_.begin() + row + 1, numbered);
895 numbers_.insert(numbers_.begin() + row + 1, empty_docstring());
896 label_.insert(label_.begin() + row + 1, dummy_pointer);
899 InsetMathGrid::addRow(row);
903 void InsetMathHull::swapRow(row_type row)
907 if (row + 1 == nrows())
909 // gcc implements the standard std::vector<bool> which is *not* a container:
910 // http://www.gotw.ca/publications/N1185.pdf
911 // As a results, it doesn't like this:
912 // swap(numbered_[row], numbered_[row + 1]);
913 // so we do it manually:
914 bool const b = numbered_[row];
915 numbered_[row] = numbered_[row + 1];
916 numbered_[row + 1] = b;
917 swap(numbers_[row], numbers_[row + 1]);
918 swap(label_[row], label_[row + 1]);
919 InsetMathGrid::swapRow(row);
923 void InsetMathHull::delRow(row_type row)
925 if (nrows() <= 1 || !rowChangeOK())
927 if (row + 1 == nrows() && type_ == hullMultline) {
928 bool const b = numbered_[row - 1];
929 numbered_[row - 1] = numbered_[row];
931 swap(numbers_[row - 1], numbers_[row]);
932 swap(label_[row - 1], label_[row]);
933 InsetMathGrid::delRow(row);
936 InsetMathGrid::delRow(row);
937 // The last dummy row has no number info nor a label.
938 // Test nrows() + 1 because we have already erased the row.
939 if (row == nrows() + 1)
941 numbered_.erase(numbered_.begin() + row);
942 numbers_.erase(numbers_.begin() + row);
944 label_.erase(label_.begin() + row);
948 void InsetMathHull::addCol(col_type col)
952 InsetMathGrid::addCol(col);
956 void InsetMathHull::delCol(col_type col)
958 if (ncols() <= 1 || !colChangeOK())
960 InsetMathGrid::delCol(col);
964 docstring InsetMathHull::nicelabel(row_type row) const
968 docstring const & val = numbers_[row];
970 return '(' + val + ')';
971 return '(' + val + ',' + label_[row]->screenLabel() + ')';
975 void InsetMathHull::glueall(HullType type)
978 for (idx_type i = 0; i < nargs(); ++i)
980 InsetLabel * label = 0;
981 if (type == hullEquation) {
982 // preserve first non-empty label
983 for (row_type row = 0; row < nrows(); ++row) {
991 *this = InsetMathHull(buffer_, hullSimple);
998 void InsetMathHull::splitTo2Cols()
1000 LASSERT(ncols() == 1, /**/);
1001 InsetMathGrid::addCol(1);
1002 for (row_type row = 0; row < nrows(); ++row) {
1003 idx_type const i = 2 * row;
1004 pos_type pos = firstRelOp(cell(i));
1005 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1006 cell(i).erase(pos, cell(i).size());
1011 void InsetMathHull::splitTo3Cols()
1013 LASSERT(ncols() < 3, /**/);
1016 InsetMathGrid::addCol(2);
1017 for (row_type row = 0; row < nrows(); ++row) {
1018 idx_type const i = 3 * row + 1;
1019 if (cell(i).size()) {
1020 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1021 cell(i).erase(1, cell(i).size());
1027 void InsetMathHull::changeCols(col_type cols)
1029 if (ncols() == cols)
1031 else if (ncols() < cols) {
1037 while (ncols() < cols)
1038 InsetMathGrid::addCol(ncols());
1044 for (row_type row = 0; row < nrows(); ++row) {
1045 idx_type const i = row * ncols();
1046 for (col_type col = cols; col < ncols(); ++col) {
1047 cell(i + cols - 1).append(cell(i + col));
1051 while (ncols() > cols) {
1052 InsetMathGrid::delCol(ncols() - 1);
1057 HullType InsetMathHull::getType() const
1063 void InsetMathHull::setType(HullType type)
1070 void InsetMathHull::mutate(HullType newtype)
1072 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1074 // we try to move along the chain
1075 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1077 // +-------------------------------------+
1078 // we use eqnarray as intermediate type for mutations that are not
1079 // directly supported because it handles labels and numbering for
1082 if (newtype == type_) {
1086 else if (newtype < hullNone) {
1091 else if (type_ == hullNone) {
1092 setType(hullSimple);
1097 else if (type_ == hullSimple) {
1098 if (newtype == hullNone) {
1102 setType(hullEquation);
1103 numbered(0, label_[0] ? true : false);
1108 else if (type_ == hullEquation) {
1109 if (newtype < type_) {
1110 setType(hullSimple);
1113 } else if (newtype == hullEqnArray) {
1114 // split it "nicely" on the first relop
1116 setType(hullEqnArray);
1117 } else if (newtype == hullMultline || newtype == hullGather) {
1120 // split it "nicely"
1127 else if (type_ == hullEqnArray) {
1128 if (newtype < type_) {
1131 } else { // align & Co.
1138 else if (type_ == hullAlign || type_ == hullAlignAt ||
1139 type_ == hullXAlignAt || type_ == hullFlAlign) {
1140 if (newtype < hullAlign) {
1142 setType(hullEqnArray);
1144 } else if (newtype == hullGather || newtype == hullMultline) {
1147 } else if (newtype == hullXXAlignAt) {
1148 for (row_type row = 0; row < nrows(); ++row)
1149 numbered(row, false);
1156 else if (type_ == hullXXAlignAt) {
1157 for (row_type row = 0; row < nrows(); ++row)
1158 numbered(row, false);
1159 if (newtype < hullAlign) {
1161 setType(hullEqnArray);
1163 } else if (newtype == hullGather || newtype == hullMultline) {
1171 else if (type_ == hullMultline || type_ == hullGather) {
1172 if (newtype == hullGather || newtype == hullMultline)
1174 else if (newtype == hullAlign || newtype == hullFlAlign ||
1175 newtype == hullAlignAt || newtype == hullXAlignAt) {
1178 } else if (newtype == hullXXAlignAt) {
1180 for (row_type row = 0; row < nrows(); ++row)
1181 numbered(row, false);
1185 setType(hullEqnArray);
1191 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1192 << "' to '" << to_utf8(hullName(newtype))
1193 << "' not implemented" << endl;
1198 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1199 bool last_eoln) const
1202 if (numberedType()) {
1203 if (label_[row] && numbered_[row]) {
1204 docstring const name =
1205 latex ? escape(label_[row]->getParam("name"))
1206 : label_[row]->getParam("name");
1207 res += "\\label{" + name + '}';
1209 if (!numbered_[row] && (type_ != hullMultline))
1210 res += "\\nonumber ";
1212 // Never add \\ on the last empty line of eqnarray and friends
1214 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1218 void InsetMathHull::write(WriteStream & os) const
1220 ModeSpecifier specifier(os, MATH_MODE);
1222 InsetMathGrid::write(os);
1227 void InsetMathHull::normalize(NormalStream & os) const
1229 os << "[formula " << hullName(type_) << ' ';
1230 InsetMathGrid::normalize(os);
1235 void InsetMathHull::infoize(odocstream & os) const
1237 os << "Type: " << hullName(type_);
1241 void InsetMathHull::check() const
1243 LASSERT(numbered_.size() == nrows(), /**/);
1244 LASSERT(numbers_.size() == nrows(), /**/);
1245 LASSERT(label_.size() == nrows(), /**/);
1249 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1253 idocstringstream iss(func.argument());
1254 iss >> dlang >> extra;
1256 extra = from_ascii("noextra");
1257 string const lang = to_ascii(dlang);
1259 // FIXME: temporarily disabled
1260 //if (cur.selection()) {
1263 // lyxerr << "use selection: " << ar << endl;
1264 // insert(pipeThroughExtern(lang, extra, ar));
1268 // only inline, display or eqnarray math is allowed
1269 if (getType() > hullEqnArray) {
1270 frontend::Alert::warning(_("Bad math environment"),
1271 _("Computation cannot be performed for AMS "
1272 "math environments.\nChange the math "
1273 "formula type and try again."));
1278 eq.push_back(MathAtom(new InsetMathChar('=')));
1280 // go to first item in line
1281 cur.idx() -= cur.idx() % ncols();
1284 if (getType() == hullSimple) {
1285 size_type pos = cur.cell().find_last(eq);
1287 if (cur.inMathed() && cur.selection()) {
1288 asArray(grabAndEraseSelection(cur), ar);
1289 } else if (pos == cur.cell().size()) {
1291 lyxerr << "use whole cell: " << ar << endl;
1293 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1294 lyxerr << "use partial cell form pos: " << pos << endl;
1296 cur.cell().append(eq);
1297 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1298 cur.pos() = cur.lastpos();
1302 if (getType() == hullEquation) {
1303 lyxerr << "use equation inset" << endl;
1304 mutate(hullEqnArray);
1305 MathData & ar = cur.cell();
1306 lyxerr << "use cell: " << ar << endl;
1310 cur.cell() = pipeThroughExtern(lang, extra, ar);
1311 // move to end of line
1312 cur.pos() = cur.lastpos();
1317 lyxerr << "use eqnarray" << endl;
1318 cur.idx() += 2 - cur.idx() % ncols();
1320 MathData ar = cur.cell();
1321 lyxerr << "use cell: " << ar << endl;
1322 // FIXME: temporarily disabled
1328 cur.cell() = pipeThroughExtern(lang, extra, ar);
1329 cur.pos() = cur.lastpos();
1334 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1336 //lyxerr << "action: " << cmd.action() << endl;
1337 switch (cmd.action()) {
1339 case LFUN_FINISHED_BACKWARD:
1340 case LFUN_FINISHED_FORWARD:
1341 case LFUN_FINISHED_RIGHT:
1342 case LFUN_FINISHED_LEFT:
1343 //lyxerr << "action: " << cmd.action() << endl;
1344 InsetMathGrid::doDispatch(cur, cmd);
1348 case LFUN_BREAK_PARAGRAPH:
1349 // just swallow this
1352 case LFUN_NEWLINE_INSERT:
1353 // some magic for the common case
1354 if (type_ == hullSimple || type_ == hullEquation) {
1355 cur.recordUndoInset();
1357 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1358 mutate(align ? hullAlign : hullEqnArray);
1359 // mutate() may change labels and such.
1360 cur.forceBufferUpdate();
1361 cur.idx() = nrows() * ncols() - 1;
1362 cur.pos() = cur.lastpos();
1364 InsetMathGrid::doDispatch(cur, cmd);
1367 case LFUN_MATH_NUMBER_TOGGLE: {
1368 //lyxerr << "toggling all numbers" << endl;
1369 cur.recordUndoInset();
1370 bool old = numberedType();
1371 if (type_ == hullMultline)
1372 numbered(nrows() - 1, !old);
1374 for (row_type row = 0; row < nrows(); ++row)
1375 numbered(row, !old);
1377 cur.message(old ? _("No number") : _("Number"));
1378 cur.forceBufferUpdate();
1382 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1383 cur.recordUndoInset();
1384 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1385 bool old = numbered(r);
1386 cur.message(old ? _("No number") : _("Number"));
1388 cur.forceBufferUpdate();
1392 case LFUN_LABEL_INSERT: {
1393 cur.recordUndoInset();
1394 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1395 docstring old_label = label(r);
1396 docstring const default_label = from_ascii("eq:");
1397 if (old_label.empty())
1398 old_label = default_label;
1400 InsetCommandParams p(LABEL_CODE);
1401 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1402 string const data = InsetCommand::params2string(p);
1404 if (cmd.argument().empty())
1405 cur.bv().showDialog("label", data);
1407 FuncRequest fr(LFUN_INSET_INSERT, data);
1413 case LFUN_LABEL_COPY_AS_REF: {
1415 if (cmd.argument().empty() && &cur.inset() == this)
1416 // if there is no argument and we're inside math, we retrieve
1417 // the row number from the cursor position.
1418 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1420 // if there is an argument, find the corresponding label, else
1421 // check whether there is at least one label.
1422 for (row = 0; row != nrows(); ++row)
1423 if (numbered_[row] && label_[row]
1424 && (cmd.argument().empty() || label(row) == cmd.argument()))
1431 InsetCommandParams p(REF_CODE, "ref");
1432 p["reference"] = label(row);
1433 cap::clearSelection();
1434 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1438 case LFUN_WORD_DELETE_FORWARD:
1439 case LFUN_CHAR_DELETE_FORWARD:
1440 if (col(cur.idx()) + 1 == ncols()
1441 && cur.pos() == cur.lastpos()
1442 && !cur.selection()) {
1443 if (!label(row(cur.idx())).empty()) {
1444 cur.recordUndoInset();
1445 label(row(cur.idx()), docstring());
1446 } else if (numbered(row(cur.idx()))) {
1447 cur.recordUndoInset();
1448 numbered(row(cur.idx()), false);
1449 cur.forceBufferUpdate();
1451 InsetMathGrid::doDispatch(cur, cmd);
1455 InsetMathGrid::doDispatch(cur, cmd);
1460 case LFUN_INSET_INSERT: {
1461 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1462 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1463 string const name = cmd.getArg(0);
1464 if (name == "label") {
1465 InsetCommandParams p(LABEL_CODE);
1466 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1467 docstring str = p["name"];
1468 cur.recordUndoInset();
1469 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1473 docstring old = label(r);
1476 // The label will take care of the reference update.
1480 // Newly created inset so initialize it.
1481 label_[r]->initView();
1484 cur.forceBufferUpdate();
1487 InsetMathGrid::doDispatch(cur, cmd);
1491 case LFUN_MATH_EXTERN:
1492 cur.recordUndoInset();
1496 case LFUN_MATH_MUTATE: {
1497 cur.recordUndoInset();
1498 row_type row = cur.row();
1499 col_type col = cur.col();
1500 mutate(hullType(cmd.argument()));
1501 cur.idx() = row * ncols() + col;
1502 if (cur.idx() > cur.lastidx()) {
1503 cur.idx() = cur.lastidx();
1504 cur.pos() = cur.lastpos();
1506 if (cur.pos() > cur.lastpos())
1507 cur.pos() = cur.lastpos();
1509 cur.forceBufferUpdate();
1510 // FIXME: find some more clever handling of the selection,
1511 // i.e. preserve it.
1512 cur.clearSelection();
1513 //cur.dispatched(FINISHED);
1517 case LFUN_MATH_DISPLAY: {
1518 cur.recordUndoInset();
1519 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1521 cur.pos() = cur.lastpos();
1522 //cur.dispatched(FINISHED);
1527 InsetMathGrid::doDispatch(cur, cmd);
1533 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1534 FuncStatus & status) const
1536 switch (cmd.action()) {
1537 case LFUN_FINISHED_BACKWARD:
1538 case LFUN_FINISHED_FORWARD:
1539 case LFUN_FINISHED_RIGHT:
1540 case LFUN_FINISHED_LEFT:
1543 case LFUN_NEWLINE_INSERT:
1544 case LFUN_MATH_EXTERN:
1546 status.setEnabled(true);
1549 // we never allow this in math, and we want to bind enter
1550 // to another actions in command-alternatives
1551 case LFUN_BREAK_PARAGRAPH:
1552 status.setEnabled(false);
1554 case LFUN_MATH_MUTATE: {
1555 HullType const ht = hullType(cmd.argument());
1556 status.setOnOff(type_ == ht);
1557 status.setEnabled(true);
1559 if (ht != hullSimple) {
1560 Cursor tmpcur = cur;
1561 while (!tmpcur.empty()) {
1562 InsetCode code = tmpcur.inset().lyxCode();
1563 if (code == BOX_CODE) {
1565 } else if (code == TABULAR_CODE) {
1566 FuncRequest tmpcmd(LFUN_MATH_DISPLAY);
1567 if (tmpcur.getStatus(tmpcmd, status) && !status.enabled())
1575 case LFUN_MATH_DISPLAY: {
1577 if (cur.depth() > 1) {
1578 Inset const & in = cur[cur.depth()-2].inset();
1579 if (in.lyxCode() == SCRIPT_CODE)
1580 enable = display() != Inline;
1582 status.setEnabled(enable);
1586 case LFUN_MATH_NUMBER_TOGGLE:
1587 // FIXME: what is the right test, this or the one of
1589 status.setEnabled(display() != Inline);
1590 status.setOnOff(numberedType());
1593 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1594 // FIXME: what is the right test, this or the one of
1596 bool const enable = (type_ == hullMultline)
1597 ? (nrows() - 1 == cur.row())
1598 : display() != Inline;
1599 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1600 status.setEnabled(enable);
1601 status.setOnOff(enable && numbered(r));
1605 case LFUN_LABEL_INSERT:
1606 status.setEnabled(type_ != hullSimple);
1609 case LFUN_LABEL_COPY_AS_REF: {
1610 bool enabled = false;
1612 if (cmd.argument().empty() && &cur.inset() == this) {
1613 // if there is no argument and we're inside math, we retrieve
1614 // the row number from the cursor position.
1615 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1616 enabled = numberedType() && label_[row] && numbered_[row];
1618 // if there is an argument, find the corresponding label, else
1619 // check whether there is at least one label.
1620 for (row_type row = 0; row != nrows(); ++row) {
1621 if (numbered_[row] && label_[row] &&
1622 (cmd.argument().empty() || label(row) == cmd.argument())) {
1628 status.setEnabled(enabled);
1632 case LFUN_INSET_INSERT:
1633 if (cmd.getArg(0) == "label") {
1634 status.setEnabled(type_ != hullSimple);
1637 return InsetMathGrid::getStatus(cur, cmd, status);
1639 case LFUN_INSET_MODIFY: {
1640 istringstream is(to_utf8(cmd.argument()));
1644 return InsetMathGrid::getStatus(cur, cmd, status);
1647 && (s == "append-row"
1648 || s == "delete-row"
1649 || s == "copy-row")) {
1650 status.message(bformat(
1651 from_utf8(N_("Can't change number of rows in '%1$s'")),
1653 status.setEnabled(false);
1657 && (s == "append-column"
1658 || s == "delete-column"
1659 || s == "copy-column")) {
1660 status.message(bformat(
1661 from_utf8(N_("Can't change number of columns in '%1$s'")),
1663 status.setEnabled(false);
1666 if ((type_ == hullSimple
1667 || type_ == hullEquation
1668 || type_ == hullNone) &&
1669 (s == "add-hline-above" || s == "add-hline-below")) {
1670 status.message(bformat(
1671 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1673 status.setEnabled(false);
1676 if (s == "add-vline-left" || s == "add-vline-right") {
1677 status.message(bformat(
1678 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1680 status.setEnabled(false);
1683 if (s == "valign-top" || s == "valign-middle"
1684 || s == "valign-bottom" || s == "align-left"
1685 || s == "align-center" || s == "align-right") {
1686 status.setEnabled(false);
1689 return InsetMathGrid::getStatus(cur, cmd, status);
1693 return InsetMathGrid::getStatus(cur, cmd, status);
1696 // This cannot really happen, but inserted to shut-up gcc
1697 return InsetMathGrid::getStatus(cur, cmd, status);
1701 /////////////////////////////////////////////////////////////////////
1705 // simply scrap this function if you want
1706 void InsetMathHull::mutateToText()
1709 // translate to latex
1711 latex(os, false, false);
1712 string str = os.str();
1715 Text * lt = view_->cursor().innerText();
1716 string::const_iterator cit = str.begin();
1717 string::const_iterator end = str.end();
1718 for (; cit != end; ++cit)
1719 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1722 //dispatch(LFUN_ESCAPE);
1727 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1728 docstring const & font)
1730 // this whole function is a hack and won't work for incremental font
1733 if (cur.inset().asInsetMath()->name() == font)
1734 cur.handleFont(to_utf8(font));
1736 cur.handleNest(createInsetMath(font, cur.buffer()));
1742 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1747 font.fromString(to_utf8(arg), b);
1748 if (font.fontInfo().color() != Color_inherit) {
1749 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1750 cur.handleNest(at, 0);
1755 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1758 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1759 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1760 enter_front ? idxFirst(cur) : idxLast(cur);
1761 // The inset formula dimension is not necessarily the same as the
1762 // one of the instant preview image, so we have to indicate to the
1763 // BufferView that a metrics update is needed.
1764 cur.screenUpdateFlags(Update::Force);
1768 void InsetMathHull::revealCodes(Cursor & cur) const
1770 if (!cur.inMathed())
1772 odocstringstream os;
1774 cur.message(os.str());
1776 // write something to the minibuffer
1777 // translate to latex
1781 string str = os.str();
1783 string::size_type pos = 0;
1785 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1788 else if (*it == '\0') {
1790 pos = it - str.begin();
1796 res = res.substr(pos - 30);
1797 if (res.size() > 60)
1798 res = res.substr(0, 60);
1804 /////////////////////////////////////////////////////////////////////
1808 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1811 // FIXME: completely broken
1812 static InsetMathHull * lastformula = 0;
1813 static CursorBase current = DocIterator(ibegin(nucleus()));
1815 static string laststr;
1817 if (lastformula != this || laststr != str) {
1818 //lyxerr << "reset lastformula to " << this << endl;
1821 current = ibegin(nucleus());
1823 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1827 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1829 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1830 CursorSlice & top = it.back();
1831 MathData const & a = top.asInsetMath()->cell(top.idx_);
1832 if (a.matchpart(ar, top.pos_)) {
1833 bv->cursor().setSelection(it, ar.size());
1835 top.pos_ += ar.size();
1841 //lyxerr << "not found!" << endl;
1848 void InsetMathHull::write(ostream & os) const
1850 odocstringstream oss;
1851 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1854 os << to_utf8(oss.str());
1858 void InsetMathHull::read(Lexer & lex)
1861 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1862 operator=(*at->asHullInset());
1866 bool InsetMathHull::readQuiet(Lexer & lex)
1869 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1871 operator=(*at->asHullInset());
1876 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1878 // disables ASCII-art for export of equations. See #2275.
1879 if (0 && display()) {
1883 TextPainter tpain(dim.width(), dim.height());
1884 drawT(tpain, 0, dim.ascent());
1886 // reset metrics cache to "real" values
1888 return tpain.textheight();
1890 odocstringstream oss;
1891 Encoding const * const enc = encodings.fromLyXName("utf8");
1892 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1894 if (type_ == hullRegexp)
1898 docstring const str = oss.str();
1905 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1910 if (getType() == hullSimple)
1911 name = from_ascii("inlineequation");
1913 name = from_ascii("informalequation");
1915 docstring bname = name;
1916 if (!label(0).empty())
1917 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1919 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1921 odocstringstream ls;
1922 if (runparams.flavor == OutputParams::XML) {
1923 ms << MTag("alt role='tex' ");
1924 // Workaround for db2latex: db2latex always includes equations with
1925 // \ensuremath{} or \begin{display}\end{display}
1926 // so we strip LyX' math environment
1927 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1928 InsetMathGrid::write(wi);
1929 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1934 InsetMathGrid::mathmlize(ms);
1939 otexstream ols(ls, texrow);
1940 ms << MTag("alt role='tex'");
1941 latex(ols, runparams);
1942 res = texrow.rows();
1943 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1947 ms << from_ascii("<graphic fileref=\"eqn/");
1948 if (!label(0).empty())
1949 ms << sgml::cleanID(buffer(), runparams, label(0));
1951 ms << sgml::uniqueID(from_ascii("anon"));
1953 if (runparams.flavor == OutputParams::XML)
1954 ms << from_ascii("\"/>");
1956 ms << from_ascii("\">");
1958 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1960 return ms.line() + res;
1964 bool InsetMathHull::haveNumbers() const
1966 bool havenumbers = false;
1967 // inline formulas are never numbered (bug 7351 part 3)
1968 if (getType() == hullSimple)
1970 for (size_t i = 0; i != numbered_.size(); ++i) {
1981 // We need to do something about alignment here.
1983 // This duplicates code from InsetMathGrid, but
1984 // we need access here to number information,
1985 // and we simply do not have that in InsetMathGrid.
1986 void InsetMathHull::htmlize(HtmlStream & os) const
1988 bool const havenumbers = haveNumbers();
1989 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
1992 os << cell(index(0, 0));
1996 os << MTag("table", "class='mathtable'");
1997 for (row_type row = 0; row < nrows(); ++row) {
1999 for (col_type col = 0; col < ncols(); ++col) {
2001 os << cell(index(row, col));
2006 docstring const & num = numbers_[row];
2008 os << '(' << num << ')';
2013 os << ETag("table");
2017 // this duplicates code from InsetMathGrid, but
2018 // we need access here to number information,
2019 // and we simply do not have that in InsetMathGrid.
2020 void InsetMathHull::mathmlize(MathStream & os) const
2022 bool const havenumbers = haveNumbers();
2023 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2026 os << MTag("mtable");
2027 char const * const celltag = havetable ? "mtd" : "mrow";
2028 // FIXME There does not seem to be wide support at the moment
2029 // for mlabeledtr, so we have to use just mtr for now.
2030 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2031 char const * const rowtag = "mtr";
2032 for (row_type row = 0; row < nrows(); ++row) {
2035 for (col_type col = 0; col < ncols(); ++col) {
2037 << cell(index(row, col))
2043 docstring const & num = numbers_[row];
2045 os << '(' << num << ')';
2052 os << ETag("mtable");
2056 void InsetMathHull::mathAsLatex(WriteStream & os) const
2058 MathEnsurer ensurer(os, false);
2059 bool havenumbers = haveNumbers();
2060 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2063 os << cell(index(0, 0));
2067 os << "<table class='mathtable'>";
2068 for (row_type row = 0; row < nrows(); ++row) {
2070 for (col_type col = 0; col < ncols(); ++col) {
2071 os << "<td class='math'>";
2072 os << cell(index(row, col));
2077 docstring const & num = numbers_[row];
2079 os << '(' << num << ')';
2088 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2090 BufferParams::MathOutput const mathtype =
2091 buffer().params().html_math_output;
2093 bool success = false;
2095 // we output all the labels just at the beginning of the equation.
2096 // this should be fine.
2097 for (size_t i = 0; i != label_.size(); ++i) {
2098 InsetLabel const * const il = label_[i];
2104 // FIXME Eventually we would like to do this inset by inset.
2105 if (mathtype == BufferParams::MathML) {
2106 odocstringstream os;
2111 } catch (MathExportException const &) {}
2113 if (getType() == hullSimple)
2114 xs << html::StartTag("math",
2115 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2117 xs << html::StartTag("math",
2118 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2119 xs << XHTMLStream::ESCAPE_NONE
2121 << html::EndTag("math");
2123 } else if (mathtype == BufferParams::HTML) {
2124 odocstringstream os;
2129 } catch (MathExportException const &) {}
2131 string const tag = (getType() == hullSimple) ? "span" : "div";
2132 xs << html::StartTag(tag, "class='formula'", true)
2133 << XHTMLStream::ESCAPE_NONE
2135 << html::EndTag(tag);
2139 // what we actually want is this:
2141 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2143 // || mathtype == BufferParams::Images
2145 // but what follows is equivalent, since we'll enter only if either (a) we
2146 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2147 // aren't doing LaTeX, in which case we are doing Images.
2148 if (!success && mathtype != BufferParams::LaTeX) {
2149 loadPreview(docit_);
2150 graphics::PreviewImage const * pimage = preview_->getPreviewImage(buffer());
2152 // FIXME Do we always have png?
2153 string const tag = (getType() == hullSimple) ? "span" : "div";
2154 FileName const & mathimg = pimage->filename();
2155 xs << html::StartTag(tag)
2156 << html::CompTag("img", "src=\"" + mathimg.onlyFileName() + "\"")
2157 << html::EndTag(tag)
2159 // add the file to the list of files to be exported
2160 op.exportdata->addExternalFile("xhtml", mathimg);
2165 // so we'll pass this test if we've failed everything else, or
2166 // if mathtype was LaTeX, since we won't have entered any of the
2168 if (!success /* || mathtype != BufferParams::LaTeX */) {
2169 // Unfortunately, we cannot use latexString() because we do not want
2170 // $...$ or whatever.
2171 odocstringstream ls;
2172 WriteStream wi(ls, false, true, WriteStream::wsPreview);
2173 ModeSpecifier specifier(wi, MATH_MODE);
2175 docstring const latex = ls.str();
2177 // class='math' allows for use of jsMath
2178 // http://www.math.union.edu/~dpvc/jsMath/
2180 // probably should allow for some kind of customization here
2181 string const tag = (getType() == hullSimple) ? "span" : "div";
2182 xs << html::StartTag(tag, "class='math'")
2183 << XHTMLStream::ESCAPE_AND
2185 << html::EndTag(tag)
2192 void InsetMathHull::toString(odocstream & os) const
2194 plaintext(os, OutputParams(0));
2198 void InsetMathHull::forToc(docstring & os, size_t) const
2200 odocstringstream ods;
2201 plaintext(ods, OutputParams(0));
2206 docstring InsetMathHull::contextMenuName() const
2208 return from_ascii("context-math");
2212 void InsetMathHull::recordLocation(DocIterator const & di)