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_ == hullMultline)
347 if (type_ == hullGather)
349 if (type_ >= hullAlign)
350 return "rl"[col & 1];
355 char InsetMathHull::displayColAlign(col_type col, row_type row) const
357 if (type_ == hullMultline) {
360 if (row == nrows() - 1)
363 return InsetMathGrid::displayColAlign(col, row);
367 int InsetMathHull::defaultColSpace(col_type col)
369 if (type_ == hullAlign || type_ == hullAlignAt)
371 if (type_ == hullXAlignAt)
372 return (col & 1) ? 20 : 0;
373 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
374 return (col & 1) ? 40 : 0;
379 docstring InsetMathHull::standardFont() const
384 font_name = from_ascii("texttt");
387 font_name = from_ascii("lyxnochange");
390 font_name = from_ascii("mathnormal");
396 ColorCode InsetMathHull::standardColor() const
402 color = Color_foreground;
411 bool InsetMathHull::previewState(BufferView * bv) const
413 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
414 graphics::PreviewImage const * pimage =
415 preview_->getPreviewImage(bv->buffer());
416 return pimage && pimage->image();
422 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
424 if (previewState(mi.base.bv)) {
425 preview_->metrics(mi, dim);
426 // insert a one pixel gap in front of the formula
429 dim.des += displayMargin();
430 // Cache the inset dimension.
431 setDimCache(mi, dim);
435 FontSetChanger dummy1(mi.base, standardFont());
436 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
438 // let the cells adjust themselves
439 InsetMathGrid::metrics(mi, dim);
442 dim.asc += displayMargin();
443 dim.des += displayMargin();
446 if (numberedType()) {
447 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
449 for (row_type row = 0; row < nrows(); ++row)
450 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
456 if (type_ == hullRegexp)
458 // make it at least as high as the current font
461 math_font_max_dim(mi.base.font, asc, des);
462 dim.asc = max(dim.asc, asc);
463 dim.des = max(dim.des, des);
464 // Cache the inset dimension.
465 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
466 setDimCache(mi, dim);
470 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
472 if (previewState(pi.base.bv))
473 return graphics::PreviewLoader::backgroundColor();
478 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
480 Dimension const dim = dimension(*pi.base.bv);
481 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
482 dim.asc + dim.des - 1, pi.backgroundColor(this));
486 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
488 use_preview_ = previewState(pi.base.bv);
490 if (type_ == hullRegexp) {
491 Dimension const dim = dimension(*pi.base.bv);
492 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
493 dim.width() - 2, dim.height() - 2, Color_regexpframe);
496 // one pixel gap in front
497 preview_->draw(pi, x + 1, y);
498 setPosCache(pi, x, y);
502 ColorCode color = pi.selected && lyxrc.use_system_colors
503 ? Color_selectiontext : standardColor();
504 bool const really_change_color = pi.base.font.color() == Color_none;
505 ColorChanger dummy0(pi.base.font, color, really_change_color);
506 FontSetChanger dummy1(pi.base, standardFont());
507 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
509 InsetMathGrid::draw(pi, x + 1, y);
511 if (numberedType()) {
512 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
513 for (row_type row = 0; row < nrows(); ++row) {
514 int const yy = y + rowinfo_[row].offset_;
515 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
516 docstring const nl = nicelabel(row);
520 setPosCache(pi, x, y);
524 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
527 InsetMathGrid::metricsT(mi, dim);
530 WriteStream wi(os, false, true, WriteStream::wsDefault);
532 dim.wid = os.str().size();
539 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
542 InsetMathGrid::drawT(pain, x, y);
545 WriteStream wi(os, false, true, WriteStream::wsDefault);
547 pain.draw(x, y, os.str().c_str());
552 static docstring latexString(InsetMathHull const & inset)
555 // This has to be static, because a preview snippet or a math
556 // macro containing math in text mode (such as $\text{$\phi$}$ or
557 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
558 // first time as a whole, and the second time only the inner math.
559 // In this last case inset.buffer() would be invalid.
560 static Encoding const * encoding = 0;
561 if (inset.isBufferValid())
562 encoding = &(inset.buffer().params().encoding());
563 WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
569 void InsetMathHull::initUnicodeMath() const
571 // Trigger classification of the unicode symbols in this inset
572 docstring const dummy = latexString(*this);
576 void InsetMathHull::addPreview(DocIterator const & inset_pos,
577 graphics::PreviewLoader & /*ploader*/) const
579 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
580 preparePreview(inset_pos);
585 void InsetMathHull::preparePreview(DocIterator const & pos,
586 bool forexport) const
588 // there is no need to do all the macro stuff if we're not
589 // actually going to generate the preview.
590 if (RenderPreview::status() != LyXRC::PREVIEW_ON && !forexport)
593 Buffer const * buffer = pos.buffer();
595 // collect macros at this position
597 buffer->listMacroNames(macros);
598 MacroNameSet::iterator it = macros.begin();
599 MacroNameSet::iterator end = macros.end();
600 odocstringstream macro_preamble;
601 for (; it != end; ++it) {
602 MacroData const * data = buffer->getMacro(*it, pos, true);
604 data->write(macro_preamble, true);
605 macro_preamble << endl;
610 if (forexport && haveNumbers()) {
611 docstring eqstr = from_ascii("equation");
612 CounterMap::const_iterator it = counter_map.find(eqstr);
613 if (it != counter_map.end()) {
614 int num = it->second;
616 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
617 '{' + convert<docstring>(num) + '}' + '\n';
619 for (size_t i = 0; i != numcnts; ++i) {
620 docstring cnt = from_ascii(counters_to_save[i]);
621 it = counter_map.find(cnt);
622 if (it == counter_map.end())
624 int num = it->second;
626 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
627 '{' + convert<docstring>(num) + '}';
630 docstring const snippet = macro_preamble.str() +
631 setcnt + latexString(*this);
632 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
633 preview_->addPreview(snippet, *buffer, forexport);
637 void InsetMathHull::reloadPreview(DocIterator const & pos) const
640 preview_->startLoading(*pos.buffer());
644 void InsetMathHull::loadPreview(DocIterator const & pos) const
646 bool const forexport = true;
647 preparePreview(pos, forexport);
648 preview_->startLoading(*pos.buffer(), forexport);
652 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
654 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
656 cur.screenUpdateFlags(Update::Force);
662 docstring InsetMathHull::label(row_type row) const
664 LASSERT(row < nrows(), /**/);
665 if (InsetLabel * il = label_[row])
666 return il->screenLabel();
671 void InsetMathHull::label(row_type row, docstring const & label)
673 //lyxerr << "setting label '" << label << "' for row " << row << endl;
677 label_[row] = dummy_pointer;
680 label_[row]->updateLabelAndRefs(label);
682 label_[row]->setParam("name", label);
686 InsetCommandParams p(LABEL_CODE);
688 label_[row] = new InsetLabel(buffer_, p);
690 label_[row]->setBuffer(buffer());
694 void InsetMathHull::numbered(row_type row, bool num)
696 numbered_[row] = num;
697 if (!numbered_[row] && label_[row]) {
704 bool InsetMathHull::numbered(row_type row) const
706 return numbered_[row];
710 bool InsetMathHull::ams() const
712 return type_ == hullAlign
713 || type_ == hullFlAlign
714 || type_ == hullMultline
715 || type_ == hullGather
716 || type_ == hullAlignAt
717 || type_ == hullXAlignAt
718 || type_ == hullXXAlignAt;
722 Inset::DisplayType InsetMathHull::display() const
724 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
729 bool InsetMathHull::numberedType() const
731 if (type_ == hullNone)
733 if (type_ == hullSimple)
735 if (type_ == hullXXAlignAt)
737 if (type_ == hullRegexp)
739 for (row_type row = 0; row < nrows(); ++row)
746 void InsetMathHull::validate(LaTeXFeatures & features) const
748 if (features.runparams().isLaTeX()) {
750 features.require("amsmath");
752 if (type_ == hullRegexp) {
753 features.require("color");
754 string frcol = lcolor.getLaTeXName(Color_regexpframe);
755 string bgcol = "white";
756 features.addPreambleSnippet(
757 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
758 + frcol + string("}{")
759 + bgcol + string("}{\\ensuremath{\\mathtt{#1}}}}"));
760 features.addPreambleSnippet(
761 string("\\newcommand{\\endregexp}{}"));
764 // Validation is necessary only if not using AMS math.
765 // To be safe, we will always run mathedvalidate.
766 //if (features.amsstyle)
769 //features.binom = true;
770 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
771 // it would be better to do this elsewhere, but we can't validate in
772 // InsetMathMatrix and we have no way, outside MathExtern, to know if
773 // we even have any matrices.
774 features.addCSSSnippet(
775 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
776 "table.matrix td{padding: 0.25px;}\n"
777 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
778 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
780 InsetMathGrid::validate(features);
784 void InsetMathHull::header_write(WriteStream & os) const
786 bool n = numberedType();
800 os << "\n\\begin{equation" << star(n) << "}\n";
810 os << "\n\\begin{" << hullName(type_) << star(n) << "}\n";
815 os << "\n\\begin{" << hullName(type_) << star(n) << '}'
816 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
820 os << "\n\\begin{" << hullName(type_) << '}'
821 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
829 os << "\n\\begin{unknown" << star(n) << "}\n";
835 void InsetMathHull::footer_write(WriteStream & os) const
837 bool n = numberedType();
850 os << "\n\\end{equation" << star(n) << "}\n";
862 os << "\n\\end{" << hullName(type_) << star(n) << "}\n";
866 os << "\n\\end{" << hullName(type_) << "}\n";
870 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
871 os << "\\endregexp{}}";
875 os << "\n\\end{unknown" << star(n) << "}\n";
881 bool InsetMathHull::rowChangeOK() const
884 type_ == hullEqnArray || type_ == hullAlign ||
885 type_ == hullFlAlign || type_ == hullAlignAt ||
886 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
887 type_ == hullGather || type_ == hullMultline;
891 bool InsetMathHull::colChangeOK() const
894 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
895 type_ == hullXAlignAt || type_ == hullXXAlignAt;
899 void InsetMathHull::addRow(row_type row)
904 bool numbered = numberedType();
905 // Move the number and raw pointer, do not call label() (bug 7511)
906 InsetLabel * label = dummy_pointer;
907 docstring number = empty_docstring();
908 if (type_ == hullMultline) {
909 if (row + 1 == nrows()) {
910 numbered_[row] = false;
911 swap(label, label_[row]);
912 swap(number, numbers_[row]);
917 numbered_.insert(numbered_.begin() + row + 1, numbered);
918 numbers_.insert(numbers_.begin() + row + 1, number);
919 label_.insert(label_.begin() + row + 1, label);
920 InsetMathGrid::addRow(row);
924 void InsetMathHull::swapRow(row_type row)
928 if (row + 1 == nrows())
930 // gcc implements the standard std::vector<bool> which is *not* a container:
931 // http://www.gotw.ca/publications/N1185.pdf
932 // As a results, it doesn't like this:
933 // swap(numbered_[row], numbered_[row + 1]);
934 // so we do it manually:
935 bool const b = numbered_[row];
936 numbered_[row] = numbered_[row + 1];
937 numbered_[row + 1] = b;
938 swap(numbers_[row], numbers_[row + 1]);
939 swap(label_[row], label_[row + 1]);
940 InsetMathGrid::swapRow(row);
944 void InsetMathHull::delRow(row_type row)
946 if (nrows() <= 1 || !rowChangeOK())
948 if (row + 1 == nrows() && type_ == hullMultline) {
949 bool const b = numbered_[row - 1];
950 numbered_[row - 1] = numbered_[row];
952 swap(numbers_[row - 1], numbers_[row]);
953 swap(label_[row - 1], label_[row]);
954 InsetMathGrid::delRow(row);
957 InsetMathGrid::delRow(row);
958 // The last dummy row has no number info nor a label.
959 // Test nrows() + 1 because we have already erased the row.
960 if (row == nrows() + 1)
962 numbered_.erase(numbered_.begin() + row);
963 numbers_.erase(numbers_.begin() + row);
965 label_.erase(label_.begin() + row);
969 void InsetMathHull::addCol(col_type col)
973 InsetMathGrid::addCol(col);
977 void InsetMathHull::delCol(col_type col)
979 if (ncols() <= 1 || !colChangeOK())
981 InsetMathGrid::delCol(col);
985 docstring InsetMathHull::nicelabel(row_type row) const
989 docstring const & val = numbers_[row];
991 return '(' + val + ')';
992 return '(' + val + ',' + label_[row]->screenLabel() + ')';
996 void InsetMathHull::glueall(HullType type)
999 for (idx_type i = 0; i < nargs(); ++i)
1001 InsetLabel * label = 0;
1002 if (type == hullEquation) {
1003 // preserve first non-empty label
1004 for (row_type row = 0; row < nrows(); ++row) {
1006 label = label_[row];
1012 *this = InsetMathHull(buffer_, hullSimple);
1019 void InsetMathHull::splitTo2Cols()
1021 LASSERT(ncols() == 1, /**/);
1022 InsetMathGrid::addCol(1);
1023 for (row_type row = 0; row < nrows(); ++row) {
1024 idx_type const i = 2 * row;
1025 pos_type pos = firstRelOp(cell(i));
1026 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1027 cell(i).erase(pos, cell(i).size());
1032 void InsetMathHull::splitTo3Cols()
1034 LASSERT(ncols() < 3, /**/);
1037 InsetMathGrid::addCol(2);
1038 for (row_type row = 0; row < nrows(); ++row) {
1039 idx_type const i = 3 * row + 1;
1040 if (cell(i).size()) {
1041 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1042 cell(i).erase(1, cell(i).size());
1048 void InsetMathHull::changeCols(col_type cols)
1050 if (ncols() == cols)
1052 else if (ncols() < cols) {
1058 while (ncols() < cols)
1059 InsetMathGrid::addCol(ncols());
1065 for (row_type row = 0; row < nrows(); ++row) {
1066 idx_type const i = row * ncols();
1067 for (col_type col = cols; col < ncols(); ++col) {
1068 cell(i + cols - 1).append(cell(i + col));
1072 while (ncols() > cols) {
1073 InsetMathGrid::delCol(ncols() - 1);
1078 HullType InsetMathHull::getType() const
1084 void InsetMathHull::setType(HullType type)
1091 void InsetMathHull::mutate(HullType newtype)
1093 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1095 // we try to move along the chain
1096 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1098 // +-------------------------------------+
1099 // we use eqnarray as intermediate type for mutations that are not
1100 // directly supported because it handles labels and numbering for
1103 if (newtype == type_) {
1107 else if (newtype < hullNone) {
1112 else if (type_ == hullNone) {
1113 setType(hullSimple);
1118 else if (type_ == hullSimple) {
1119 if (newtype == hullNone) {
1123 setType(hullEquation);
1124 numbered(0, label_[0] ? true : false);
1129 else if (type_ == hullEquation) {
1130 if (newtype < type_) {
1131 setType(hullSimple);
1134 } else if (newtype == hullEqnArray) {
1135 // split it "nicely" on the first relop
1137 setType(hullEqnArray);
1138 } else if (newtype == hullMultline || newtype == hullGather) {
1141 // split it "nicely"
1148 else if (type_ == hullEqnArray) {
1149 if (newtype < type_) {
1152 } else { // align & Co.
1159 else if (type_ == hullAlign || type_ == hullAlignAt ||
1160 type_ == hullXAlignAt || type_ == hullFlAlign) {
1161 if (newtype < hullAlign) {
1163 setType(hullEqnArray);
1165 } else if (newtype == hullGather || newtype == hullMultline) {
1168 } else if (newtype == hullXXAlignAt) {
1169 for (row_type row = 0; row < nrows(); ++row)
1170 numbered(row, false);
1177 else if (type_ == hullXXAlignAt) {
1178 for (row_type row = 0; row < nrows(); ++row)
1179 numbered(row, false);
1180 if (newtype < hullAlign) {
1182 setType(hullEqnArray);
1184 } else if (newtype == hullGather || newtype == hullMultline) {
1192 else if (type_ == hullMultline || type_ == hullGather) {
1193 if (newtype == hullGather || newtype == hullMultline)
1195 else if (newtype == hullAlign || newtype == hullFlAlign ||
1196 newtype == hullAlignAt || newtype == hullXAlignAt) {
1199 } else if (newtype == hullXXAlignAt) {
1201 for (row_type row = 0; row < nrows(); ++row)
1202 numbered(row, false);
1206 setType(hullEqnArray);
1212 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1213 << "' to '" << to_utf8(hullName(newtype))
1214 << "' not implemented" << endl;
1219 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1220 bool last_eoln) const
1223 if (numberedType()) {
1224 if (label_[row] && numbered_[row]) {
1225 docstring const name =
1226 latex ? escape(label_[row]->getParam("name"))
1227 : label_[row]->getParam("name");
1228 res += "\\label{" + name + '}';
1230 if (!numbered_[row] && (type_ != hullMultline))
1231 res += "\\nonumber ";
1233 // Never add \\ on the last empty line of eqnarray and friends
1235 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1239 void InsetMathHull::write(WriteStream & os) const
1241 ModeSpecifier specifier(os, MATH_MODE);
1243 InsetMathGrid::write(os);
1248 void InsetMathHull::normalize(NormalStream & os) const
1250 os << "[formula " << hullName(type_) << ' ';
1251 InsetMathGrid::normalize(os);
1256 void InsetMathHull::infoize(odocstream & os) const
1258 os << "Type: " << hullName(type_);
1262 void InsetMathHull::check() const
1264 LASSERT(numbered_.size() == nrows(), /**/);
1265 LASSERT(numbers_.size() == nrows(), /**/);
1266 LASSERT(label_.size() == nrows(), /**/);
1270 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1274 idocstringstream iss(func.argument());
1275 iss >> dlang >> extra;
1277 extra = from_ascii("noextra");
1278 string const lang = to_ascii(dlang);
1280 // FIXME: temporarily disabled
1281 //if (cur.selection()) {
1284 // lyxerr << "use selection: " << ar << endl;
1285 // insert(pipeThroughExtern(lang, extra, ar));
1289 // only inline, display or eqnarray math is allowed
1290 if (getType() > hullEqnArray) {
1291 frontend::Alert::warning(_("Bad math environment"),
1292 _("Computation cannot be performed for AMS "
1293 "math environments.\nChange the math "
1294 "formula type and try again."));
1299 eq.push_back(MathAtom(new InsetMathChar('=')));
1301 // go to first item in line
1302 cur.idx() -= cur.idx() % ncols();
1305 if (getType() == hullSimple) {
1306 size_type pos = cur.cell().find_last(eq);
1308 if (cur.inMathed() && cur.selection()) {
1309 asArray(grabAndEraseSelection(cur), ar);
1310 } else if (pos == cur.cell().size()) {
1312 lyxerr << "use whole cell: " << ar << endl;
1314 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1315 lyxerr << "use partial cell form pos: " << pos << endl;
1317 cur.cell().append(eq);
1318 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1319 cur.pos() = cur.lastpos();
1323 if (getType() == hullEquation) {
1324 lyxerr << "use equation inset" << endl;
1325 mutate(hullEqnArray);
1326 MathData & ar = cur.cell();
1327 lyxerr << "use cell: " << ar << endl;
1331 cur.cell() = pipeThroughExtern(lang, extra, ar);
1332 // move to end of line
1333 cur.pos() = cur.lastpos();
1338 lyxerr << "use eqnarray" << endl;
1339 cur.idx() += 2 - cur.idx() % ncols();
1341 MathData ar = cur.cell();
1342 lyxerr << "use cell: " << ar << endl;
1343 // FIXME: temporarily disabled
1349 cur.cell() = pipeThroughExtern(lang, extra, ar);
1350 cur.pos() = cur.lastpos();
1355 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1357 //lyxerr << "action: " << cmd.action() << endl;
1358 switch (cmd.action()) {
1360 case LFUN_FINISHED_BACKWARD:
1361 case LFUN_FINISHED_FORWARD:
1362 case LFUN_FINISHED_RIGHT:
1363 case LFUN_FINISHED_LEFT:
1364 //lyxerr << "action: " << cmd.action() << endl;
1365 InsetMathGrid::doDispatch(cur, cmd);
1369 case LFUN_BREAK_PARAGRAPH:
1370 // just swallow this
1373 case LFUN_NEWLINE_INSERT:
1374 // some magic for the common case
1375 if (type_ == hullSimple || type_ == hullEquation) {
1376 cur.recordUndoInset();
1378 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1379 mutate(align ? hullAlign : hullEqnArray);
1380 // mutate() may change labels and such.
1381 cur.forceBufferUpdate();
1382 cur.idx() = nrows() * ncols() - 1;
1383 cur.pos() = cur.lastpos();
1385 InsetMathGrid::doDispatch(cur, cmd);
1388 case LFUN_MATH_NUMBER_TOGGLE: {
1389 //lyxerr << "toggling all numbers" << endl;
1390 cur.recordUndoInset();
1391 bool old = numberedType();
1392 if (type_ == hullMultline)
1393 numbered(nrows() - 1, !old);
1395 for (row_type row = 0; row < nrows(); ++row)
1396 numbered(row, !old);
1398 cur.message(old ? _("No number") : _("Number"));
1399 cur.forceBufferUpdate();
1403 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1404 cur.recordUndoInset();
1405 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1406 bool old = numbered(r);
1407 cur.message(old ? _("No number") : _("Number"));
1409 cur.forceBufferUpdate();
1413 case LFUN_LABEL_INSERT: {
1414 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1415 docstring old_label = label(r);
1416 docstring const default_label = from_ascii("eq:");
1417 if (old_label.empty())
1418 old_label = default_label;
1420 InsetCommandParams p(LABEL_CODE);
1421 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1422 string const data = InsetCommand::params2string(p);
1424 if (cmd.argument().empty())
1425 cur.bv().showDialog("label", data);
1427 FuncRequest fr(LFUN_INSET_INSERT, data);
1433 case LFUN_LABEL_COPY_AS_REF: {
1435 if (cmd.argument().empty() && &cur.inset() == this)
1436 // if there is no argument and we're inside math, we retrieve
1437 // the row number from the cursor position.
1438 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1440 // if there is an argument, find the corresponding label, else
1441 // check whether there is at least one label.
1442 for (row = 0; row != nrows(); ++row)
1443 if (numbered_[row] && label_[row]
1444 && (cmd.argument().empty() || label(row) == cmd.argument()))
1451 InsetCommandParams p(REF_CODE, "ref");
1452 p["reference"] = label(row);
1453 cap::clearSelection();
1454 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1458 case LFUN_WORD_DELETE_FORWARD:
1459 case LFUN_CHAR_DELETE_FORWARD:
1460 if (col(cur.idx()) + 1 == ncols()
1461 && cur.pos() == cur.lastpos()
1462 && !cur.selection()) {
1463 if (!label(row(cur.idx())).empty()) {
1464 cur.recordUndoInset();
1465 label(row(cur.idx()), docstring());
1466 } else if (numbered(row(cur.idx()))) {
1467 cur.recordUndoInset();
1468 numbered(row(cur.idx()), false);
1469 cur.forceBufferUpdate();
1471 InsetMathGrid::doDispatch(cur, cmd);
1475 InsetMathGrid::doDispatch(cur, cmd);
1480 case LFUN_INSET_INSERT: {
1481 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1482 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1483 string const name = cmd.getArg(0);
1484 if (name == "label") {
1485 InsetCommandParams p(LABEL_CODE);
1486 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1487 docstring str = p["name"];
1488 cur.recordUndoInset();
1489 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1493 docstring old = label(r);
1496 // The label will take care of the reference update.
1500 // Newly created inset so initialize it.
1501 label_[r]->initView();
1504 cur.forceBufferUpdate();
1507 InsetMathGrid::doDispatch(cur, cmd);
1511 case LFUN_MATH_EXTERN:
1512 cur.recordUndoInset();
1516 case LFUN_MATH_MUTATE: {
1517 cur.recordUndoInset();
1518 row_type row = cur.row();
1519 col_type col = cur.col();
1520 mutate(hullType(cmd.argument()));
1521 cur.idx() = row * ncols() + col;
1522 if (cur.idx() > cur.lastidx()) {
1523 cur.idx() = cur.lastidx();
1524 cur.pos() = cur.lastpos();
1526 if (cur.pos() > cur.lastpos())
1527 cur.pos() = cur.lastpos();
1529 cur.forceBufferUpdate();
1530 // FIXME: find some more clever handling of the selection,
1531 // i.e. preserve it.
1532 cur.clearSelection();
1533 //cur.dispatched(FINISHED);
1537 case LFUN_MATH_DISPLAY: {
1538 cur.recordUndoInset();
1539 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1541 cur.pos() = cur.lastpos();
1542 //cur.dispatched(FINISHED);
1547 InsetMathGrid::doDispatch(cur, cmd);
1553 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1554 FuncStatus & status) const
1556 switch (cmd.action()) {
1557 case LFUN_FINISHED_BACKWARD:
1558 case LFUN_FINISHED_FORWARD:
1559 case LFUN_FINISHED_RIGHT:
1560 case LFUN_FINISHED_LEFT:
1563 case LFUN_NEWLINE_INSERT:
1564 case LFUN_MATH_EXTERN:
1566 status.setEnabled(true);
1569 // we never allow this in math, and we want to bind enter
1570 // to another actions in command-alternatives
1571 case LFUN_BREAK_PARAGRAPH:
1572 status.setEnabled(false);
1574 case LFUN_MATH_MUTATE: {
1575 HullType const ht = hullType(cmd.argument());
1576 status.setOnOff(type_ == ht);
1577 status.setEnabled(true);
1579 if (ht != hullSimple) {
1580 Cursor tmpcur = cur;
1581 while (!tmpcur.empty()) {
1582 InsetCode code = tmpcur.inset().lyxCode();
1583 if (code == BOX_CODE) {
1585 } else if (code == TABULAR_CODE) {
1586 FuncRequest tmpcmd(LFUN_MATH_DISPLAY);
1587 if (tmpcur.getStatus(tmpcmd, status) && !status.enabled())
1595 case LFUN_MATH_DISPLAY: {
1597 if (cur.depth() > 1) {
1598 Inset const & in = cur[cur.depth()-2].inset();
1599 if (in.lyxCode() == SCRIPT_CODE)
1600 enable = display() != Inline;
1602 status.setEnabled(enable);
1606 case LFUN_MATH_NUMBER_TOGGLE:
1607 // FIXME: what is the right test, this or the one of
1609 status.setEnabled(display() != Inline);
1610 status.setOnOff(numberedType());
1613 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1614 // FIXME: what is the right test, this or the one of
1616 bool const enable = (type_ == hullMultline)
1617 ? (nrows() - 1 == cur.row())
1618 : display() != Inline;
1619 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1620 status.setEnabled(enable);
1621 status.setOnOff(enable && numbered(r));
1625 case LFUN_LABEL_INSERT:
1626 status.setEnabled(type_ != hullSimple);
1629 case LFUN_LABEL_COPY_AS_REF: {
1630 bool enabled = false;
1632 if (cmd.argument().empty() && &cur.inset() == this) {
1633 // if there is no argument and we're inside math, we retrieve
1634 // the row number from the cursor position.
1635 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1636 enabled = numberedType() && label_[row] && numbered_[row];
1638 // if there is an argument, find the corresponding label, else
1639 // check whether there is at least one label.
1640 for (row_type row = 0; row != nrows(); ++row) {
1641 if (numbered_[row] && label_[row] &&
1642 (cmd.argument().empty() || label(row) == cmd.argument())) {
1648 status.setEnabled(enabled);
1652 case LFUN_INSET_INSERT:
1653 if (cmd.getArg(0) == "label") {
1654 status.setEnabled(type_ != hullSimple);
1657 return InsetMathGrid::getStatus(cur, cmd, status);
1659 case LFUN_INSET_MODIFY: {
1660 istringstream is(to_utf8(cmd.argument()));
1664 return InsetMathGrid::getStatus(cur, cmd, status);
1667 && (s == "append-row"
1668 || s == "delete-row"
1669 || s == "copy-row")) {
1670 status.message(bformat(
1671 from_utf8(N_("Can't change number of rows in '%1$s'")),
1673 status.setEnabled(false);
1677 && (s == "append-column"
1678 || s == "delete-column"
1679 || s == "copy-column")) {
1680 status.message(bformat(
1681 from_utf8(N_("Can't change number of columns in '%1$s'")),
1683 status.setEnabled(false);
1686 if ((type_ == hullSimple
1687 || type_ == hullEquation
1688 || type_ == hullNone) &&
1689 (s == "add-hline-above" || s == "add-hline-below")) {
1690 status.message(bformat(
1691 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1693 status.setEnabled(false);
1696 if (s == "add-vline-left" || s == "add-vline-right") {
1697 status.message(bformat(
1698 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1700 status.setEnabled(false);
1703 if (s == "valign-top" || s == "valign-middle"
1704 || s == "valign-bottom" || s == "align-left"
1705 || s == "align-center" || s == "align-right") {
1706 status.setEnabled(false);
1709 return InsetMathGrid::getStatus(cur, cmd, status);
1713 return InsetMathGrid::getStatus(cur, cmd, status);
1716 // This cannot really happen, but inserted to shut-up gcc
1717 return InsetMathGrid::getStatus(cur, cmd, status);
1721 /////////////////////////////////////////////////////////////////////
1725 // simply scrap this function if you want
1726 void InsetMathHull::mutateToText()
1729 // translate to latex
1731 latex(os, false, false);
1732 string str = os.str();
1735 Text * lt = view_->cursor().innerText();
1736 string::const_iterator cit = str.begin();
1737 string::const_iterator end = str.end();
1738 for (; cit != end; ++cit)
1739 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1742 //dispatch(LFUN_ESCAPE);
1747 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1748 docstring const & font)
1750 // this whole function is a hack and won't work for incremental font
1753 if (cur.inset().asInsetMath()->name() == font)
1754 cur.handleFont(to_utf8(font));
1756 cur.handleNest(createInsetMath(font, cur.buffer()));
1762 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1767 font.fromString(to_utf8(arg), b);
1768 if (font.fontInfo().color() != Color_inherit) {
1769 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1770 cur.handleNest(at, 0);
1775 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1778 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1779 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1780 enter_front ? idxFirst(cur) : idxLast(cur);
1781 // The inset formula dimension is not necessarily the same as the
1782 // one of the instant preview image, so we have to indicate to the
1783 // BufferView that a metrics update is needed.
1784 cur.screenUpdateFlags(Update::Force);
1788 void InsetMathHull::revealCodes(Cursor & cur) const
1790 if (!cur.inMathed())
1792 odocstringstream os;
1794 cur.message(os.str());
1796 // write something to the minibuffer
1797 // translate to latex
1801 string str = os.str();
1803 string::size_type pos = 0;
1805 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1808 else if (*it == '\0') {
1810 pos = it - str.begin();
1816 res = res.substr(pos - 30);
1817 if (res.size() > 60)
1818 res = res.substr(0, 60);
1824 /////////////////////////////////////////////////////////////////////
1828 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1831 // FIXME: completely broken
1832 static InsetMathHull * lastformula = 0;
1833 static CursorBase current = DocIterator(ibegin(nucleus()));
1835 static string laststr;
1837 if (lastformula != this || laststr != str) {
1838 //lyxerr << "reset lastformula to " << this << endl;
1841 current = ibegin(nucleus());
1843 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1847 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1849 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1850 CursorSlice & top = it.back();
1851 MathData const & a = top.asInsetMath()->cell(top.idx_);
1852 if (a.matchpart(ar, top.pos_)) {
1853 bv->cursor().setSelection(it, ar.size());
1855 top.pos_ += ar.size();
1861 //lyxerr << "not found!" << endl;
1868 void InsetMathHull::write(ostream & os) const
1870 odocstringstream oss;
1871 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1874 os << to_utf8(oss.str());
1878 void InsetMathHull::read(Lexer & lex)
1881 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1882 operator=(*at->asHullInset());
1886 bool InsetMathHull::readQuiet(Lexer & lex)
1889 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1891 operator=(*at->asHullInset());
1896 int InsetMathHull::plaintext(odocstream & os, OutputParams const & op) const
1898 // disables ASCII-art for export of equations. See #2275.
1899 if (0 && display()) {
1903 TextPainter tpain(dim.width(), dim.height());
1904 drawT(tpain, 0, dim.ascent());
1906 // reset metrics cache to "real" values
1908 return tpain.textheight();
1911 odocstringstream oss;
1912 Encoding const * const enc = encodings.fromLyXName("utf8");
1913 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1916 if (type_ == hullRegexp)
1919 for (row_type r = 0; r < nrows(); ++r) {
1920 for (col_type c = 0; c < ncols(); ++c)
1921 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
1922 // if it's for the TOC, we write just the first line
1923 // and do not include the newline.
1929 docstring const str = oss.str();
1935 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1940 if (getType() == hullSimple)
1941 name = from_ascii("inlineequation");
1943 name = from_ascii("informalequation");
1945 docstring bname = name;
1946 if (!label(0).empty())
1947 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1949 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1951 odocstringstream ls;
1952 if (runparams.flavor == OutputParams::XML) {
1953 ms << MTag("alt role='tex' ");
1954 // Workaround for db2latex: db2latex always includes equations with
1955 // \ensuremath{} or \begin{display}\end{display}
1956 // so we strip LyX' math environment
1957 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1958 InsetMathGrid::write(wi);
1959 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1964 InsetMathGrid::mathmlize(ms);
1969 otexstream ols(ls, texrow);
1970 ms << MTag("alt role='tex'");
1971 latex(ols, runparams);
1972 res = texrow.rows();
1973 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1977 ms << from_ascii("<graphic fileref=\"eqn/");
1978 if (!label(0).empty())
1979 ms << sgml::cleanID(buffer(), runparams, label(0));
1981 ms << sgml::uniqueID(from_ascii("anon"));
1983 if (runparams.flavor == OutputParams::XML)
1984 ms << from_ascii("\"/>");
1986 ms << from_ascii("\">");
1988 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1990 return ms.line() + res;
1994 bool InsetMathHull::haveNumbers() const
1996 bool havenumbers = false;
1997 // inline formulas are never numbered (bug 7351 part 3)
1998 if (getType() == hullSimple)
2000 for (size_t i = 0; i != numbered_.size(); ++i) {
2011 // We need to do something about alignment here.
2013 // This duplicates code from InsetMathGrid, but
2014 // we need access here to number information,
2015 // and we simply do not have that in InsetMathGrid.
2016 void InsetMathHull::htmlize(HtmlStream & os) const
2018 bool const havenumbers = haveNumbers();
2019 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2022 os << cell(index(0, 0));
2026 os << MTag("table", "class='mathtable'");
2027 for (row_type row = 0; row < nrows(); ++row) {
2029 for (col_type col = 0; col < ncols(); ++col) {
2031 os << cell(index(row, col));
2036 docstring const & num = numbers_[row];
2038 os << '(' << num << ')';
2043 os << ETag("table");
2047 // this duplicates code from InsetMathGrid, but
2048 // we need access here to number information,
2049 // and we simply do not have that in InsetMathGrid.
2050 void InsetMathHull::mathmlize(MathStream & os) const
2052 bool const havenumbers = haveNumbers();
2053 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2056 os << MTag("mtable");
2057 char const * const celltag = havetable ? "mtd" : "mrow";
2058 // FIXME There does not seem to be wide support at the moment
2059 // for mlabeledtr, so we have to use just mtr for now.
2060 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2061 char const * const rowtag = "mtr";
2062 for (row_type row = 0; row < nrows(); ++row) {
2065 for (col_type col = 0; col < ncols(); ++col) {
2067 << cell(index(row, col))
2073 docstring const & num = numbers_[row];
2075 os << '(' << num << ')';
2082 os << ETag("mtable");
2086 void InsetMathHull::mathAsLatex(WriteStream & os) const
2088 MathEnsurer ensurer(os, false);
2089 bool havenumbers = haveNumbers();
2090 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2093 os << cell(index(0, 0));
2097 os << "<table class='mathtable'>";
2098 for (row_type row = 0; row < nrows(); ++row) {
2100 for (col_type col = 0; col < ncols(); ++col) {
2101 os << "<td class='math'>";
2102 os << cell(index(row, col));
2107 docstring const & num = numbers_[row];
2109 os << '(' << num << ')';
2118 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2120 BufferParams::MathOutput const mathtype =
2121 buffer().params().html_math_output;
2123 bool success = false;
2125 // we output all the labels just at the beginning of the equation.
2126 // this should be fine.
2127 for (size_t i = 0; i != label_.size(); ++i) {
2128 InsetLabel const * const il = label_[i];
2134 // FIXME Eventually we would like to do this inset by inset.
2135 if (mathtype == BufferParams::MathML) {
2136 odocstringstream os;
2141 } catch (MathExportException const &) {}
2143 if (getType() == hullSimple)
2144 xs << html::StartTag("math",
2145 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2147 xs << html::StartTag("math",
2148 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2149 xs << XHTMLStream::ESCAPE_NONE
2151 << html::EndTag("math");
2153 } else if (mathtype == BufferParams::HTML) {
2154 odocstringstream os;
2159 } catch (MathExportException const &) {}
2161 string const tag = (getType() == hullSimple) ? "span" : "div";
2162 xs << html::StartTag(tag, "class='formula'", true)
2163 << XHTMLStream::ESCAPE_NONE
2165 << html::EndTag(tag);
2169 // what we actually want is this:
2171 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2173 // || mathtype == BufferParams::Images
2175 // but what follows is equivalent, since we'll enter only if either (a) we
2176 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2177 // aren't doing LaTeX, in which case we are doing Images.
2178 if (!success && mathtype != BufferParams::LaTeX) {
2179 graphics::PreviewImage const * pimage = 0;
2181 loadPreview(docit_);
2182 pimage = preview_->getPreviewImage(buffer());
2183 // FIXME Do we always have png?
2186 if (pimage || op.dryrun) {
2187 string const filename = pimage ? pimage->filename().onlyFileName()
2188 : "previewimage.png";
2190 // if we are not in the master buffer, then we need to see that the
2191 // generated image is copied there; otherwise, preview fails.
2192 Buffer const * mbuf = buffer().masterBuffer();
2193 if (mbuf != &buffer()) {
2194 string mbtmp = mbuf->temppath();
2195 FileName const mbufimg(support::addName(mbtmp, filename));
2196 pimage->filename().copyTo(mbufimg);
2198 // add the file to the list of files to be exported
2199 op.exportdata->addExternalFile("xhtml", pimage->filename());
2202 string const tag = (getType() == hullSimple) ? "span" : "div";
2204 << html::StartTag(tag)
2205 << html::CompTag("img", "src=\"" + filename + "\"")
2206 << html::EndTag(tag)
2212 // so we'll pass this test if we've failed everything else, or
2213 // if mathtype was LaTeX, since we won't have entered any of the
2215 if (!success /* || mathtype != BufferParams::LaTeX */) {
2216 // Unfortunately, we cannot use latexString() because we do not want
2217 // $...$ or whatever.
2218 odocstringstream ls;
2219 WriteStream wi(ls, false, true, WriteStream::wsPreview);
2220 ModeSpecifier specifier(wi, MATH_MODE);
2222 docstring const latex = ls.str();
2224 // class='math' allows for use of jsMath
2225 // http://www.math.union.edu/~dpvc/jsMath/
2227 // probably should allow for some kind of customization here
2228 string const tag = (getType() == hullSimple) ? "span" : "div";
2229 xs << html::StartTag(tag, "class='math'")
2231 << html::EndTag(tag)
2238 void InsetMathHull::toString(odocstream & os) const
2240 plaintext(os, OutputParams(0));
2244 void InsetMathHull::forToc(docstring & os, size_t) const
2246 odocstringstream ods;
2254 string InsetMathHull::contextMenuName() const
2256 return "context-math";
2260 void InsetMathHull::recordLocation(DocIterator const & di)