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.addPreambleSnippet("<style type=\"text/css\">\n"
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;}\n"
781 InsetMathGrid::validate(features);
785 void InsetMathHull::header_write(WriteStream & os) const
787 bool n = numberedType();
801 os << "\n\\begin{equation" << star(n) << "}\n";
811 os << "\n\\begin{" << hullName(type_) << star(n) << "}\n";
816 os << "\n\\begin{" << hullName(type_) << star(n) << '}'
817 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
821 os << "\n\\begin{" << hullName(type_) << '}'
822 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
830 os << "\n\\begin{unknown" << star(n) << "}\n";
836 void InsetMathHull::footer_write(WriteStream & os) const
838 bool n = numberedType();
851 os << "\n\\end{equation" << star(n) << "}\n";
863 os << "\n\\end{" << hullName(type_) << star(n) << "}\n";
867 os << "\n\\end{" << hullName(type_) << "}\n";
871 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
872 os << "\\endregexp{}}";
876 os << "\n\\end{unknown" << star(n) << "}\n";
882 bool InsetMathHull::rowChangeOK() const
885 type_ == hullEqnArray || type_ == hullAlign ||
886 type_ == hullFlAlign || type_ == hullAlignAt ||
887 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
888 type_ == hullGather || type_ == hullMultline;
892 bool InsetMathHull::colChangeOK() const
895 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
896 type_ == hullXAlignAt || type_ == hullXXAlignAt;
900 void InsetMathHull::addRow(row_type row)
905 bool numbered = numberedType();
906 // Move the number and raw pointer, do not call label() (bug 7511)
907 InsetLabel * label = dummy_pointer;
908 docstring number = empty_docstring();
909 if (type_ == hullMultline) {
910 if (row + 1 == nrows()) {
911 numbered_[row] = false;
912 swap(label, label_[row]);
913 swap(number, numbers_[row]);
918 numbered_.insert(numbered_.begin() + row + 1, numbered);
919 numbers_.insert(numbers_.begin() + row + 1, number);
920 label_.insert(label_.begin() + row + 1, label);
921 InsetMathGrid::addRow(row);
925 void InsetMathHull::swapRow(row_type row)
929 if (row + 1 == nrows())
931 // gcc implements the standard std::vector<bool> which is *not* a container:
932 // http://www.gotw.ca/publications/N1185.pdf
933 // As a results, it doesn't like this:
934 // swap(numbered_[row], numbered_[row + 1]);
935 // so we do it manually:
936 bool const b = numbered_[row];
937 numbered_[row] = numbered_[row + 1];
938 numbered_[row + 1] = b;
939 swap(numbers_[row], numbers_[row + 1]);
940 swap(label_[row], label_[row + 1]);
941 InsetMathGrid::swapRow(row);
945 void InsetMathHull::delRow(row_type row)
947 if (nrows() <= 1 || !rowChangeOK())
949 if (row + 1 == nrows() && type_ == hullMultline) {
950 bool const b = numbered_[row - 1];
951 numbered_[row - 1] = numbered_[row];
953 swap(numbers_[row - 1], numbers_[row]);
954 swap(label_[row - 1], label_[row]);
955 InsetMathGrid::delRow(row);
958 InsetMathGrid::delRow(row);
959 // The last dummy row has no number info nor a label.
960 // Test nrows() + 1 because we have already erased the row.
961 if (row == nrows() + 1)
963 numbered_.erase(numbered_.begin() + row);
964 numbers_.erase(numbers_.begin() + row);
966 label_.erase(label_.begin() + row);
970 void InsetMathHull::addCol(col_type col)
974 InsetMathGrid::addCol(col);
978 void InsetMathHull::delCol(col_type col)
980 if (ncols() <= 1 || !colChangeOK())
982 InsetMathGrid::delCol(col);
986 docstring InsetMathHull::nicelabel(row_type row) const
990 docstring const & val = numbers_[row];
992 return '(' + val + ')';
993 return '(' + val + ',' + label_[row]->screenLabel() + ')';
997 void InsetMathHull::glueall(HullType type)
1000 for (idx_type i = 0; i < nargs(); ++i)
1002 InsetLabel * label = 0;
1003 if (type == hullEquation) {
1004 // preserve first non-empty label
1005 for (row_type row = 0; row < nrows(); ++row) {
1007 label = label_[row];
1013 *this = InsetMathHull(buffer_, hullSimple);
1020 void InsetMathHull::splitTo2Cols()
1022 LASSERT(ncols() == 1, /**/);
1023 InsetMathGrid::addCol(1);
1024 for (row_type row = 0; row < nrows(); ++row) {
1025 idx_type const i = 2 * row;
1026 pos_type pos = firstRelOp(cell(i));
1027 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1028 cell(i).erase(pos, cell(i).size());
1033 void InsetMathHull::splitTo3Cols()
1035 LASSERT(ncols() < 3, /**/);
1038 InsetMathGrid::addCol(2);
1039 for (row_type row = 0; row < nrows(); ++row) {
1040 idx_type const i = 3 * row + 1;
1041 if (cell(i).size()) {
1042 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1043 cell(i).erase(1, cell(i).size());
1049 void InsetMathHull::changeCols(col_type cols)
1051 if (ncols() == cols)
1053 else if (ncols() < cols) {
1059 while (ncols() < cols)
1060 InsetMathGrid::addCol(ncols());
1066 for (row_type row = 0; row < nrows(); ++row) {
1067 idx_type const i = row * ncols();
1068 for (col_type col = cols; col < ncols(); ++col) {
1069 cell(i + cols - 1).append(cell(i + col));
1073 while (ncols() > cols) {
1074 InsetMathGrid::delCol(ncols() - 1);
1079 HullType InsetMathHull::getType() const
1085 void InsetMathHull::setType(HullType type)
1092 void InsetMathHull::mutate(HullType newtype)
1094 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1096 // we try to move along the chain
1097 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1099 // +-------------------------------------+
1100 // we use eqnarray as intermediate type for mutations that are not
1101 // directly supported because it handles labels and numbering for
1104 if (newtype == type_) {
1108 else if (newtype < hullNone) {
1113 else if (type_ == hullNone) {
1114 setType(hullSimple);
1119 else if (type_ == hullSimple) {
1120 if (newtype == hullNone) {
1124 setType(hullEquation);
1125 numbered(0, label_[0] ? true : false);
1130 else if (type_ == hullEquation) {
1131 if (newtype < type_) {
1132 setType(hullSimple);
1135 } else if (newtype == hullEqnArray) {
1136 // split it "nicely" on the first relop
1138 setType(hullEqnArray);
1139 } else if (newtype == hullMultline || newtype == hullGather) {
1142 // split it "nicely"
1149 else if (type_ == hullEqnArray) {
1150 if (newtype < type_) {
1153 } else { // align & Co.
1160 else if (type_ == hullAlign || type_ == hullAlignAt ||
1161 type_ == hullXAlignAt || type_ == hullFlAlign) {
1162 if (newtype < hullAlign) {
1164 setType(hullEqnArray);
1166 } else if (newtype == hullGather || newtype == hullMultline) {
1169 } else if (newtype == hullXXAlignAt) {
1170 for (row_type row = 0; row < nrows(); ++row)
1171 numbered(row, false);
1178 else if (type_ == hullXXAlignAt) {
1179 for (row_type row = 0; row < nrows(); ++row)
1180 numbered(row, false);
1181 if (newtype < hullAlign) {
1183 setType(hullEqnArray);
1185 } else if (newtype == hullGather || newtype == hullMultline) {
1193 else if (type_ == hullMultline || type_ == hullGather) {
1194 if (newtype == hullGather || newtype == hullMultline)
1196 else if (newtype == hullAlign || newtype == hullFlAlign ||
1197 newtype == hullAlignAt || newtype == hullXAlignAt) {
1200 } else if (newtype == hullXXAlignAt) {
1202 for (row_type row = 0; row < nrows(); ++row)
1203 numbered(row, false);
1207 setType(hullEqnArray);
1213 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1214 << "' to '" << to_utf8(hullName(newtype))
1215 << "' not implemented" << endl;
1220 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1221 bool last_eoln) const
1224 if (numberedType()) {
1225 if (label_[row] && numbered_[row]) {
1226 docstring const name =
1227 latex ? escape(label_[row]->getParam("name"))
1228 : label_[row]->getParam("name");
1229 res += "\\label{" + name + '}';
1231 if (!numbered_[row] && (type_ != hullMultline))
1232 res += "\\nonumber ";
1234 // Never add \\ on the last empty line of eqnarray and friends
1236 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1240 void InsetMathHull::write(WriteStream & os) const
1242 ModeSpecifier specifier(os, MATH_MODE);
1244 InsetMathGrid::write(os);
1249 void InsetMathHull::normalize(NormalStream & os) const
1251 os << "[formula " << hullName(type_) << ' ';
1252 InsetMathGrid::normalize(os);
1257 void InsetMathHull::infoize(odocstream & os) const
1259 os << "Type: " << hullName(type_);
1263 void InsetMathHull::check() const
1265 LASSERT(numbered_.size() == nrows(), /**/);
1266 LASSERT(numbers_.size() == nrows(), /**/);
1267 LASSERT(label_.size() == nrows(), /**/);
1271 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1275 idocstringstream iss(func.argument());
1276 iss >> dlang >> extra;
1278 extra = from_ascii("noextra");
1279 string const lang = to_ascii(dlang);
1281 // FIXME: temporarily disabled
1282 //if (cur.selection()) {
1285 // lyxerr << "use selection: " << ar << endl;
1286 // insert(pipeThroughExtern(lang, extra, ar));
1290 // only inline, display or eqnarray math is allowed
1291 if (getType() > hullEqnArray) {
1292 frontend::Alert::warning(_("Bad math environment"),
1293 _("Computation cannot be performed for AMS "
1294 "math environments.\nChange the math "
1295 "formula type and try again."));
1300 eq.push_back(MathAtom(new InsetMathChar('=')));
1302 // go to first item in line
1303 cur.idx() -= cur.idx() % ncols();
1306 if (getType() == hullSimple) {
1307 size_type pos = cur.cell().find_last(eq);
1309 if (cur.inMathed() && cur.selection()) {
1310 asArray(grabAndEraseSelection(cur), ar);
1311 } else if (pos == cur.cell().size()) {
1313 lyxerr << "use whole cell: " << ar << endl;
1315 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1316 lyxerr << "use partial cell form pos: " << pos << endl;
1318 cur.cell().append(eq);
1319 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1320 cur.pos() = cur.lastpos();
1324 if (getType() == hullEquation) {
1325 lyxerr << "use equation inset" << endl;
1326 mutate(hullEqnArray);
1327 MathData & ar = cur.cell();
1328 lyxerr << "use cell: " << ar << endl;
1332 cur.cell() = pipeThroughExtern(lang, extra, ar);
1333 // move to end of line
1334 cur.pos() = cur.lastpos();
1339 lyxerr << "use eqnarray" << endl;
1340 cur.idx() += 2 - cur.idx() % ncols();
1342 MathData ar = cur.cell();
1343 lyxerr << "use cell: " << ar << endl;
1344 // FIXME: temporarily disabled
1350 cur.cell() = pipeThroughExtern(lang, extra, ar);
1351 cur.pos() = cur.lastpos();
1356 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1358 //lyxerr << "action: " << cmd.action() << endl;
1359 switch (cmd.action()) {
1361 case LFUN_FINISHED_BACKWARD:
1362 case LFUN_FINISHED_FORWARD:
1363 case LFUN_FINISHED_RIGHT:
1364 case LFUN_FINISHED_LEFT:
1365 //lyxerr << "action: " << cmd.action() << endl;
1366 InsetMathGrid::doDispatch(cur, cmd);
1370 case LFUN_BREAK_PARAGRAPH:
1371 // just swallow this
1374 case LFUN_NEWLINE_INSERT:
1375 // some magic for the common case
1376 if (type_ == hullSimple || type_ == hullEquation) {
1377 cur.recordUndoInset();
1379 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1380 mutate(align ? hullAlign : hullEqnArray);
1381 // mutate() may change labels and such.
1382 cur.forceBufferUpdate();
1383 cur.idx() = nrows() * ncols() - 1;
1384 cur.pos() = cur.lastpos();
1386 InsetMathGrid::doDispatch(cur, cmd);
1389 case LFUN_MATH_NUMBER_TOGGLE: {
1390 //lyxerr << "toggling all numbers" << endl;
1391 cur.recordUndoInset();
1392 bool old = numberedType();
1393 if (type_ == hullMultline)
1394 numbered(nrows() - 1, !old);
1396 for (row_type row = 0; row < nrows(); ++row)
1397 numbered(row, !old);
1399 cur.message(old ? _("No number") : _("Number"));
1400 cur.forceBufferUpdate();
1404 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1405 cur.recordUndoInset();
1406 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1407 bool old = numbered(r);
1408 cur.message(old ? _("No number") : _("Number"));
1410 cur.forceBufferUpdate();
1414 case LFUN_LABEL_INSERT: {
1415 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1416 docstring old_label = label(r);
1417 docstring const default_label = from_ascii("eq:");
1418 if (old_label.empty())
1419 old_label = default_label;
1421 InsetCommandParams p(LABEL_CODE);
1422 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1423 string const data = InsetCommand::params2string(p);
1425 if (cmd.argument().empty())
1426 cur.bv().showDialog("label", data);
1428 FuncRequest fr(LFUN_INSET_INSERT, data);
1434 case LFUN_LABEL_COPY_AS_REF: {
1436 if (cmd.argument().empty() && &cur.inset() == this)
1437 // if there is no argument and we're inside math, we retrieve
1438 // the row number from the cursor position.
1439 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1441 // if there is an argument, find the corresponding label, else
1442 // check whether there is at least one label.
1443 for (row = 0; row != nrows(); ++row)
1444 if (numbered_[row] && label_[row]
1445 && (cmd.argument().empty() || label(row) == cmd.argument()))
1452 InsetCommandParams p(REF_CODE, "ref");
1453 p["reference"] = label(row);
1454 cap::clearSelection();
1455 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1459 case LFUN_WORD_DELETE_FORWARD:
1460 case LFUN_CHAR_DELETE_FORWARD:
1461 if (col(cur.idx()) + 1 == ncols()
1462 && cur.pos() == cur.lastpos()
1463 && !cur.selection()) {
1464 if (!label(row(cur.idx())).empty()) {
1465 cur.recordUndoInset();
1466 label(row(cur.idx()), docstring());
1467 } else if (numbered(row(cur.idx()))) {
1468 cur.recordUndoInset();
1469 numbered(row(cur.idx()), false);
1470 cur.forceBufferUpdate();
1472 InsetMathGrid::doDispatch(cur, cmd);
1476 InsetMathGrid::doDispatch(cur, cmd);
1481 case LFUN_INSET_INSERT: {
1482 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1483 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1484 string const name = cmd.getArg(0);
1485 if (name == "label") {
1486 InsetCommandParams p(LABEL_CODE);
1487 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1488 docstring str = p["name"];
1489 cur.recordUndoInset();
1490 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1494 docstring old = label(r);
1497 // The label will take care of the reference update.
1501 // Newly created inset so initialize it.
1502 label_[r]->initView();
1505 cur.forceBufferUpdate();
1508 InsetMathGrid::doDispatch(cur, cmd);
1512 case LFUN_MATH_EXTERN:
1513 cur.recordUndoInset();
1517 case LFUN_MATH_MUTATE: {
1518 cur.recordUndoInset();
1519 row_type row = cur.row();
1520 col_type col = cur.col();
1521 mutate(hullType(cmd.argument()));
1522 cur.idx() = row * ncols() + col;
1523 if (cur.idx() > cur.lastidx()) {
1524 cur.idx() = cur.lastidx();
1525 cur.pos() = cur.lastpos();
1527 if (cur.pos() > cur.lastpos())
1528 cur.pos() = cur.lastpos();
1530 cur.forceBufferUpdate();
1531 // FIXME: find some more clever handling of the selection,
1532 // i.e. preserve it.
1533 cur.clearSelection();
1534 //cur.dispatched(FINISHED);
1538 case LFUN_MATH_DISPLAY: {
1539 cur.recordUndoInset();
1540 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1542 cur.pos() = cur.lastpos();
1543 //cur.dispatched(FINISHED);
1548 InsetMathGrid::doDispatch(cur, cmd);
1554 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1555 FuncStatus & status) const
1557 switch (cmd.action()) {
1558 case LFUN_FINISHED_BACKWARD:
1559 case LFUN_FINISHED_FORWARD:
1560 case LFUN_FINISHED_RIGHT:
1561 case LFUN_FINISHED_LEFT:
1564 case LFUN_NEWLINE_INSERT:
1565 case LFUN_MATH_EXTERN:
1567 status.setEnabled(true);
1570 // we never allow this in math, and we want to bind enter
1571 // to another actions in command-alternatives
1572 case LFUN_BREAK_PARAGRAPH:
1573 status.setEnabled(false);
1575 case LFUN_MATH_MUTATE: {
1576 HullType const ht = hullType(cmd.argument());
1577 status.setOnOff(type_ == ht);
1578 status.setEnabled(true);
1580 if (ht != hullSimple) {
1581 Cursor tmpcur = cur;
1582 while (!tmpcur.empty()) {
1583 InsetCode code = tmpcur.inset().lyxCode();
1584 if (code == BOX_CODE) {
1586 } else if (code == TABULAR_CODE) {
1587 FuncRequest tmpcmd(LFUN_MATH_DISPLAY);
1588 if (tmpcur.getStatus(tmpcmd, status) && !status.enabled())
1596 case LFUN_MATH_DISPLAY: {
1598 if (cur.depth() > 1) {
1599 Inset const & in = cur[cur.depth()-2].inset();
1600 if (in.lyxCode() == SCRIPT_CODE)
1601 enable = display() != Inline;
1603 status.setEnabled(enable);
1607 case LFUN_MATH_NUMBER_TOGGLE:
1608 // FIXME: what is the right test, this or the one of
1610 status.setEnabled(display() != Inline);
1611 status.setOnOff(numberedType());
1614 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1615 // FIXME: what is the right test, this or the one of
1617 bool const enable = (type_ == hullMultline)
1618 ? (nrows() - 1 == cur.row())
1619 : display() != Inline;
1620 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1621 status.setEnabled(enable);
1622 status.setOnOff(enable && numbered(r));
1626 case LFUN_LABEL_INSERT:
1627 status.setEnabled(type_ != hullSimple);
1630 case LFUN_LABEL_COPY_AS_REF: {
1631 bool enabled = false;
1633 if (cmd.argument().empty() && &cur.inset() == this) {
1634 // if there is no argument and we're inside math, we retrieve
1635 // the row number from the cursor position.
1636 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1637 enabled = numberedType() && label_[row] && numbered_[row];
1639 // if there is an argument, find the corresponding label, else
1640 // check whether there is at least one label.
1641 for (row_type row = 0; row != nrows(); ++row) {
1642 if (numbered_[row] && label_[row] &&
1643 (cmd.argument().empty() || label(row) == cmd.argument())) {
1649 status.setEnabled(enabled);
1653 case LFUN_INSET_INSERT:
1654 if (cmd.getArg(0) == "label") {
1655 status.setEnabled(type_ != hullSimple);
1658 return InsetMathGrid::getStatus(cur, cmd, status);
1660 case LFUN_INSET_MODIFY: {
1661 istringstream is(to_utf8(cmd.argument()));
1665 return InsetMathGrid::getStatus(cur, cmd, status);
1668 && (s == "append-row"
1669 || s == "delete-row"
1670 || s == "copy-row")) {
1671 status.message(bformat(
1672 from_utf8(N_("Can't change number of rows in '%1$s'")),
1674 status.setEnabled(false);
1678 && (s == "append-column"
1679 || s == "delete-column"
1680 || s == "copy-column")) {
1681 status.message(bformat(
1682 from_utf8(N_("Can't change number of columns in '%1$s'")),
1684 status.setEnabled(false);
1687 if ((type_ == hullSimple
1688 || type_ == hullEquation
1689 || type_ == hullNone) &&
1690 (s == "add-hline-above" || s == "add-hline-below")) {
1691 status.message(bformat(
1692 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1694 status.setEnabled(false);
1697 if (s == "add-vline-left" || s == "add-vline-right") {
1698 status.message(bformat(
1699 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1701 status.setEnabled(false);
1704 if (s == "valign-top" || s == "valign-middle"
1705 || s == "valign-bottom" || s == "align-left"
1706 || s == "align-center" || s == "align-right") {
1707 status.setEnabled(false);
1710 return InsetMathGrid::getStatus(cur, cmd, status);
1714 return InsetMathGrid::getStatus(cur, cmd, status);
1717 // This cannot really happen, but inserted to shut-up gcc
1718 return InsetMathGrid::getStatus(cur, cmd, status);
1722 /////////////////////////////////////////////////////////////////////
1726 // simply scrap this function if you want
1727 void InsetMathHull::mutateToText()
1730 // translate to latex
1732 latex(os, false, false);
1733 string str = os.str();
1736 Text * lt = view_->cursor().innerText();
1737 string::const_iterator cit = str.begin();
1738 string::const_iterator end = str.end();
1739 for (; cit != end; ++cit)
1740 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1743 //dispatch(LFUN_ESCAPE);
1748 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1749 docstring const & font)
1751 // this whole function is a hack and won't work for incremental font
1754 if (cur.inset().asInsetMath()->name() == font)
1755 cur.handleFont(to_utf8(font));
1757 cur.handleNest(createInsetMath(font, cur.buffer()));
1763 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1768 font.fromString(to_utf8(arg), b);
1769 if (font.fontInfo().color() != Color_inherit) {
1770 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1771 cur.handleNest(at, 0);
1776 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1779 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1780 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1781 enter_front ? idxFirst(cur) : idxLast(cur);
1782 // The inset formula dimension is not necessarily the same as the
1783 // one of the instant preview image, so we have to indicate to the
1784 // BufferView that a metrics update is needed.
1785 cur.screenUpdateFlags(Update::Force);
1789 void InsetMathHull::revealCodes(Cursor & cur) const
1791 if (!cur.inMathed())
1793 odocstringstream os;
1795 cur.message(os.str());
1797 // write something to the minibuffer
1798 // translate to latex
1802 string str = os.str();
1804 string::size_type pos = 0;
1806 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1809 else if (*it == '\0') {
1811 pos = it - str.begin();
1817 res = res.substr(pos - 30);
1818 if (res.size() > 60)
1819 res = res.substr(0, 60);
1825 /////////////////////////////////////////////////////////////////////
1829 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1832 // FIXME: completely broken
1833 static InsetMathHull * lastformula = 0;
1834 static CursorBase current = DocIterator(ibegin(nucleus()));
1836 static string laststr;
1838 if (lastformula != this || laststr != str) {
1839 //lyxerr << "reset lastformula to " << this << endl;
1842 current = ibegin(nucleus());
1844 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1848 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1850 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1851 CursorSlice & top = it.back();
1852 MathData const & a = top.asInsetMath()->cell(top.idx_);
1853 if (a.matchpart(ar, top.pos_)) {
1854 bv->cursor().setSelection(it, ar.size());
1856 top.pos_ += ar.size();
1862 //lyxerr << "not found!" << endl;
1869 void InsetMathHull::write(ostream & os) const
1871 odocstringstream oss;
1872 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1875 os << to_utf8(oss.str());
1879 void InsetMathHull::read(Lexer & lex)
1882 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1883 operator=(*at->asHullInset());
1887 bool InsetMathHull::readQuiet(Lexer & lex)
1890 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1892 operator=(*at->asHullInset());
1897 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1899 // disables ASCII-art for export of equations. See #2275.
1900 if (0 && display()) {
1904 TextPainter tpain(dim.width(), dim.height());
1905 drawT(tpain, 0, dim.ascent());
1907 // reset metrics cache to "real" values
1909 return tpain.textheight();
1911 odocstringstream oss;
1912 Encoding const * const enc = encodings.fromLyXName("utf8");
1913 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1915 if (type_ == hullRegexp)
1918 for (row_type r = 0; r < nrows(); ++r) {
1919 for (col_type c = 0; c < ncols(); ++c)
1920 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
1924 docstring const str = oss.str();
1931 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1936 if (getType() == hullSimple)
1937 name = from_ascii("inlineequation");
1939 name = from_ascii("informalequation");
1941 docstring bname = name;
1942 if (!label(0).empty())
1943 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1945 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1947 odocstringstream ls;
1948 if (runparams.flavor == OutputParams::XML) {
1949 ms << MTag("alt role='tex' ");
1950 // Workaround for db2latex: db2latex always includes equations with
1951 // \ensuremath{} or \begin{display}\end{display}
1952 // so we strip LyX' math environment
1953 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1954 InsetMathGrid::write(wi);
1955 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1960 InsetMathGrid::mathmlize(ms);
1965 otexstream ols(ls, texrow);
1966 ms << MTag("alt role='tex'");
1967 latex(ols, runparams);
1968 res = texrow.rows();
1969 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1973 ms << from_ascii("<graphic fileref=\"eqn/");
1974 if (!label(0).empty())
1975 ms << sgml::cleanID(buffer(), runparams, label(0));
1977 ms << sgml::uniqueID(from_ascii("anon"));
1979 if (runparams.flavor == OutputParams::XML)
1980 ms << from_ascii("\"/>");
1982 ms << from_ascii("\">");
1984 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1986 return ms.line() + res;
1990 bool InsetMathHull::haveNumbers() const
1992 bool havenumbers = false;
1993 // inline formulas are never numbered (bug 7351 part 3)
1994 if (getType() == hullSimple)
1996 for (size_t i = 0; i != numbered_.size(); ++i) {
2007 // We need to do something about alignment here.
2009 // This duplicates code from InsetMathGrid, but
2010 // we need access here to number information,
2011 // and we simply do not have that in InsetMathGrid.
2012 void InsetMathHull::htmlize(HtmlStream & os) const
2014 bool const havenumbers = haveNumbers();
2015 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2018 os << cell(index(0, 0));
2022 os << MTag("table", "class='mathtable'");
2023 for (row_type row = 0; row < nrows(); ++row) {
2025 for (col_type col = 0; col < ncols(); ++col) {
2027 os << cell(index(row, col));
2032 docstring const & num = numbers_[row];
2034 os << '(' << num << ')';
2039 os << ETag("table");
2043 // this duplicates code from InsetMathGrid, but
2044 // we need access here to number information,
2045 // and we simply do not have that in InsetMathGrid.
2046 void InsetMathHull::mathmlize(MathStream & os) const
2048 bool const havenumbers = haveNumbers();
2049 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2052 os << MTag("mtable");
2053 char const * const celltag = havetable ? "mtd" : "mrow";
2054 // FIXME There does not seem to be wide support at the moment
2055 // for mlabeledtr, so we have to use just mtr for now.
2056 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2057 char const * const rowtag = "mtr";
2058 for (row_type row = 0; row < nrows(); ++row) {
2061 for (col_type col = 0; col < ncols(); ++col) {
2063 << cell(index(row, col))
2069 docstring const & num = numbers_[row];
2071 os << '(' << num << ')';
2078 os << ETag("mtable");
2082 void InsetMathHull::mathAsLatex(WriteStream & os) const
2084 MathEnsurer ensurer(os, false);
2085 bool havenumbers = haveNumbers();
2086 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2089 os << cell(index(0, 0));
2093 os << "<table class='mathtable'>";
2094 for (row_type row = 0; row < nrows(); ++row) {
2096 for (col_type col = 0; col < ncols(); ++col) {
2097 os << "<td class='math'>";
2098 os << cell(index(row, col));
2103 docstring const & num = numbers_[row];
2105 os << '(' << num << ')';
2114 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2116 BufferParams::MathOutput const mathtype =
2117 buffer().params().html_math_output;
2119 bool success = false;
2121 // we output all the labels just at the beginning of the equation.
2122 // this should be fine.
2123 for (size_t i = 0; i != label_.size(); ++i) {
2124 InsetLabel const * const il = label_[i];
2130 // FIXME Eventually we would like to do this inset by inset.
2131 if (mathtype == BufferParams::MathML) {
2132 odocstringstream os;
2137 } catch (MathExportException const &) {}
2139 if (getType() == hullSimple)
2140 xs << html::StartTag("math",
2141 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2143 xs << html::StartTag("math",
2144 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2145 xs << XHTMLStream::ESCAPE_NONE
2147 << html::EndTag("math");
2149 } else if (mathtype == BufferParams::HTML) {
2150 odocstringstream os;
2155 } catch (MathExportException const &) {}
2157 string const tag = (getType() == hullSimple) ? "span" : "div";
2158 xs << html::StartTag(tag, "class='formula'", true)
2159 << XHTMLStream::ESCAPE_NONE
2161 << html::EndTag(tag);
2165 // what we actually want is this:
2167 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2169 // || mathtype == BufferParams::Images
2171 // but what follows is equivalent, since we'll enter only if either (a) we
2172 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2173 // aren't doing LaTeX, in which case we are doing Images.
2174 if (!success && mathtype != BufferParams::LaTeX) {
2175 graphics::PreviewImage const * pimage = 0;
2177 loadPreview(docit_);
2178 pimage = preview_->getPreviewImage(buffer());
2179 // FIXME Do we always have png?
2182 if (pimage || op.dryrun) {
2183 string const filename = pimage ? pimage->filename().onlyFileName()
2184 : "previewimage.png";
2186 // if we are not in the master buffer, then we need to see that the
2187 // generated image is copied there; otherwise, preview fails.
2188 Buffer const * mbuf = buffer().masterBuffer();
2189 if (mbuf != &buffer()) {
2190 string mbtmp = mbuf->temppath();
2191 FileName const mbufimg(support::addName(mbtmp, filename));
2192 pimage->filename().copyTo(mbufimg);
2194 // add the file to the list of files to be exported
2195 op.exportdata->addExternalFile("xhtml", pimage->filename());
2198 string const tag = (getType() == hullSimple) ? "span" : "div";
2200 << html::StartTag(tag)
2201 << html::CompTag("img", "src=\"" + filename + "\"")
2202 << html::EndTag(tag)
2208 // so we'll pass this test if we've failed everything else, or
2209 // if mathtype was LaTeX, since we won't have entered any of the
2211 if (!success /* || mathtype != BufferParams::LaTeX */) {
2212 // Unfortunately, we cannot use latexString() because we do not want
2213 // $...$ or whatever.
2214 odocstringstream ls;
2215 WriteStream wi(ls, false, true, WriteStream::wsPreview);
2216 ModeSpecifier specifier(wi, MATH_MODE);
2218 docstring const latex = ls.str();
2220 // class='math' allows for use of jsMath
2221 // http://www.math.union.edu/~dpvc/jsMath/
2223 // probably should allow for some kind of customization here
2224 string const tag = (getType() == hullSimple) ? "span" : "div";
2225 xs << html::StartTag(tag, "class='math'")
2227 << html::EndTag(tag)
2234 void InsetMathHull::toString(odocstream & os) const
2236 plaintext(os, OutputParams(0));
2240 void InsetMathHull::forToc(docstring & os, size_t) const
2242 odocstringstream ods;
2243 plaintext(ods, OutputParams(0));
2248 docstring InsetMathHull::contextMenuName() const
2250 return from_ascii("context-math");
2254 void InsetMathHull::recordLocation(DocIterator const & di)