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);
228 // FIXME This should really be controlled by the TOC level, or
229 // something of the sort.
231 const char * counters_to_save[] = {"section", "chapter"};
232 unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
236 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
239 //FIXME: buffer_ should be set at creation for this inset! Problem is
240 // This inset is created at too many places (see Parser::parse1() in
245 // if any of the equations are numbered, then we want to save the values
246 // of some of the counters.
248 BufferParams const & bp = buffer_->params();
249 string const & lang = it->getParLanguage(bp)->code();
251 buffer_->masterBuffer()->params().documentClass().counters();
253 // right now, we only need to do this at export time
254 if (utype == OutputUpdate) {
255 for (size_t i = 0; i < numcnts; ++i) {
256 docstring const cnt = from_ascii(counters_to_save[i]);
257 if (cnts.hasCounter(cnt))
258 counter_map[cnt] = cnts.value(cnt);
262 // this has to be done separately
263 docstring const eqstr = from_ascii("equation");
264 if (cnts.hasCounter(eqstr)) {
265 if (utype == OutputUpdate)
266 counter_map[eqstr] = cnts.value(eqstr);
267 for (size_t i = 0; i != label_.size(); ++i) {
269 cnts.step(eqstr, utype);
270 numbers_[i] = cnts.theCounter(eqstr, lang);
272 numbers_[i] = empty_docstring();
278 for (size_t i = 0; i != label_.size(); ++i) {
280 label_[i]->updateBuffer(it, utype);
283 InsetMathGrid::updateBuffer(it, utype);
287 void InsetMathHull::addToToc(DocIterator const & pit) const
290 //FIXME: buffer_ should be set at creation for this inset! Problem is
291 // This inset is created at too many places (see Parser::parse1() in
296 Toc & toc = buffer().tocBackend().toc("equation");
298 for (row_type row = 0; row != nrows(); ++row) {
302 label_[row]->addToToc(pit);
303 toc.push_back(TocItem(pit, 0, nicelabel(row)));
308 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
314 return InsetMathNest::editXY(cur, x, y);
318 InsetMath::mode_type InsetMathHull::currentMode() const
320 if (type_ == hullNone)
321 return UNDECIDED_MODE;
322 // definitely math mode ...
327 bool InsetMathHull::idxFirst(Cursor & cur) const
335 bool InsetMathHull::idxLast(Cursor & cur) const
337 cur.idx() = nargs() - 1;
338 cur.pos() = cur.lastpos();
343 char InsetMathHull::defaultColAlign(col_type col)
345 if (type_ == hullEqnArray)
347 if (type_ == hullMultline)
349 if (type_ == hullGather)
351 if (type_ >= hullAlign)
352 return "rl"[col & 1];
357 char InsetMathHull::displayColAlign(col_type col, row_type row) const
359 if (type_ == hullMultline) {
362 if (row == nrows() - 1)
365 return InsetMathGrid::displayColAlign(col, row);
369 int InsetMathHull::defaultColSpace(col_type col)
371 if (type_ == hullAlign || type_ == hullAlignAt)
373 if (type_ == hullXAlignAt)
374 return (col & 1) ? 20 : 0;
375 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
376 return (col & 1) ? 40 : 0;
381 docstring InsetMathHull::standardFont() const
386 font_name = from_ascii("texttt");
389 font_name = from_ascii("lyxnochange");
392 font_name = from_ascii("mathnormal");
398 ColorCode InsetMathHull::standardColor() const
404 color = Color_foreground;
413 bool InsetMathHull::previewState(BufferView * bv) const
415 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
416 graphics::PreviewImage const * pimage =
417 preview_->getPreviewImage(bv->buffer());
418 return pimage && pimage->image();
424 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
426 if (previewState(mi.base.bv)) {
427 preview_->metrics(mi, dim);
428 // insert a one pixel gap in front of the formula
431 dim.des += displayMargin();
432 // Cache the inset dimension.
433 setDimCache(mi, dim);
437 FontSetChanger dummy1(mi.base, standardFont());
438 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
440 // let the cells adjust themselves
441 InsetMathGrid::metrics(mi, dim);
444 dim.asc += displayMargin();
445 dim.des += displayMargin();
448 if (numberedType()) {
449 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
451 for (row_type row = 0; row < nrows(); ++row)
452 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
458 if (type_ == hullRegexp)
460 // make it at least as high as the current font
463 math_font_max_dim(mi.base.font, asc, des);
464 dim.asc = max(dim.asc, asc);
465 dim.des = max(dim.des, des);
466 // Cache the inset dimension.
467 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
468 setDimCache(mi, dim);
472 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
474 if (previewState(pi.base.bv))
475 return graphics::PreviewLoader::backgroundColor();
480 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
482 Dimension const dim = dimension(*pi.base.bv);
483 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
484 dim.asc + dim.des - 1, pi.backgroundColor(this));
488 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
490 use_preview_ = previewState(pi.base.bv);
492 if (type_ == hullRegexp) {
493 Dimension const dim = dimension(*pi.base.bv);
494 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
495 dim.width() - 2, dim.height() - 2, Color_regexpframe);
498 // one pixel gap in front
499 preview_->draw(pi, x + 1, y);
500 setPosCache(pi, x, y);
504 ColorCode color = pi.selected && lyxrc.use_system_colors
505 ? Color_selectiontext : standardColor();
506 bool const really_change_color = pi.base.font.color() == Color_none;
507 ColorChanger dummy0(pi.base.font, color, really_change_color);
508 FontSetChanger dummy1(pi.base, standardFont());
509 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
511 InsetMathGrid::draw(pi, x + 1, y);
513 if (numberedType()) {
514 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
515 for (row_type row = 0; row < nrows(); ++row) {
516 int const yy = y + rowinfo_[row].offset_;
517 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
518 docstring const nl = nicelabel(row);
522 setPosCache(pi, x, y);
526 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
529 InsetMathGrid::metricsT(mi, dim);
532 WriteStream wi(os, false, true, WriteStream::wsDefault);
534 dim.wid = os.str().size();
541 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
544 InsetMathGrid::drawT(pain, x, y);
547 WriteStream wi(os, false, true, WriteStream::wsDefault);
549 pain.draw(x, y, os.str().c_str());
554 static docstring latexString(InsetMathHull const & inset)
557 // This has to be static, because a preview snippet or a math
558 // macro containing math in text mode (such as $\text{$\phi$}$ or
559 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
560 // first time as a whole, and the second time only the inner math.
561 // In this last case inset.buffer() would be invalid.
562 static Encoding const * encoding = 0;
563 if (inset.isBufferValid())
564 encoding = &(inset.buffer().params().encoding());
565 WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
571 void InsetMathHull::initUnicodeMath() const
573 // Trigger classification of the unicode symbols in this inset
574 docstring const dummy = latexString(*this);
578 void InsetMathHull::addPreview(DocIterator const & inset_pos,
579 graphics::PreviewLoader & /*ploader*/) const
581 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
582 preparePreview(inset_pos);
587 void InsetMathHull::preparePreview(DocIterator const & pos,
588 bool forexport) const
590 // there is no need to do all the macro stuff if we're not
591 // actually going to generate the preview.
592 if (RenderPreview::status() != LyXRC::PREVIEW_ON && !forexport)
595 Buffer const * buffer = pos.buffer();
597 // collect macros at this position
599 buffer->listMacroNames(macros);
600 MacroNameSet::iterator it = macros.begin();
601 MacroNameSet::iterator end = macros.end();
602 odocstringstream macro_preamble;
603 for (; it != end; ++it) {
604 MacroData const * data = buffer->getMacro(*it, pos, true);
606 data->write(macro_preamble, true);
607 macro_preamble << endl;
612 if (forexport && haveNumbers()) {
613 docstring eqstr = from_ascii("equation");
614 CounterMap::const_iterator it = counter_map.find(eqstr);
615 if (it != counter_map.end()) {
616 int num = it->second;
618 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
619 '{' + convert<docstring>(num) + '}' + '\n';
621 for (size_t i = 0; i != numcnts; ++i) {
622 docstring cnt = from_ascii(counters_to_save[i]);
623 it = counter_map.find(cnt);
624 if (it == counter_map.end())
626 int num = it->second;
628 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
629 '{' + convert<docstring>(num) + '}';
632 docstring const snippet = macro_preamble.str() +
633 setcnt + latexString(*this);
634 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
635 preview_->addPreview(snippet, *buffer, forexport);
639 void InsetMathHull::reloadPreview(DocIterator const & pos) const
642 preview_->startLoading(*pos.buffer());
646 void InsetMathHull::loadPreview(DocIterator const & pos) const
648 bool const forexport = true;
649 preparePreview(pos, forexport);
650 preview_->startLoading(*pos.buffer(), forexport);
654 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
656 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
658 cur.screenUpdateFlags(Update::Force);
664 docstring InsetMathHull::label(row_type row) const
666 LASSERT(row < nrows(), /**/);
667 if (InsetLabel * il = label_[row])
668 return il->screenLabel();
673 void InsetMathHull::label(row_type row, docstring const & label)
675 //lyxerr << "setting label '" << label << "' for row " << row << endl;
679 label_[row] = dummy_pointer;
682 label_[row]->updateLabelAndRefs(label);
684 label_[row]->setParam("name", label);
688 InsetCommandParams p(LABEL_CODE);
690 label_[row] = new InsetLabel(buffer_, p);
692 label_[row]->setBuffer(buffer());
696 void InsetMathHull::numbered(row_type row, bool num)
698 numbered_[row] = num;
699 if (!numbered_[row] && label_[row]) {
706 bool InsetMathHull::numbered(row_type row) const
708 return numbered_[row];
712 bool InsetMathHull::ams() const
714 return type_ == hullAlign
715 || type_ == hullFlAlign
716 || type_ == hullMultline
717 || type_ == hullGather
718 || type_ == hullAlignAt
719 || type_ == hullXAlignAt
720 || type_ == hullXXAlignAt;
724 Inset::DisplayType InsetMathHull::display() const
726 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
731 bool InsetMathHull::numberedType() const
733 if (type_ == hullNone)
735 if (type_ == hullSimple)
737 if (type_ == hullXXAlignAt)
739 if (type_ == hullRegexp)
741 for (row_type row = 0; row < nrows(); ++row)
748 void InsetMathHull::validate(LaTeXFeatures & features) const
750 if (features.runparams().isLaTeX()) {
752 features.require("amsmath");
754 if (type_ == hullRegexp) {
755 features.require("color");
756 string frcol = lcolor.getLaTeXName(Color_regexpframe);
757 string bgcol = "white";
758 features.addPreambleSnippet(
759 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
760 + frcol + string("}{")
761 + bgcol + string("}{\\ensuremath{\\mathtt{#1}}}}"));
762 features.addPreambleSnippet(
763 string("\\newcommand{\\endregexp}{}"));
766 // Validation is necessary only if not using AMS math.
767 // To be safe, we will always run mathedvalidate.
768 //if (features.amsstyle)
771 //features.binom = true;
772 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
773 // it would be better to do this elsewhere, but we can't validate in
774 // InsetMathMatrix and we have no way, outside MathExtern, to know if
775 // we even have any matrices.
776 features.addCSSSnippet(
777 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
778 "table.matrix td{padding: 0.25px;}\n"
779 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
780 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
782 InsetMathGrid::validate(features);
786 void InsetMathHull::header_write(WriteStream & os) const
788 bool n = numberedType();
802 os << "\n\\begin{equation" << star(n) << "}\n";
812 os << "\n\\begin{" << hullName(type_) << star(n) << "}\n";
817 os << "\n\\begin{" << hullName(type_) << star(n) << '}'
818 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
822 os << "\n\\begin{" << hullName(type_) << '}'
823 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
831 os << "\n\\begin{unknown" << star(n) << "}\n";
837 void InsetMathHull::footer_write(WriteStream & os) const
839 bool n = numberedType();
852 os << "\n\\end{equation" << star(n) << "}\n";
864 os << "\n\\end{" << hullName(type_) << star(n) << "}\n";
868 os << "\n\\end{" << hullName(type_) << "}\n";
872 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
873 os << "\\endregexp{}}";
877 os << "\n\\end{unknown" << star(n) << "}\n";
883 bool InsetMathHull::rowChangeOK() const
886 type_ == hullEqnArray || type_ == hullAlign ||
887 type_ == hullFlAlign || type_ == hullAlignAt ||
888 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
889 type_ == hullGather || type_ == hullMultline;
893 bool InsetMathHull::colChangeOK() const
896 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
897 type_ == hullXAlignAt || type_ == hullXXAlignAt;
901 void InsetMathHull::addRow(row_type row)
906 bool numbered = numberedType();
907 // Move the number and raw pointer, do not call label() (bug 7511)
908 InsetLabel * label = dummy_pointer;
909 docstring number = empty_docstring();
910 if (type_ == hullMultline) {
911 if (row + 1 == nrows()) {
912 numbered_[row] = false;
913 swap(label, label_[row]);
914 swap(number, numbers_[row]);
919 numbered_.insert(numbered_.begin() + row + 1, numbered);
920 numbers_.insert(numbers_.begin() + row + 1, number);
921 label_.insert(label_.begin() + row + 1, label);
922 InsetMathGrid::addRow(row);
926 void InsetMathHull::swapRow(row_type row)
930 if (row + 1 == nrows())
932 // gcc implements the standard std::vector<bool> which is *not* a container:
933 // http://www.gotw.ca/publications/N1185.pdf
934 // As a results, it doesn't like this:
935 // swap(numbered_[row], numbered_[row + 1]);
936 // so we do it manually:
937 bool const b = numbered_[row];
938 numbered_[row] = numbered_[row + 1];
939 numbered_[row + 1] = b;
940 swap(numbers_[row], numbers_[row + 1]);
941 swap(label_[row], label_[row + 1]);
942 InsetMathGrid::swapRow(row);
946 void InsetMathHull::delRow(row_type row)
948 if (nrows() <= 1 || !rowChangeOK())
950 if (row + 1 == nrows() && type_ == hullMultline) {
951 bool const b = numbered_[row - 1];
952 numbered_[row - 1] = numbered_[row];
954 swap(numbers_[row - 1], numbers_[row]);
955 swap(label_[row - 1], label_[row]);
956 InsetMathGrid::delRow(row);
959 InsetMathGrid::delRow(row);
960 // The last dummy row has no number info nor a label.
961 // Test nrows() + 1 because we have already erased the row.
962 if (row == nrows() + 1)
964 numbered_.erase(numbered_.begin() + row);
965 numbers_.erase(numbers_.begin() + row);
967 label_.erase(label_.begin() + row);
971 void InsetMathHull::addCol(col_type col)
975 InsetMathGrid::addCol(col);
979 void InsetMathHull::delCol(col_type col)
981 if (ncols() <= 1 || !colChangeOK())
983 InsetMathGrid::delCol(col);
987 docstring InsetMathHull::nicelabel(row_type row) const
991 docstring const & val = numbers_[row];
993 return '(' + val + ')';
994 return '(' + val + ',' + label_[row]->screenLabel() + ')';
998 void InsetMathHull::glueall(HullType type)
1001 for (idx_type i = 0; i < nargs(); ++i)
1003 InsetLabel * label = 0;
1004 if (type == hullEquation) {
1005 // preserve first non-empty label
1006 for (row_type row = 0; row < nrows(); ++row) {
1008 label = label_[row];
1014 *this = InsetMathHull(buffer_, hullSimple);
1021 void InsetMathHull::splitTo2Cols()
1023 LASSERT(ncols() == 1, /**/);
1024 InsetMathGrid::addCol(1);
1025 for (row_type row = 0; row < nrows(); ++row) {
1026 idx_type const i = 2 * row;
1027 pos_type pos = firstRelOp(cell(i));
1028 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1029 cell(i).erase(pos, cell(i).size());
1034 void InsetMathHull::splitTo3Cols()
1036 LASSERT(ncols() < 3, /**/);
1039 InsetMathGrid::addCol(2);
1040 for (row_type row = 0; row < nrows(); ++row) {
1041 idx_type const i = 3 * row + 1;
1042 if (!cell(i).empty()) {
1043 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1044 cell(i).erase(1, cell(i).size());
1050 void InsetMathHull::changeCols(col_type cols)
1052 if (ncols() == cols)
1054 else if (ncols() < cols) {
1060 while (ncols() < cols)
1061 InsetMathGrid::addCol(ncols());
1067 for (row_type row = 0; row < nrows(); ++row) {
1068 idx_type const i = row * ncols();
1069 for (col_type col = cols; col < ncols(); ++col) {
1070 cell(i + cols - 1).append(cell(i + col));
1074 while (ncols() > cols) {
1075 InsetMathGrid::delCol(ncols() - 1);
1080 HullType InsetMathHull::getType() const
1086 void InsetMathHull::setType(HullType type)
1093 void InsetMathHull::mutate(HullType newtype)
1095 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1097 // we try to move along the chain
1098 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1100 // +-------------------------------------+
1101 // we use eqnarray as intermediate type for mutations that are not
1102 // directly supported because it handles labels and numbering for
1105 if (newtype == type_) {
1109 else if (newtype < hullNone) {
1114 else if (type_ == hullNone) {
1115 setType(hullSimple);
1120 else if (type_ == hullSimple) {
1121 if (newtype == hullNone) {
1125 setType(hullEquation);
1126 numbered(0, label_[0] ? true : false);
1131 else if (type_ == hullEquation) {
1132 if (newtype < type_) {
1133 setType(hullSimple);
1136 } else if (newtype == hullEqnArray) {
1137 // split it "nicely" on the first relop
1139 setType(hullEqnArray);
1140 } else if (newtype == hullMultline || newtype == hullGather) {
1143 // split it "nicely"
1150 else if (type_ == hullEqnArray) {
1151 if (newtype < type_) {
1154 } else { // align & Co.
1161 else if (type_ == hullAlign || type_ == hullAlignAt ||
1162 type_ == hullXAlignAt || type_ == hullFlAlign) {
1163 if (newtype < hullAlign) {
1165 setType(hullEqnArray);
1167 } else if (newtype == hullGather || newtype == hullMultline) {
1170 } else if (newtype == hullXXAlignAt) {
1171 for (row_type row = 0; row < nrows(); ++row)
1172 numbered(row, false);
1179 else if (type_ == hullXXAlignAt) {
1180 for (row_type row = 0; row < nrows(); ++row)
1181 numbered(row, false);
1182 if (newtype < hullAlign) {
1184 setType(hullEqnArray);
1186 } else if (newtype == hullGather || newtype == hullMultline) {
1194 else if (type_ == hullMultline || type_ == hullGather) {
1195 if (newtype == hullGather || newtype == hullMultline)
1197 else if (newtype == hullAlign || newtype == hullFlAlign ||
1198 newtype == hullAlignAt || newtype == hullXAlignAt) {
1201 } else if (newtype == hullXXAlignAt) {
1203 for (row_type row = 0; row < nrows(); ++row)
1204 numbered(row, false);
1208 setType(hullEqnArray);
1214 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1215 << "' to '" << to_utf8(hullName(newtype))
1216 << "' not implemented" << endl;
1221 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1222 bool last_eoln) const
1225 if (numberedType()) {
1226 if (label_[row] && numbered_[row]) {
1227 docstring const name =
1228 latex ? escape(label_[row]->getParam("name"))
1229 : label_[row]->getParam("name");
1230 res += "\\label{" + name + '}';
1232 if (!numbered_[row] && (type_ != hullMultline))
1233 res += "\\nonumber ";
1235 // Never add \\ on the last empty line of eqnarray and friends
1237 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1241 void InsetMathHull::write(WriteStream & os) const
1243 ModeSpecifier specifier(os, MATH_MODE);
1245 InsetMathGrid::write(os);
1250 void InsetMathHull::normalize(NormalStream & os) const
1252 os << "[formula " << hullName(type_) << ' ';
1253 InsetMathGrid::normalize(os);
1258 void InsetMathHull::infoize(odocstream & os) const
1260 os << "Type: " << hullName(type_);
1264 void InsetMathHull::check() const
1266 LASSERT(numbered_.size() == nrows(), /**/);
1267 LASSERT(numbers_.size() == nrows(), /**/);
1268 LASSERT(label_.size() == nrows(), /**/);
1272 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1276 idocstringstream iss(func.argument());
1277 iss >> dlang >> extra;
1279 extra = from_ascii("noextra");
1280 string const lang = to_ascii(dlang);
1282 // FIXME: temporarily disabled
1283 //if (cur.selection()) {
1286 // lyxerr << "use selection: " << ar << endl;
1287 // insert(pipeThroughExtern(lang, extra, ar));
1291 // only inline, display or eqnarray math is allowed
1292 if (getType() > hullEqnArray) {
1293 frontend::Alert::warning(_("Bad math environment"),
1294 _("Computation cannot be performed for AMS "
1295 "math environments.\nChange the math "
1296 "formula type and try again."));
1301 eq.push_back(MathAtom(new InsetMathChar('=')));
1303 // go to first item in line
1304 cur.idx() -= cur.idx() % ncols();
1307 if (getType() == hullSimple) {
1308 size_type pos = cur.cell().find_last(eq);
1310 if (cur.inMathed() && cur.selection()) {
1311 asArray(grabAndEraseSelection(cur), ar);
1312 } else if (!pos == cur.cell().empty()) {
1314 lyxerr << "use whole cell: " << ar << endl;
1316 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1317 lyxerr << "use partial cell form pos: " << pos << endl;
1319 cur.cell().append(eq);
1320 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1321 cur.pos() = cur.lastpos();
1325 if (getType() == hullEquation) {
1326 lyxerr << "use equation inset" << endl;
1327 mutate(hullEqnArray);
1328 MathData & ar = cur.cell();
1329 lyxerr << "use cell: " << ar << endl;
1333 cur.cell() = pipeThroughExtern(lang, extra, ar);
1334 // move to end of line
1335 cur.pos() = cur.lastpos();
1340 lyxerr << "use eqnarray" << endl;
1341 cur.idx() += 2 - cur.idx() % ncols();
1343 MathData ar = cur.cell();
1344 lyxerr << "use cell: " << ar << endl;
1345 // FIXME: temporarily disabled
1351 cur.cell() = pipeThroughExtern(lang, extra, ar);
1352 cur.pos() = cur.lastpos();
1357 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1359 //lyxerr << "action: " << cmd.action() << endl;
1360 switch (cmd.action()) {
1362 case LFUN_FINISHED_BACKWARD:
1363 case LFUN_FINISHED_FORWARD:
1364 case LFUN_FINISHED_RIGHT:
1365 case LFUN_FINISHED_LEFT:
1366 //lyxerr << "action: " << cmd.action() << endl;
1367 InsetMathGrid::doDispatch(cur, cmd);
1371 case LFUN_PARAGRAPH_BREAK:
1372 // just swallow this
1375 case LFUN_NEWLINE_INSERT:
1376 // some magic for the common case
1377 if (type_ == hullSimple || type_ == hullEquation) {
1378 cur.recordUndoInset();
1380 cur.bv().buffer().params().use_package("amsmath") == BufferParams::package_on;
1381 mutate(align ? hullAlign : hullEqnArray);
1382 // mutate() may change labels and such.
1383 cur.forceBufferUpdate();
1384 cur.idx() = nrows() * ncols() - 1;
1385 cur.pos() = cur.lastpos();
1387 InsetMathGrid::doDispatch(cur, cmd);
1390 case LFUN_MATH_NUMBER_TOGGLE: {
1391 //lyxerr << "toggling all numbers" << endl;
1392 cur.recordUndoInset();
1393 bool old = numberedType();
1394 if (type_ == hullMultline)
1395 numbered(nrows() - 1, !old);
1397 for (row_type row = 0; row < nrows(); ++row)
1398 numbered(row, !old);
1400 cur.message(old ? _("No number") : _("Number"));
1401 cur.forceBufferUpdate();
1405 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1406 cur.recordUndoInset();
1407 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1408 bool old = numbered(r);
1409 cur.message(old ? _("No number") : _("Number"));
1411 cur.forceBufferUpdate();
1415 case LFUN_LABEL_INSERT: {
1416 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1417 docstring old_label = label(r);
1418 docstring const default_label = from_ascii("eq:");
1419 if (old_label.empty())
1420 old_label = default_label;
1422 InsetCommandParams p(LABEL_CODE);
1423 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1424 string const data = InsetCommand::params2string(p);
1426 if (cmd.argument().empty())
1427 cur.bv().showDialog("label", data);
1429 FuncRequest fr(LFUN_INSET_INSERT, data);
1435 case LFUN_LABEL_COPY_AS_REF: {
1437 if (cmd.argument().empty() && &cur.inset() == this)
1438 // if there is no argument and we're inside math, we retrieve
1439 // the row number from the cursor position.
1440 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1442 // if there is an argument, find the corresponding label, else
1443 // check whether there is at least one label.
1444 for (row = 0; row != nrows(); ++row)
1445 if (numbered_[row] && label_[row]
1446 && (cmd.argument().empty() || label(row) == cmd.argument()))
1453 InsetCommandParams p(REF_CODE, "ref");
1454 p["reference"] = label(row);
1455 cap::clearSelection();
1456 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1460 case LFUN_WORD_DELETE_FORWARD:
1461 case LFUN_CHAR_DELETE_FORWARD:
1462 if (col(cur.idx()) + 1 == ncols()
1463 && cur.pos() == cur.lastpos()
1464 && !cur.selection()) {
1465 if (!label(row(cur.idx())).empty()) {
1466 cur.recordUndoInset();
1467 label(row(cur.idx()), docstring());
1468 } else if (numbered(row(cur.idx()))) {
1469 cur.recordUndoInset();
1470 numbered(row(cur.idx()), false);
1471 cur.forceBufferUpdate();
1473 InsetMathGrid::doDispatch(cur, cmd);
1477 InsetMathGrid::doDispatch(cur, cmd);
1482 case LFUN_INSET_INSERT: {
1483 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1484 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1485 string const name = cmd.getArg(0);
1486 if (name == "label") {
1487 InsetCommandParams p(LABEL_CODE);
1488 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1489 docstring str = p["name"];
1490 cur.recordUndoInset();
1491 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1495 docstring old = label(r);
1498 // The label will take care of the reference update.
1502 // Newly created inset so initialize it.
1503 label_[r]->initView();
1506 cur.forceBufferUpdate();
1509 InsetMathGrid::doDispatch(cur, cmd);
1513 case LFUN_MATH_EXTERN:
1514 cur.recordUndoInset();
1518 case LFUN_MATH_MUTATE: {
1519 cur.recordUndoInset();
1520 row_type row = cur.row();
1521 col_type col = cur.col();
1522 mutate(hullType(cmd.argument()));
1523 cur.idx() = row * ncols() + col;
1524 if (cur.idx() > cur.lastidx()) {
1525 cur.idx() = cur.lastidx();
1526 cur.pos() = cur.lastpos();
1528 if (cur.pos() > cur.lastpos())
1529 cur.pos() = cur.lastpos();
1531 cur.forceBufferUpdate();
1532 // FIXME: find some more clever handling of the selection,
1533 // i.e. preserve it.
1534 cur.clearSelection();
1535 //cur.dispatched(FINISHED);
1539 case LFUN_MATH_DISPLAY: {
1540 cur.recordUndoInset();
1541 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1543 cur.pos() = cur.lastpos();
1544 //cur.dispatched(FINISHED);
1549 InsetMathGrid::doDispatch(cur, cmd);
1555 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1556 FuncStatus & status) const
1558 switch (cmd.action()) {
1559 case LFUN_FINISHED_BACKWARD:
1560 case LFUN_FINISHED_FORWARD:
1561 case LFUN_FINISHED_RIGHT:
1562 case LFUN_FINISHED_LEFT:
1565 case LFUN_NEWLINE_INSERT:
1566 case LFUN_MATH_EXTERN:
1568 status.setEnabled(true);
1571 // we never allow this in math, and we want to bind enter
1572 // to another actions in command-alternatives
1573 case LFUN_PARAGRAPH_BREAK:
1574 status.setEnabled(false);
1576 case LFUN_MATH_MUTATE: {
1577 HullType const ht = hullType(cmd.argument());
1578 status.setOnOff(type_ == ht);
1579 status.setEnabled(true);
1581 if (ht != hullSimple) {
1582 Cursor tmpcur = cur;
1583 while (!tmpcur.empty()) {
1584 InsetCode code = tmpcur.inset().lyxCode();
1585 if (code == BOX_CODE) {
1587 } else if (code == TABULAR_CODE) {
1588 FuncRequest tmpcmd(LFUN_MATH_DISPLAY);
1589 if (tmpcur.getStatus(tmpcmd, status) && !status.enabled())
1597 case LFUN_MATH_DISPLAY: {
1599 if (cur.depth() > 1) {
1600 Inset const & in = cur[cur.depth()-2].inset();
1601 if (in.lyxCode() == SCRIPT_CODE)
1602 enable = display() != Inline;
1604 status.setEnabled(enable);
1608 case LFUN_MATH_NUMBER_TOGGLE:
1609 // FIXME: what is the right test, this or the one of
1611 status.setEnabled(display() != Inline);
1612 status.setOnOff(numberedType());
1615 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1616 // FIXME: what is the right test, this or the one of
1618 bool const enable = (type_ == hullMultline)
1619 ? (nrows() - 1 == cur.row())
1620 : display() != Inline;
1621 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1622 status.setEnabled(enable);
1623 status.setOnOff(enable && numbered(r));
1627 case LFUN_LABEL_INSERT:
1628 status.setEnabled(type_ != hullSimple);
1631 case LFUN_LABEL_COPY_AS_REF: {
1632 bool enabled = false;
1634 if (cmd.argument().empty() && &cur.inset() == this) {
1635 // if there is no argument and we're inside math, we retrieve
1636 // the row number from the cursor position.
1637 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1638 enabled = numberedType() && label_[row] && numbered_[row];
1640 // if there is an argument, find the corresponding label, else
1641 // check whether there is at least one label.
1642 for (row_type row = 0; row != nrows(); ++row) {
1643 if (numbered_[row] && label_[row] &&
1644 (cmd.argument().empty() || label(row) == cmd.argument())) {
1650 status.setEnabled(enabled);
1654 case LFUN_INSET_INSERT:
1655 if (cmd.getArg(0) == "label") {
1656 status.setEnabled(type_ != hullSimple);
1659 return InsetMathGrid::getStatus(cur, cmd, status);
1661 case LFUN_INSET_MODIFY: {
1662 istringstream is(to_utf8(cmd.argument()));
1666 return InsetMathGrid::getStatus(cur, cmd, status);
1669 && (s == "append-row"
1670 || s == "delete-row"
1671 || s == "copy-row")) {
1672 status.message(bformat(
1673 from_utf8(N_("Can't change number of rows in '%1$s'")),
1675 status.setEnabled(false);
1679 && (s == "append-column"
1680 || s == "delete-column"
1681 || s == "copy-column")) {
1682 status.message(bformat(
1683 from_utf8(N_("Can't change number of columns in '%1$s'")),
1685 status.setEnabled(false);
1688 if ((type_ == hullSimple
1689 || type_ == hullEquation
1690 || type_ == hullNone) &&
1691 (s == "add-hline-above" || s == "add-hline-below")) {
1692 status.message(bformat(
1693 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1695 status.setEnabled(false);
1698 if (s == "add-vline-left" || s == "add-vline-right") {
1699 status.message(bformat(
1700 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1702 status.setEnabled(false);
1705 if (s == "valign-top" || s == "valign-middle"
1706 || s == "valign-bottom" || s == "align-left"
1707 || s == "align-center" || s == "align-right") {
1708 status.setEnabled(false);
1711 return InsetMathGrid::getStatus(cur, cmd, status);
1715 return InsetMathGrid::getStatus(cur, cmd, status);
1718 // This cannot really happen, but inserted to shut-up gcc
1719 return InsetMathGrid::getStatus(cur, cmd, status);
1723 /////////////////////////////////////////////////////////////////////
1727 // simply scrap this function if you want
1728 void InsetMathHull::mutateToText()
1731 // translate to latex
1733 latex(os, false, false);
1734 string str = os.str();
1737 Text * lt = view_->cursor().innerText();
1738 string::const_iterator cit = str.begin();
1739 string::const_iterator end = str.end();
1740 for (; cit != end; ++cit)
1741 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1744 //dispatch(LFUN_ESCAPE);
1749 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1750 docstring const & font)
1752 // this whole function is a hack and won't work for incremental font
1755 if (cur.inset().asInsetMath()->name() == font)
1756 cur.handleFont(to_utf8(font));
1758 cur.handleNest(createInsetMath(font, cur.buffer()));
1764 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1769 font.fromString(to_utf8(arg), b);
1770 if (font.fontInfo().color() != Color_inherit) {
1771 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1772 cur.handleNest(at, 0);
1777 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1780 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1781 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1782 enter_front ? idxFirst(cur) : idxLast(cur);
1783 // The inset formula dimension is not necessarily the same as the
1784 // one of the instant preview image, so we have to indicate to the
1785 // BufferView that a metrics update is needed.
1786 cur.screenUpdateFlags(Update::Force);
1790 void InsetMathHull::revealCodes(Cursor & cur) const
1792 if (!cur.inMathed())
1794 odocstringstream os;
1796 cur.message(os.str());
1798 // write something to the minibuffer
1799 // translate to latex
1803 string str = os.str();
1805 string::size_type pos = 0;
1807 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1810 else if (*it == '\0') {
1812 pos = it - str.begin();
1818 res = res.substr(pos - 30);
1819 if (res.size() > 60)
1820 res = res.substr(0, 60);
1826 /////////////////////////////////////////////////////////////////////
1830 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1833 // FIXME: completely broken
1834 static InsetMathHull * lastformula = 0;
1835 static CursorBase current = DocIterator(ibegin(nucleus()));
1837 static string laststr;
1839 if (lastformula != this || laststr != str) {
1840 //lyxerr << "reset lastformula to " << this << endl;
1843 current = ibegin(nucleus());
1845 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1849 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1851 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1852 CursorSlice & top = it.back();
1853 MathData const & a = top.asInsetMath()->cell(top.idx_);
1854 if (a.matchpart(ar, top.pos_)) {
1855 bv->cursor().setSelection(it, ar.size());
1857 top.pos_ += ar.size();
1863 //lyxerr << "not found!" << endl;
1870 void InsetMathHull::write(ostream & os) const
1872 odocstringstream oss;
1873 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1876 os << to_utf8(oss.str());
1880 void InsetMathHull::read(Lexer & lex)
1883 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1884 operator=(*at->asHullInset());
1888 bool InsetMathHull::readQuiet(Lexer & lex)
1891 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1893 operator=(*at->asHullInset());
1898 int InsetMathHull::plaintext(odocstream & os, OutputParams const & op) const
1900 // disables ASCII-art for export of equations. See #2275.
1901 if (0 && display()) {
1905 TextPainter tpain(dim.width(), dim.height());
1906 drawT(tpain, 0, dim.ascent());
1908 // reset metrics cache to "real" values
1910 return tpain.textheight();
1913 odocstringstream oss;
1914 Encoding const * const enc = encodings.fromLyXName("utf8");
1915 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1918 if (type_ == hullRegexp)
1921 for (row_type r = 0; r < nrows(); ++r) {
1922 for (col_type c = 0; c < ncols(); ++c)
1923 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
1924 // if it's for the TOC, we write just the first line
1925 // and do not include the newline.
1931 docstring const str = oss.str();
1937 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1942 if (getType() == hullSimple)
1943 name = from_ascii("inlineequation");
1945 name = from_ascii("informalequation");
1947 docstring bname = name;
1948 if (!label(0).empty())
1949 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1951 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1953 odocstringstream ls;
1954 if (runparams.flavor == OutputParams::XML) {
1955 ms << MTag("alt role='tex' ");
1956 // Workaround for db2latex: db2latex always includes equations with
1957 // \ensuremath{} or \begin{display}\end{display}
1958 // so we strip LyX' math environment
1959 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1960 InsetMathGrid::write(wi);
1961 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1966 InsetMathGrid::mathmlize(ms);
1971 otexstream ols(ls, texrow);
1972 ms << MTag("alt role='tex'");
1973 latex(ols, runparams);
1974 res = texrow.rows();
1975 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1979 ms << from_ascii("<graphic fileref=\"eqn/");
1980 if (!label(0).empty())
1981 ms << sgml::cleanID(buffer(), runparams, label(0));
1983 ms << sgml::uniqueID(from_ascii("anon"));
1985 if (runparams.flavor == OutputParams::XML)
1986 ms << from_ascii("\"/>");
1988 ms << from_ascii("\">");
1990 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1992 return ms.line() + res;
1996 bool InsetMathHull::haveNumbers() const
1998 bool havenumbers = false;
1999 // inline formulas are never numbered (bug 7351 part 3)
2000 if (getType() == hullSimple)
2002 for (size_t i = 0; i != numbered_.size(); ++i) {
2013 // We need to do something about alignment here.
2015 // This duplicates code from InsetMathGrid, but
2016 // we need access here to number information,
2017 // and we simply do not have that in InsetMathGrid.
2018 void InsetMathHull::htmlize(HtmlStream & os) const
2020 bool const havenumbers = haveNumbers();
2021 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2024 os << cell(index(0, 0));
2028 os << MTag("table", "class='mathtable'");
2029 for (row_type row = 0; row < nrows(); ++row) {
2031 for (col_type col = 0; col < ncols(); ++col) {
2033 os << cell(index(row, col));
2038 docstring const & num = numbers_[row];
2040 os << '(' << num << ')';
2045 os << ETag("table");
2049 // this duplicates code from InsetMathGrid, but
2050 // we need access here to number information,
2051 // and we simply do not have that in InsetMathGrid.
2052 void InsetMathHull::mathmlize(MathStream & os) const
2054 bool const havenumbers = haveNumbers();
2055 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2058 os << MTag("mtable");
2059 char const * const celltag = havetable ? "mtd" : "mrow";
2060 // FIXME There does not seem to be wide support at the moment
2061 // for mlabeledtr, so we have to use just mtr for now.
2062 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2063 char const * const rowtag = "mtr";
2064 for (row_type row = 0; row < nrows(); ++row) {
2067 for (col_type col = 0; col < ncols(); ++col) {
2069 << cell(index(row, col))
2075 docstring const & num = numbers_[row];
2077 os << '(' << num << ')';
2084 os << ETag("mtable");
2088 void InsetMathHull::mathAsLatex(WriteStream & os) const
2090 MathEnsurer ensurer(os, false);
2091 bool havenumbers = haveNumbers();
2092 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2095 os << cell(index(0, 0));
2099 os << "<table class='mathtable'>";
2100 for (row_type row = 0; row < nrows(); ++row) {
2102 for (col_type col = 0; col < ncols(); ++col) {
2103 os << "<td class='math'>";
2104 os << cell(index(row, col));
2109 docstring const & num = numbers_[row];
2111 os << '(' << num << ')';
2120 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2122 BufferParams::MathOutput const mathtype =
2123 buffer().params().html_math_output;
2125 bool success = false;
2127 // we output all the labels just at the beginning of the equation.
2128 // this should be fine.
2129 for (size_t i = 0; i != label_.size(); ++i) {
2130 InsetLabel const * const il = label_[i];
2136 // FIXME Eventually we would like to do this inset by inset.
2137 if (mathtype == BufferParams::MathML) {
2138 odocstringstream os;
2143 } catch (MathExportException const &) {}
2145 if (getType() == hullSimple)
2146 xs << html::StartTag("math",
2147 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2149 xs << html::StartTag("math",
2150 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2151 xs << XHTMLStream::ESCAPE_NONE
2153 << html::EndTag("math");
2155 } else if (mathtype == BufferParams::HTML) {
2156 odocstringstream os;
2161 } catch (MathExportException const &) {}
2163 string const tag = (getType() == hullSimple) ? "span" : "div";
2164 xs << html::StartTag(tag, "class='formula'", true)
2165 << XHTMLStream::ESCAPE_NONE
2167 << html::EndTag(tag);
2171 // what we actually want is this:
2173 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2175 // || mathtype == BufferParams::Images
2177 // but what follows is equivalent, since we'll enter only if either (a) we
2178 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2179 // aren't doing LaTeX, in which case we are doing Images.
2180 if (!success && mathtype != BufferParams::LaTeX) {
2181 graphics::PreviewImage const * pimage = 0;
2183 loadPreview(docit_);
2184 pimage = preview_->getPreviewImage(buffer());
2185 // FIXME Do we always have png?
2188 if (pimage || op.dryrun) {
2189 string const filename = pimage ? pimage->filename().onlyFileName()
2190 : "previewimage.png";
2192 // if we are not in the master buffer, then we need to see that the
2193 // generated image is copied there; otherwise, preview fails.
2194 Buffer const * mbuf = buffer().masterBuffer();
2195 if (mbuf != &buffer()) {
2196 string mbtmp = mbuf->temppath();
2197 FileName const mbufimg(support::addName(mbtmp, filename));
2198 pimage->filename().copyTo(mbufimg);
2200 // add the file to the list of files to be exported
2201 op.exportdata->addExternalFile("xhtml", pimage->filename());
2204 string const tag = (getType() == hullSimple) ? "span" : "div";
2206 << html::StartTag(tag)
2207 << html::CompTag("img", "src=\"" + filename + "\"")
2208 << html::EndTag(tag)
2214 // so we'll pass this test if we've failed everything else, or
2215 // if mathtype was LaTeX, since we won't have entered any of the
2217 if (!success /* || mathtype != BufferParams::LaTeX */) {
2218 // Unfortunately, we cannot use latexString() because we do not want
2219 // $...$ or whatever.
2220 odocstringstream ls;
2221 WriteStream wi(ls, false, true, WriteStream::wsPreview);
2222 ModeSpecifier specifier(wi, MATH_MODE);
2224 docstring const latex = ls.str();
2226 // class='math' allows for use of jsMath
2227 // http://www.math.union.edu/~dpvc/jsMath/
2229 // probably should allow for some kind of customization here
2230 string const tag = (getType() == hullSimple) ? "span" : "div";
2231 xs << html::StartTag(tag, "class='math'")
2233 << html::EndTag(tag)
2240 void InsetMathHull::toString(odocstream & os) const
2242 plaintext(os, OutputParams(0));
2246 void InsetMathHull::forToc(docstring & os, size_t) const
2248 odocstringstream ods;
2256 string InsetMathHull::contextMenuName() const
2258 return "context-math";
2262 void InsetMathHull::recordLocation(DocIterator const & di)