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, bool output_active) 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, output_active);
303 toc.push_back(TocItem(pit, 0, nicelabel(row), output_active));
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 && type_ != hullRegexp)
418 graphics::PreviewImage const * pimage =
419 preview_->getPreviewImage(bv->buffer());
420 return pimage && pimage->image();
426 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
428 if (previewState(mi.base.bv)) {
429 preview_->metrics(mi, dim);
430 // insert a one pixel gap in front of the formula
433 dim.des += displayMargin();
434 // Cache the inset dimension.
435 setDimCache(mi, dim);
439 FontSetChanger dummy1(mi.base, standardFont());
440 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
442 // let the cells adjust themselves
443 InsetMathGrid::metrics(mi, dim);
446 dim.asc += displayMargin();
447 dim.des += displayMargin();
450 if (numberedType()) {
451 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
453 for (row_type row = 0; row < nrows(); ++row)
454 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
460 if (type_ == hullRegexp)
462 // make it at least as high as the current font
465 math_font_max_dim(mi.base.font, asc, des);
466 dim.asc = max(dim.asc, asc);
467 dim.des = max(dim.des, des);
468 // Cache the inset dimension.
469 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
470 setDimCache(mi, dim);
474 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
476 if (previewState(pi.base.bv))
477 return graphics::PreviewLoader::backgroundColor();
482 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
484 Dimension const dim = dimension(*pi.base.bv);
485 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
486 dim.asc + dim.des - 1, pi.backgroundColor(this));
490 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
492 use_preview_ = previewState(pi.base.bv);
494 if (type_ == hullRegexp) {
495 Dimension const dim = dimension(*pi.base.bv);
496 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
497 dim.width() - 2, dim.height() - 2, Color_regexpframe);
500 // one pixel gap in front
501 preview_->draw(pi, x + 1, y);
502 setPosCache(pi, x, y);
506 ColorCode color = pi.selected && lyxrc.use_system_colors
507 ? Color_selectiontext : standardColor();
508 bool const really_change_color = pi.base.font.color() == Color_none;
509 ColorChanger dummy0(pi.base.font, color, really_change_color);
510 FontSetChanger dummy1(pi.base, standardFont());
511 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
513 InsetMathGrid::draw(pi, x + 1, y);
515 if (numberedType()) {
516 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
517 for (row_type row = 0; row < nrows(); ++row) {
518 int const yy = y + rowinfo_[row].offset_;
519 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
520 docstring const nl = nicelabel(row);
524 setPosCache(pi, x, y);
528 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
531 InsetMathGrid::metricsT(mi, dim);
534 WriteStream wi(os, false, true, WriteStream::wsDefault);
536 dim.wid = os.str().size();
543 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
546 InsetMathGrid::drawT(pain, x, y);
549 WriteStream wi(os, false, true, WriteStream::wsDefault);
551 pain.draw(x, y, os.str().c_str());
556 static docstring latexString(InsetMathHull const & inset)
559 // This has to be static, because a preview snippet or a math
560 // macro containing math in text mode (such as $\text{$\phi$}$ or
561 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
562 // first time as a whole, and the second time only the inner math.
563 // In this last case inset.buffer() would be invalid.
564 static Encoding const * encoding = 0;
565 if (inset.isBufferValid())
566 encoding = &(inset.buffer().params().encoding());
567 WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
573 void InsetMathHull::initUnicodeMath() const
575 // Trigger classification of the unicode symbols in this inset
576 docstring const dummy = latexString(*this);
580 void InsetMathHull::addPreview(DocIterator const & inset_pos,
581 graphics::PreviewLoader & /*ploader*/) const
583 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
584 preparePreview(inset_pos);
589 void InsetMathHull::preparePreview(DocIterator const & pos,
590 bool forexport) const
592 // there is no need to do all the macro stuff if we're not
593 // actually going to generate the preview.
594 if (RenderPreview::status() != LyXRC::PREVIEW_ON && !forexport)
597 Buffer const * buffer = pos.buffer();
599 // collect macros at this position
601 buffer->listMacroNames(macros);
602 MacroNameSet::iterator it = macros.begin();
603 MacroNameSet::iterator end = macros.end();
604 odocstringstream macro_preamble;
605 for (; it != end; ++it) {
606 MacroData const * data = buffer->getMacro(*it, pos, true);
608 data->write(macro_preamble, true);
609 macro_preamble << endl;
614 if (forexport && haveNumbers()) {
615 docstring eqstr = from_ascii("equation");
616 CounterMap::const_iterator it = counter_map.find(eqstr);
617 if (it != counter_map.end()) {
618 int num = it->second;
620 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
621 '{' + convert<docstring>(num) + '}' + '\n';
623 for (size_t i = 0; i != numcnts; ++i) {
624 docstring cnt = from_ascii(counters_to_save[i]);
625 it = counter_map.find(cnt);
626 if (it == counter_map.end())
628 int num = it->second;
630 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
631 '{' + convert<docstring>(num) + '}';
634 docstring const snippet = macro_preamble.str() +
635 setcnt + latexString(*this);
636 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
637 preview_->addPreview(snippet, *buffer, forexport);
641 void InsetMathHull::reloadPreview(DocIterator const & pos) const
644 preview_->startLoading(*pos.buffer());
648 void InsetMathHull::loadPreview(DocIterator const & pos) const
650 bool const forexport = true;
651 preparePreview(pos, forexport);
652 preview_->startLoading(*pos.buffer(), forexport);
656 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
658 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
660 cur.screenUpdateFlags(Update::Force);
666 docstring InsetMathHull::label(row_type row) const
668 LASSERT(row < nrows(), return docstring());
669 if (InsetLabel * il = label_[row])
670 return il->screenLabel();
675 void InsetMathHull::label(row_type row, docstring const & label)
677 //lyxerr << "setting label '" << label << "' for row " << row << endl;
681 label_[row] = dummy_pointer;
684 label_[row]->updateLabelAndRefs(label);
686 label_[row]->setParam("name", label);
690 InsetCommandParams p(LABEL_CODE);
692 label_[row] = new InsetLabel(buffer_, p);
694 label_[row]->setBuffer(buffer());
698 void InsetMathHull::numbered(row_type row, bool num)
700 numbered_[row] = num;
701 if (!numbered_[row] && label_[row]) {
708 bool InsetMathHull::numbered(row_type row) const
710 return numbered_[row];
714 bool InsetMathHull::ams() const
716 return type_ == hullAlign
717 || type_ == hullFlAlign
718 || type_ == hullMultline
719 || type_ == hullGather
720 || type_ == hullAlignAt
721 || type_ == hullXAlignAt
722 || type_ == hullXXAlignAt;
726 Inset::DisplayType InsetMathHull::display() const
728 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
733 bool InsetMathHull::numberedType() const
735 if (type_ == hullNone)
737 if (type_ == hullSimple)
739 if (type_ == hullXXAlignAt)
741 if (type_ == hullRegexp)
743 for (row_type row = 0; row < nrows(); ++row)
750 void InsetMathHull::validate(LaTeXFeatures & features) const
752 if (features.runparams().isLaTeX()) {
754 features.require("amsmath");
756 if (type_ == hullRegexp) {
757 features.require("color");
758 string frcol = lcolor.getLaTeXName(Color_regexpframe);
759 string bgcol = "white";
760 features.addPreambleSnippet(
761 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
762 + frcol + string("}{")
763 + bgcol + string("}{\\ensuremath{\\mathtt{#1}}}}"));
764 features.addPreambleSnippet(
765 string("\\newcommand{\\endregexp}{}"));
768 // Validation is necessary only if not using AMS math.
769 // To be safe, we will always run mathedvalidate.
770 //if (features.amsstyle)
773 //features.binom = true;
774 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
775 // it would be better to do this elsewhere, but we can't validate in
776 // InsetMathMatrix and we have no way, outside MathExtern, to know if
777 // we even have any matrices.
778 features.addCSSSnippet(
779 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
780 "table.matrix td{padding: 0.25px;}\n"
781 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
782 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
784 InsetMathGrid::validate(features);
788 void InsetMathHull::header_write(WriteStream & os) const
790 bool n = numberedType();
804 os << "\n\\begin{equation" << star(n) << "}\n";
814 os << "\n\\begin{" << hullName(type_) << star(n) << "}\n";
819 os << "\n\\begin{" << hullName(type_) << star(n) << '}'
820 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
824 os << "\n\\begin{" << hullName(type_) << '}'
825 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
833 os << "\n\\begin{unknown" << star(n) << "}\n";
839 void InsetMathHull::footer_write(WriteStream & os) const
841 bool n = numberedType();
854 os << "\n\\end{equation" << star(n) << "}\n";
866 os << "\n\\end{" << hullName(type_) << star(n) << "}\n";
870 os << "\n\\end{" << hullName(type_) << "}\n";
874 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
875 os << "\\endregexp{}}";
879 os << "\n\\end{unknown" << star(n) << "}\n";
885 bool InsetMathHull::rowChangeOK() const
888 type_ == hullEqnArray || type_ == hullAlign ||
889 type_ == hullFlAlign || type_ == hullAlignAt ||
890 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
891 type_ == hullGather || type_ == hullMultline;
895 bool InsetMathHull::colChangeOK() const
898 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
899 type_ == hullXAlignAt || type_ == hullXXAlignAt;
903 void InsetMathHull::addRow(row_type row)
908 bool numbered = numberedType();
909 // Move the number and raw pointer, do not call label() (bug 7511)
910 InsetLabel * label = dummy_pointer;
911 docstring number = empty_docstring();
912 if (type_ == hullMultline) {
913 if (row + 1 == nrows()) {
914 numbered_[row] = false;
915 swap(label, label_[row]);
916 swap(number, numbers_[row]);
921 numbered_.insert(numbered_.begin() + row + 1, numbered);
922 numbers_.insert(numbers_.begin() + row + 1, number);
923 label_.insert(label_.begin() + row + 1, label);
924 InsetMathGrid::addRow(row);
928 void InsetMathHull::swapRow(row_type row)
932 if (row + 1 == nrows())
934 // gcc implements the standard std::vector<bool> which is *not* a container:
935 // http://www.gotw.ca/publications/N1185.pdf
936 // As a results, it doesn't like this:
937 // swap(numbered_[row], numbered_[row + 1]);
938 // so we do it manually:
939 bool const b = numbered_[row];
940 numbered_[row] = numbered_[row + 1];
941 numbered_[row + 1] = b;
942 swap(numbers_[row], numbers_[row + 1]);
943 swap(label_[row], label_[row + 1]);
944 InsetMathGrid::swapRow(row);
948 void InsetMathHull::delRow(row_type row)
950 if (nrows() <= 1 || !rowChangeOK())
952 if (row + 1 == nrows() && type_ == hullMultline) {
953 bool const b = numbered_[row - 1];
954 numbered_[row - 1] = numbered_[row];
956 swap(numbers_[row - 1], numbers_[row]);
957 swap(label_[row - 1], label_[row]);
958 InsetMathGrid::delRow(row);
961 InsetMathGrid::delRow(row);
962 // The last dummy row has no number info nor a label.
963 // Test nrows() + 1 because we have already erased the row.
964 if (row == nrows() + 1)
966 numbered_.erase(numbered_.begin() + row);
967 numbers_.erase(numbers_.begin() + row);
969 label_.erase(label_.begin() + row);
973 void InsetMathHull::addCol(col_type col)
977 InsetMathGrid::addCol(col);
981 void InsetMathHull::delCol(col_type col)
983 if (ncols() <= 1 || !colChangeOK())
985 InsetMathGrid::delCol(col);
989 docstring InsetMathHull::nicelabel(row_type row) const
993 docstring const & val = numbers_[row];
995 return '(' + val + ')';
996 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1000 void InsetMathHull::glueall(HullType type)
1003 for (idx_type i = 0; i < nargs(); ++i)
1005 InsetLabel * label = 0;
1006 if (type == hullEquation) {
1007 // preserve first non-empty label
1008 for (row_type row = 0; row < nrows(); ++row) {
1010 label = label_[row];
1016 *this = InsetMathHull(buffer_, hullSimple);
1023 void InsetMathHull::splitTo2Cols()
1025 LASSERT(ncols() == 1, return);
1026 InsetMathGrid::addCol(1);
1027 for (row_type row = 0; row < nrows(); ++row) {
1028 idx_type const i = 2 * row;
1029 pos_type pos = firstRelOp(cell(i));
1030 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1031 cell(i).erase(pos, cell(i).size());
1036 void InsetMathHull::splitTo3Cols()
1038 LASSERT(ncols() < 3, return);
1041 InsetMathGrid::addCol(2);
1042 for (row_type row = 0; row < nrows(); ++row) {
1043 idx_type const i = 3 * row + 1;
1044 if (!cell(i).empty()) {
1045 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1046 cell(i).erase(1, cell(i).size());
1052 void InsetMathHull::changeCols(col_type cols)
1054 if (ncols() == cols)
1056 else if (ncols() < cols) {
1062 while (ncols() < cols)
1063 InsetMathGrid::addCol(ncols());
1069 for (row_type row = 0; row < nrows(); ++row) {
1070 idx_type const i = row * ncols();
1071 for (col_type col = cols; col < ncols(); ++col) {
1072 cell(i + cols - 1).append(cell(i + col));
1076 while (ncols() > cols) {
1077 InsetMathGrid::delCol(ncols() - 1);
1082 HullType InsetMathHull::getType() const
1088 void InsetMathHull::setType(HullType type)
1095 void InsetMathHull::mutate(HullType newtype)
1097 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1099 // we try to move along the chain
1100 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1102 // +-------------------------------------+
1103 // we use eqnarray as intermediate type for mutations that are not
1104 // directly supported because it handles labels and numbering for
1107 if (newtype == type_) {
1111 else if (newtype < hullNone) {
1116 else if (type_ == hullNone) {
1117 setType(hullSimple);
1122 else if (type_ == hullSimple) {
1123 if (newtype == hullNone) {
1127 setType(hullEquation);
1128 numbered(0, label_[0] ? true : false);
1133 else if (type_ == hullEquation) {
1134 if (newtype < type_) {
1135 setType(hullSimple);
1138 } else if (newtype == hullEqnArray) {
1139 // split it "nicely" on the first relop
1141 setType(hullEqnArray);
1142 } else if (newtype == hullMultline || newtype == hullGather) {
1145 // split it "nicely"
1152 else if (type_ == hullEqnArray) {
1153 if (newtype < type_) {
1156 } else { // align & Co.
1163 else if (type_ == hullAlign || type_ == hullAlignAt ||
1164 type_ == hullXAlignAt || type_ == hullFlAlign) {
1165 if (newtype < hullAlign) {
1167 setType(hullEqnArray);
1169 } else if (newtype == hullGather || newtype == hullMultline) {
1172 } else if (newtype == hullXXAlignAt) {
1173 for (row_type row = 0; row < nrows(); ++row)
1174 numbered(row, false);
1181 else if (type_ == hullXXAlignAt) {
1182 for (row_type row = 0; row < nrows(); ++row)
1183 numbered(row, false);
1184 if (newtype < hullAlign) {
1186 setType(hullEqnArray);
1188 } else if (newtype == hullGather || newtype == hullMultline) {
1196 else if (type_ == hullMultline || type_ == hullGather) {
1197 if (newtype == hullGather || newtype == hullMultline)
1199 else if (newtype == hullAlign || newtype == hullFlAlign ||
1200 newtype == hullAlignAt || newtype == hullXAlignAt) {
1203 } else if (newtype == hullXXAlignAt) {
1205 for (row_type row = 0; row < nrows(); ++row)
1206 numbered(row, false);
1210 setType(hullEqnArray);
1216 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1217 << "' to '" << to_utf8(hullName(newtype))
1218 << "' not implemented" << endl;
1223 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1224 bool last_eoln) const
1227 if (numberedType()) {
1228 if (label_[row] && numbered_[row]) {
1229 docstring const name =
1230 latex ? escape(label_[row]->getParam("name"))
1231 : label_[row]->getParam("name");
1232 res += "\\label{" + name + '}';
1234 if (!numbered_[row] && (type_ != hullMultline))
1235 res += "\\nonumber ";
1237 // Never add \\ on the last empty line of eqnarray and friends
1239 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1243 void InsetMathHull::write(WriteStream & os) const
1245 ModeSpecifier specifier(os,
1246 type_ == hullRegexp ? TEXT_MODE : MATH_MODE);
1248 InsetMathGrid::write(os);
1253 void InsetMathHull::normalize(NormalStream & os) const
1255 os << "[formula " << hullName(type_) << ' ';
1256 InsetMathGrid::normalize(os);
1261 void InsetMathHull::infoize(odocstream & os) const
1263 os << "Type: " << hullName(type_);
1267 void InsetMathHull::check() const
1269 LATTEST(numbered_.size() == nrows());
1270 LATTEST(numbers_.size() == nrows());
1271 LATTEST(label_.size() == nrows());
1275 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1279 idocstringstream iss(func.argument());
1280 iss >> dlang >> extra;
1282 extra = from_ascii("noextra");
1283 string const lang = to_ascii(dlang);
1285 // FIXME: temporarily disabled
1286 //if (cur.selection()) {
1289 // lyxerr << "use selection: " << ar << endl;
1290 // insert(pipeThroughExtern(lang, extra, ar));
1294 // only inline, display or eqnarray math is allowed
1295 if (getType() > hullEqnArray) {
1296 frontend::Alert::warning(_("Bad math environment"),
1297 _("Computation cannot be performed for AMS "
1298 "math environments.\nChange the math "
1299 "formula type and try again."));
1304 eq.push_back(MathAtom(new InsetMathChar('=')));
1306 // go to first item in line
1307 cur.idx() -= cur.idx() % ncols();
1310 if (getType() == hullSimple) {
1311 size_type pos = cur.cell().find_last(eq);
1313 if (cur.inMathed() && cur.selection()) {
1314 asArray(grabAndEraseSelection(cur), ar);
1315 } else if (!pos == cur.cell().empty()) {
1317 lyxerr << "use whole cell: " << ar << endl;
1319 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1320 lyxerr << "use partial cell form pos: " << pos << endl;
1322 cur.cell().append(eq);
1323 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1324 cur.pos() = cur.lastpos();
1328 if (getType() == hullEquation) {
1329 lyxerr << "use equation inset" << endl;
1330 mutate(hullEqnArray);
1331 MathData & ar = cur.cell();
1332 lyxerr << "use cell: " << ar << endl;
1336 cur.cell() = pipeThroughExtern(lang, extra, ar);
1337 // move to end of line
1338 cur.pos() = cur.lastpos();
1343 lyxerr << "use eqnarray" << endl;
1344 cur.idx() += 2 - cur.idx() % ncols();
1346 MathData ar = cur.cell();
1347 lyxerr << "use cell: " << ar << endl;
1348 // FIXME: temporarily disabled
1354 cur.cell() = pipeThroughExtern(lang, extra, ar);
1355 cur.pos() = cur.lastpos();
1360 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1362 //lyxerr << "action: " << cmd.action() << endl;
1363 switch (cmd.action()) {
1365 case LFUN_FINISHED_BACKWARD:
1366 case LFUN_FINISHED_FORWARD:
1367 case LFUN_FINISHED_RIGHT:
1368 case LFUN_FINISHED_LEFT:
1369 //lyxerr << "action: " << cmd.action() << endl;
1370 InsetMathGrid::doDispatch(cur, cmd);
1374 case LFUN_PARAGRAPH_BREAK:
1375 // just swallow this
1378 case LFUN_NEWLINE_INSERT:
1379 // some magic for the common case
1380 if (type_ == hullSimple || type_ == hullEquation) {
1381 cur.recordUndoInset();
1383 cur.bv().buffer().params().use_package("amsmath") == BufferParams::package_on;
1384 mutate(align ? hullAlign : hullEqnArray);
1385 // mutate() may change labels and such.
1386 cur.forceBufferUpdate();
1387 cur.idx() = nrows() * ncols() - 1;
1388 cur.pos() = cur.lastpos();
1390 InsetMathGrid::doDispatch(cur, cmd);
1393 case LFUN_MATH_NUMBER_TOGGLE: {
1394 //lyxerr << "toggling all numbers" << endl;
1395 cur.recordUndoInset();
1396 bool old = numberedType();
1397 if (type_ == hullMultline)
1398 numbered(nrows() - 1, !old);
1400 for (row_type row = 0; row < nrows(); ++row)
1401 numbered(row, !old);
1403 cur.message(old ? _("No number") : _("Number"));
1404 cur.forceBufferUpdate();
1408 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1409 cur.recordUndoInset();
1410 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1411 bool old = numbered(r);
1412 cur.message(old ? _("No number") : _("Number"));
1414 cur.forceBufferUpdate();
1418 case LFUN_LABEL_INSERT: {
1419 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1420 docstring old_label = label(r);
1421 docstring const default_label = from_ascii("eq:");
1422 if (old_label.empty())
1423 old_label = default_label;
1425 InsetCommandParams p(LABEL_CODE);
1426 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1427 string const data = InsetCommand::params2string(p);
1429 if (cmd.argument().empty())
1430 cur.bv().showDialog("label", data);
1432 FuncRequest fr(LFUN_INSET_INSERT, data);
1438 case LFUN_LABEL_COPY_AS_REF: {
1440 if (cmd.argument().empty() && &cur.inset() == this)
1441 // if there is no argument and we're inside math, we retrieve
1442 // the row number from the cursor position.
1443 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1445 // if there is an argument, find the corresponding label, else
1446 // check whether there is at least one label.
1447 for (row = 0; row != nrows(); ++row)
1448 if (numbered_[row] && label_[row]
1449 && (cmd.argument().empty() || label(row) == cmd.argument()))
1456 InsetCommandParams p(REF_CODE, "ref");
1457 p["reference"] = label(row);
1458 cap::clearSelection();
1459 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1463 case LFUN_WORD_DELETE_FORWARD:
1464 case LFUN_CHAR_DELETE_FORWARD:
1465 if (col(cur.idx()) + 1 == ncols()
1466 && cur.pos() == cur.lastpos()
1467 && !cur.selection()) {
1468 if (!label(row(cur.idx())).empty()) {
1469 cur.recordUndoInset();
1470 label(row(cur.idx()), docstring());
1471 } else if (numbered(row(cur.idx()))) {
1472 cur.recordUndoInset();
1473 numbered(row(cur.idx()), false);
1474 cur.forceBufferUpdate();
1476 InsetMathGrid::doDispatch(cur, cmd);
1480 InsetMathGrid::doDispatch(cur, cmd);
1485 case LFUN_INSET_INSERT: {
1486 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1487 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1488 string const name = cmd.getArg(0);
1489 if (name == "label") {
1490 InsetCommandParams p(LABEL_CODE);
1491 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1492 docstring str = p["name"];
1493 cur.recordUndoInset();
1494 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1498 docstring old = label(r);
1501 // The label will take care of the reference update.
1505 // Newly created inset so initialize it.
1506 label_[r]->initView();
1509 cur.forceBufferUpdate();
1512 InsetMathGrid::doDispatch(cur, cmd);
1516 case LFUN_MATH_EXTERN:
1517 cur.recordUndoInset();
1521 case LFUN_MATH_MUTATE: {
1522 cur.recordUndoInset();
1523 row_type row = cur.row();
1524 col_type col = cur.col();
1525 mutate(hullType(cmd.argument()));
1526 cur.idx() = row * ncols() + col;
1527 if (cur.idx() > cur.lastidx()) {
1528 cur.idx() = cur.lastidx();
1529 cur.pos() = cur.lastpos();
1531 if (cur.pos() > cur.lastpos())
1532 cur.pos() = cur.lastpos();
1534 cur.forceBufferUpdate();
1535 // FIXME: find some more clever handling of the selection,
1536 // i.e. preserve it.
1537 cur.clearSelection();
1538 //cur.dispatched(FINISHED);
1542 case LFUN_MATH_DISPLAY: {
1543 cur.recordUndoInset();
1544 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1546 cur.pos() = cur.lastpos();
1547 //cur.dispatched(FINISHED);
1552 InsetMathGrid::doDispatch(cur, cmd);
1558 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1559 FuncStatus & status) const
1561 switch (cmd.action()) {
1562 case LFUN_FINISHED_BACKWARD:
1563 case LFUN_FINISHED_FORWARD:
1564 case LFUN_FINISHED_RIGHT:
1565 case LFUN_FINISHED_LEFT:
1568 case LFUN_NEWLINE_INSERT:
1569 case LFUN_MATH_EXTERN:
1571 status.setEnabled(true);
1574 // we never allow this in math, and we want to bind enter
1575 // to another actions in command-alternatives
1576 case LFUN_PARAGRAPH_BREAK:
1577 status.setEnabled(false);
1579 case LFUN_MATH_MUTATE: {
1580 HullType const ht = hullType(cmd.argument());
1581 status.setOnOff(type_ == ht);
1582 status.setEnabled(true);
1584 if (ht != hullSimple) {
1585 Cursor tmpcur = cur;
1586 while (!tmpcur.empty()) {
1587 InsetCode code = tmpcur.inset().lyxCode();
1588 if (code == BOX_CODE) {
1590 } else if (code == TABULAR_CODE) {
1591 FuncRequest tmpcmd(LFUN_MATH_DISPLAY);
1592 if (tmpcur.getStatus(tmpcmd, status) && !status.enabled())
1600 case LFUN_MATH_DISPLAY: {
1602 if (cur.depth() > 1) {
1603 Inset const & in = cur[cur.depth()-2].inset();
1604 if (in.lyxCode() == SCRIPT_CODE)
1605 enable = display() != Inline;
1607 status.setEnabled(enable);
1611 case LFUN_MATH_NUMBER_TOGGLE:
1612 // FIXME: what is the right test, this or the one of
1614 status.setEnabled(display() != Inline);
1615 status.setOnOff(numberedType());
1618 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1619 // FIXME: what is the right test, this or the one of
1621 bool const enable = (type_ == hullMultline)
1622 ? (nrows() - 1 == cur.row())
1623 : display() != Inline;
1624 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1625 status.setEnabled(enable);
1626 status.setOnOff(enable && numbered(r));
1630 case LFUN_LABEL_INSERT:
1631 status.setEnabled(type_ != hullSimple);
1634 case LFUN_LABEL_COPY_AS_REF: {
1635 bool enabled = false;
1637 if (cmd.argument().empty() && &cur.inset() == this) {
1638 // if there is no argument and we're inside math, we retrieve
1639 // the row number from the cursor position.
1640 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1641 enabled = numberedType() && label_[row] && numbered_[row];
1643 // if there is an argument, find the corresponding label, else
1644 // check whether there is at least one label.
1645 for (row_type row = 0; row != nrows(); ++row) {
1646 if (numbered_[row] && label_[row] &&
1647 (cmd.argument().empty() || label(row) == cmd.argument())) {
1653 status.setEnabled(enabled);
1657 case LFUN_INSET_INSERT:
1658 if (cmd.getArg(0) == "label") {
1659 status.setEnabled(type_ != hullSimple);
1662 return InsetMathGrid::getStatus(cur, cmd, status);
1664 case LFUN_INSET_MODIFY: {
1665 istringstream is(to_utf8(cmd.argument()));
1669 return InsetMathGrid::getStatus(cur, cmd, status);
1672 && (s == "append-row"
1673 || s == "delete-row"
1674 || s == "copy-row")) {
1675 status.message(bformat(
1676 from_utf8(N_("Can't change number of rows in '%1$s'")),
1678 status.setEnabled(false);
1682 && (s == "append-column"
1683 || s == "delete-column"
1684 || s == "copy-column")) {
1685 status.message(bformat(
1686 from_utf8(N_("Can't change number of columns in '%1$s'")),
1688 status.setEnabled(false);
1691 if ((type_ == hullSimple
1692 || type_ == hullEquation
1693 || type_ == hullNone) &&
1694 (s == "add-hline-above" || s == "add-hline-below")) {
1695 status.message(bformat(
1696 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1698 status.setEnabled(false);
1701 if (s == "add-vline-left" || s == "add-vline-right") {
1702 status.message(bformat(
1703 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1705 status.setEnabled(false);
1708 if (s == "valign-top" || s == "valign-middle"
1709 || s == "valign-bottom" || s == "align-left"
1710 || s == "align-center" || s == "align-right") {
1711 status.setEnabled(false);
1714 return InsetMathGrid::getStatus(cur, cmd, status);
1718 return InsetMathGrid::getStatus(cur, cmd, status);
1721 // This cannot really happen, but inserted to shut-up gcc
1722 return InsetMathGrid::getStatus(cur, cmd, status);
1726 /////////////////////////////////////////////////////////////////////
1730 // simply scrap this function if you want
1731 void InsetMathHull::mutateToText()
1734 // translate to latex
1736 latex(os, false, false);
1737 string str = os.str();
1740 Text * lt = view_->cursor().innerText();
1741 string::const_iterator cit = str.begin();
1742 string::const_iterator end = str.end();
1743 for (; cit != end; ++cit)
1744 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1747 //dispatch(LFUN_ESCAPE);
1752 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1753 docstring const & font)
1755 // this whole function is a hack and won't work for incremental font
1758 if (cur.inset().asInsetMath()->name() == font)
1759 cur.handleFont(to_utf8(font));
1761 cur.handleNest(createInsetMath(font, cur.buffer()));
1767 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1772 font.fromString(to_utf8(arg), b);
1773 if (font.fontInfo().color() != Color_inherit) {
1774 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1775 cur.handleNest(at, 0);
1780 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1783 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1784 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1785 enter_front ? idxFirst(cur) : idxLast(cur);
1786 // The inset formula dimension is not necessarily the same as the
1787 // one of the instant preview image, so we have to indicate to the
1788 // BufferView that a metrics update is needed.
1789 cur.screenUpdateFlags(Update::Force);
1793 void InsetMathHull::revealCodes(Cursor & cur) const
1795 if (!cur.inMathed())
1797 odocstringstream os;
1799 cur.message(os.str());
1801 // write something to the minibuffer
1802 // translate to latex
1806 string str = os.str();
1808 string::size_type pos = 0;
1810 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1813 else if (*it == '\0') {
1815 pos = it - str.begin();
1821 res = res.substr(pos - 30);
1822 if (res.size() > 60)
1823 res = res.substr(0, 60);
1829 /////////////////////////////////////////////////////////////////////
1833 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1836 // FIXME: completely broken
1837 static InsetMathHull * lastformula = 0;
1838 static CursorBase current = DocIterator(ibegin(nucleus()));
1840 static string laststr;
1842 if (lastformula != this || laststr != str) {
1843 //lyxerr << "reset lastformula to " << this << endl;
1846 current = ibegin(nucleus());
1848 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1852 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1854 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1855 CursorSlice & top = it.back();
1856 MathData const & a = top.asInsetMath()->cell(top.idx_);
1857 if (a.matchpart(ar, top.pos_)) {
1858 bv->cursor().setSelection(it, ar.size());
1860 top.pos_ += ar.size();
1866 //lyxerr << "not found!" << endl;
1873 void InsetMathHull::write(ostream & os) const
1875 odocstringstream oss;
1876 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1879 os << to_utf8(oss.str());
1883 void InsetMathHull::read(Lexer & lex)
1886 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1887 operator=(*at->asHullInset());
1891 bool InsetMathHull::readQuiet(Lexer & lex)
1894 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1896 operator=(*at->asHullInset());
1901 int InsetMathHull::plaintext(odocstringstream & os,
1902 OutputParams const & op, size_t max_length) const
1904 // disables ASCII-art for export of equations. See #2275.
1905 if (0 && display()) {
1909 TextPainter tpain(dim.width(), dim.height());
1910 drawT(tpain, 0, dim.ascent());
1912 // reset metrics cache to "real" values
1914 return tpain.textheight();
1917 odocstringstream oss;
1918 Encoding const * const enc = encodings.fromLyXName("utf8");
1919 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1922 if (type_ == hullRegexp)
1925 for (row_type r = 0; r < nrows(); ++r) {
1926 for (col_type c = 0; c < ncols(); ++c)
1927 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
1928 // if it's for the TOC, we write just the first line
1929 // and do not include the newline.
1930 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
1935 docstring const str = oss.str();
1941 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1946 if (getType() == hullSimple)
1947 name = from_ascii("inlineequation");
1949 name = from_ascii("informalequation");
1951 docstring bname = name;
1952 if (!label(0).empty())
1953 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1955 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1957 odocstringstream ls;
1958 if (runparams.flavor == OutputParams::XML) {
1959 ms << MTag("alt role='tex' ");
1960 // Workaround for db2latex: db2latex always includes equations with
1961 // \ensuremath{} or \begin{display}\end{display}
1962 // so we strip LyX' math environment
1963 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1964 InsetMathGrid::write(wi);
1965 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1970 InsetMathGrid::mathmlize(ms);
1975 otexstream ols(ls, texrow);
1976 ms << MTag("alt role='tex'");
1977 latex(ols, runparams);
1978 res = texrow.rows();
1979 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1983 ms << from_ascii("<graphic fileref=\"eqn/");
1984 if (!label(0).empty())
1985 ms << sgml::cleanID(buffer(), runparams, label(0));
1987 ms << sgml::uniqueID(from_ascii("anon"));
1989 if (runparams.flavor == OutputParams::XML)
1990 ms << from_ascii("\"/>");
1992 ms << from_ascii("\">");
1994 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1996 return ms.line() + res;
2000 bool InsetMathHull::haveNumbers() const
2002 bool havenumbers = false;
2003 // inline formulas are never numbered (bug 7351 part 3)
2004 if (getType() == hullSimple)
2006 for (size_t i = 0; i != numbered_.size(); ++i) {
2017 // We need to do something about alignment here.
2019 // This duplicates code from InsetMathGrid, but
2020 // we need access here to number information,
2021 // and we simply do not have that in InsetMathGrid.
2022 void InsetMathHull::htmlize(HtmlStream & os) const
2024 bool const havenumbers = haveNumbers();
2025 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2028 os << cell(index(0, 0));
2032 os << MTag("table", "class='mathtable'");
2033 for (row_type row = 0; row < nrows(); ++row) {
2035 for (col_type col = 0; col < ncols(); ++col) {
2037 os << cell(index(row, col));
2042 docstring const & num = numbers_[row];
2044 os << '(' << num << ')';
2049 os << ETag("table");
2053 // this duplicates code from InsetMathGrid, but
2054 // we need access here to number information,
2055 // and we simply do not have that in InsetMathGrid.
2056 void InsetMathHull::mathmlize(MathStream & os) const
2058 bool const havenumbers = haveNumbers();
2059 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2062 os << MTag("mtable");
2063 char const * const celltag = havetable ? "mtd" : "mrow";
2064 // FIXME There does not seem to be wide support at the moment
2065 // for mlabeledtr, so we have to use just mtr for now.
2066 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2067 char const * const rowtag = "mtr";
2068 for (row_type row = 0; row < nrows(); ++row) {
2071 for (col_type col = 0; col < ncols(); ++col) {
2073 << cell(index(row, col))
2079 docstring const & num = numbers_[row];
2081 os << '(' << num << ')';
2088 os << ETag("mtable");
2092 void InsetMathHull::mathAsLatex(WriteStream & os) const
2094 MathEnsurer ensurer(os, false);
2095 bool havenumbers = haveNumbers();
2096 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2099 os << cell(index(0, 0));
2103 os << "<table class='mathtable'>";
2104 for (row_type row = 0; row < nrows(); ++row) {
2106 for (col_type col = 0; col < ncols(); ++col) {
2107 os << "<td class='math'>";
2108 os << cell(index(row, col));
2113 docstring const & num = numbers_[row];
2115 os << '(' << num << ')';
2124 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2126 BufferParams::MathOutput const mathtype =
2127 buffer().masterBuffer()->params().html_math_output;
2129 bool success = false;
2131 // we output all the labels just at the beginning of the equation.
2132 // this should be fine.
2133 for (size_t i = 0; i != label_.size(); ++i) {
2134 InsetLabel const * const il = label_[i];
2140 // FIXME Eventually we would like to do this inset by inset.
2141 if (mathtype == BufferParams::MathML) {
2142 odocstringstream os;
2147 } catch (MathExportException const &) {}
2149 if (getType() == hullSimple)
2150 xs << html::StartTag("math",
2151 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2153 xs << html::StartTag("math",
2154 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2155 xs << XHTMLStream::ESCAPE_NONE
2157 << html::EndTag("math");
2159 } else if (mathtype == BufferParams::HTML) {
2160 odocstringstream os;
2165 } catch (MathExportException const &) {}
2167 string const tag = (getType() == hullSimple) ? "span" : "div";
2168 xs << html::StartTag(tag, "class='formula'", true)
2169 << XHTMLStream::ESCAPE_NONE
2171 << html::EndTag(tag);
2175 // what we actually want is this:
2177 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2179 // || mathtype == BufferParams::Images
2181 // but what follows is equivalent, since we'll enter only if either (a) we
2182 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2183 // aren't doing LaTeX, in which case we are doing Images.
2184 if (!success && mathtype != BufferParams::LaTeX) {
2185 graphics::PreviewImage const * pimage = 0;
2187 loadPreview(docit_);
2188 pimage = preview_->getPreviewImage(buffer());
2189 // FIXME Do we always have png?
2192 if (pimage || op.dryrun) {
2193 string const filename = pimage ? pimage->filename().onlyFileName()
2194 : "previewimage.png";
2196 // if we are not in the master buffer, then we need to see that the
2197 // generated image is copied there; otherwise, preview fails.
2198 Buffer const * mbuf = buffer().masterBuffer();
2199 if (mbuf != &buffer()) {
2200 string mbtmp = mbuf->temppath();
2201 FileName const mbufimg(support::addName(mbtmp, filename));
2202 pimage->filename().copyTo(mbufimg);
2204 // add the file to the list of files to be exported
2205 op.exportdata->addExternalFile("xhtml", pimage->filename());
2208 string const tag = (getType() == hullSimple) ? "span" : "div";
2210 << html::StartTag(tag)
2211 << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2212 << html::EndTag(tag)
2218 // so we'll pass this test if we've failed everything else, or
2219 // if mathtype was LaTeX, since we won't have entered any of the
2221 if (!success /* || mathtype != BufferParams::LaTeX */) {
2222 // Unfortunately, we cannot use latexString() because we do not want
2223 // $...$ or whatever.
2224 odocstringstream ls;
2225 WriteStream wi(ls, false, true, WriteStream::wsPreview);
2226 ModeSpecifier specifier(wi, MATH_MODE);
2228 docstring const latex = ls.str();
2230 // class='math' allows for use of jsMath
2231 // http://www.math.union.edu/~dpvc/jsMath/
2233 // probably should allow for some kind of customization here
2234 string const tag = (getType() == hullSimple) ? "span" : "div";
2235 xs << html::StartTag(tag, "class='math'")
2237 << html::EndTag(tag)
2244 void InsetMathHull::toString(odocstream & os) const
2246 odocstringstream ods;
2247 plaintext(ods, OutputParams(0));
2252 void InsetMathHull::forToc(docstring & os, size_t) const
2254 odocstringstream ods;
2262 string InsetMathHull::contextMenuName() const
2264 return "context-math";
2268 void InsetMathHull::recordLocation(DocIterator const & di)