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/GraphicsImage.h"
48 #include "graphics/PreviewImage.h"
49 #include "graphics/PreviewLoader.h"
51 #include "frontends/alert.h"
52 #include "frontends/Painter.h"
54 #include "support/convert.h"
55 #include "support/lassert.h"
56 #include "support/debug.h"
57 #include "support/filetools.h"
58 #include "support/gettext.h"
59 #include "support/lstrings.h"
64 using namespace lyx::support;
68 using cap::grabAndEraseSelection;
69 using cap::reduceSelectionToOneCell;
73 int getCols(HullType type)
90 // returns position of first relation operator in the array
91 // used for "intelligent splitting"
92 size_t firstRelOp(MathData const & ar)
94 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
96 return it - ar.begin();
101 char const * star(bool numbered)
103 return numbered ? "" : "*";
107 } // end anon namespace
110 HullType hullType(docstring const & s)
112 if (s == "none") return hullNone;
113 if (s == "simple") return hullSimple;
114 if (s == "equation") return hullEquation;
115 if (s == "eqnarray") return hullEqnArray;
116 if (s == "align") return hullAlign;
117 if (s == "alignat") return hullAlignAt;
118 if (s == "xalignat") return hullXAlignAt;
119 if (s == "xxalignat") return hullXXAlignAt;
120 if (s == "multline") return hullMultline;
121 if (s == "gather") return hullGather;
122 if (s == "flalign") return hullFlAlign;
123 if (s == "regexp") return hullRegexp;
124 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
129 docstring hullName(HullType type)
132 case hullNone: return from_ascii("none");
133 case hullSimple: return from_ascii("simple");
134 case hullEquation: return from_ascii("equation");
135 case hullEqnArray: return from_ascii("eqnarray");
136 case hullAlign: return from_ascii("align");
137 case hullAlignAt: return from_ascii("alignat");
138 case hullXAlignAt: return from_ascii("xalignat");
139 case hullXXAlignAt: return from_ascii("xxalignat");
140 case hullMultline: return from_ascii("multline");
141 case hullGather: return from_ascii("gather");
142 case hullFlAlign: return from_ascii("flalign");
143 case hullRegexp: return from_ascii("regexp");
145 lyxerr << "unknown hull type '" << type << "'" << endl;
146 return from_ascii("none");
150 static InsetLabel * dummy_pointer = 0;
152 InsetMathHull::InsetMathHull(Buffer * buf)
153 : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, NUMBER),
154 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
155 preview_(new RenderPreview(this)), use_preview_(false)
157 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
158 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
159 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
160 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
167 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
168 : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, NUMBER),
169 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
170 preview_(new RenderPreview(this)), use_preview_(false)
178 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
184 InsetMathHull::~InsetMathHull()
186 for (size_t i = 0; i < label_.size(); ++i)
191 Inset * InsetMathHull::clone() const
193 return new InsetMathHull(*this);
197 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
201 InsetMathGrid::operator=(other);
203 numbered_ = other.numbered_;
204 numbers_ = other.numbers_;
205 buffer_ = other.buffer_;
206 for (size_t i = 0; i < label_.size(); ++i)
208 label_ = other.label_;
209 for (size_t i = 0; i != label_.size(); ++i) {
211 label_[i] = new InsetLabel(*label_[i]);
213 preview_.reset(new RenderPreview(*other.preview_, this));
219 void InsetMathHull::setBuffer(Buffer & buffer)
221 InsetMathGrid::setBuffer(buffer);
223 for (size_t i = 0; i != label_.size(); ++i) {
225 label_[i]->setBuffer(buffer);
230 // FIXME This should really be controlled by the TOC level, or
231 // something of the sort.
233 const char * counters_to_save[] = {"section", "chapter"};
234 unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
238 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
241 //FIXME: buffer_ should be set at creation for this inset! Problem is
242 // This inset is created at too many places (see Parser::parse1() in
247 // if any of the equations are numbered, then we want to save the values
248 // of some of the counters.
250 BufferParams const & bp = buffer_->params();
251 string const & lang = it->getParLanguage(bp)->code();
253 buffer_->masterBuffer()->params().documentClass().counters();
255 // right now, we only need to do this at export time
256 if (utype == OutputUpdate) {
257 for (size_t i = 0; i < numcnts; ++i) {
258 docstring const cnt = from_ascii(counters_to_save[i]);
259 if (cnts.hasCounter(cnt))
260 counter_map[cnt] = cnts.value(cnt);
264 // this has to be done separately
265 docstring const eqstr = from_ascii("equation");
266 if (cnts.hasCounter(eqstr)) {
267 if (utype == OutputUpdate)
268 counter_map[eqstr] = cnts.value(eqstr);
269 for (size_t i = 0; i != label_.size(); ++i) {
271 cnts.step(eqstr, utype);
272 numbers_[i] = cnts.theCounter(eqstr, lang);
274 numbers_[i] = empty_docstring();
280 for (size_t i = 0; i != label_.size(); ++i) {
282 label_[i]->updateBuffer(it, utype);
285 InsetMathGrid::updateBuffer(it, utype);
289 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active) const
292 //FIXME: buffer_ should be set at creation for this inset! Problem is
293 // This inset is created at too many places (see Parser::parse1() in
298 Toc & toc = buffer().tocBackend().toc("equation");
300 for (row_type row = 0; row != nrows(); ++row) {
304 label_[row]->addToToc(pit, output_active);
305 toc.push_back(TocItem(pit, 0, nicelabel(row), output_active));
310 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
316 return InsetMathNest::editXY(cur, x, y);
320 InsetMath::mode_type InsetMathHull::currentMode() const
322 if (type_ == hullNone)
323 return UNDECIDED_MODE;
324 // definitely math mode ...
329 bool InsetMathHull::idxFirst(Cursor & cur) const
337 bool InsetMathHull::idxLast(Cursor & cur) const
339 cur.idx() = nargs() - 1;
340 cur.pos() = cur.lastpos();
345 char InsetMathHull::defaultColAlign(col_type col)
347 if (type_ == hullEqnArray)
349 if (type_ == hullMultline)
351 if (type_ == hullGather)
353 if (type_ >= hullAlign)
354 return "rl"[col & 1];
359 char InsetMathHull::displayColAlign(idx_type idx) const
361 if (type_ == hullMultline) {
362 row_type const r = row(idx);
365 if (r == nrows() - 1)
368 return InsetMathGrid::displayColAlign(idx);
372 int InsetMathHull::defaultColSpace(col_type col)
374 if (type_ == hullAlign || type_ == hullAlignAt)
376 if (type_ == hullXAlignAt)
377 return (col & 1) ? 20 : 0;
378 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
379 return (col & 1) ? 40 : 0;
384 docstring InsetMathHull::standardFont() const
389 font_name = from_ascii("texttt");
392 font_name = from_ascii("lyxnochange");
395 font_name = from_ascii("mathnormal");
401 ColorCode InsetMathHull::standardColor() const
407 color = Color_foreground;
416 bool InsetMathHull::previewState(const BufferView *const bv) const
418 if (!editing(bv) && RenderPreview::previewMath()
419 && type_ != hullRegexp)
421 graphics::PreviewImage const * pimage =
422 preview_->getPreviewImage(bv->buffer());
423 return pimage && pimage->image();
430 static const int ERROR_FRAME_WIDTH = 2;
433 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
435 if (previewState(mi.base.bv)) {
436 preview_->metrics(mi, dim);
437 if (previewTooSmall(dim)) {
438 // preview image is too small
439 dim.wid += 2 * ERROR_FRAME_WIDTH;
440 dim.asc += 2 * ERROR_FRAME_WIDTH;
442 // insert a one pixel gap in front of the formula
445 dim.des += displayMargin();
447 // Cache the inset dimension.
448 setDimCache(mi, dim);
452 FontSetChanger dummy1(mi.base, standardFont());
453 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
455 // let the cells adjust themselves
456 InsetMathGrid::metrics(mi, dim);
459 dim.asc += displayMargin();
460 dim.des += displayMargin();
463 if (numberedType()) {
464 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
466 for (row_type row = 0; row < nrows(); ++row)
467 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
473 if (type_ == hullRegexp)
475 // make it at least as high as the current font
478 math_font_max_dim(mi.base.font, asc, des);
479 dim.asc = max(dim.asc, asc);
480 dim.des = max(dim.des, des);
481 // Cache the inset dimension.
482 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
483 setDimCache(mi, dim);
487 bool InsetMathHull::previewTooSmall(Dimension const & dim) const
489 return dim.width() <= 10 && dim.height() <= 10;
493 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
495 BufferView const * const bv = pi.base.bv;
496 if (previewState(bv)) {
497 Dimension const dim = dimension(*pi.base.bv);
498 if (previewTooSmall(dim))
500 return graphics::PreviewLoader::backgroundColor();
506 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
508 Dimension const dim = dimension(*pi.base.bv);
509 if (previewTooSmall(dim)) {
510 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
511 dim.wid, dim.asc + dim.des, backgroundColor(pi));
514 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
515 dim.asc + dim.des - 1, pi.backgroundColor(this));
519 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
521 BufferView const * const bv = pi.base.bv;
522 use_preview_ = previewState(bv);
524 if (type_ == hullRegexp) {
525 Dimension const dim = dimension(*bv);
526 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
527 dim.width() - 2, dim.height() - 2, Color_regexpframe);
531 Dimension const dim = dimension(*bv);
532 if (previewTooSmall(dim)) {
533 // we have an extra frame
534 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
536 // one pixel gap in front
537 preview_->draw(pi, x + 1, y);
539 setPosCache(pi, x, y);
543 ColorCode color = pi.selected && lyxrc.use_system_colors
544 ? Color_selectiontext : standardColor();
545 bool const really_change_color = pi.base.font.color() == Color_none;
546 ColorChanger dummy0(pi.base.font, color, really_change_color);
547 FontSetChanger dummy1(pi.base, standardFont());
548 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
550 InsetMathGrid::draw(pi, x + 1, y);
552 if (numberedType()) {
553 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
554 for (row_type row = 0; row < nrows(); ++row) {
555 int const yy = y + rowinfo_[row].offset_;
556 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
557 docstring const nl = nicelabel(row);
561 setPosCache(pi, x, y);
565 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
568 InsetMathGrid::metricsT(mi, dim);
571 WriteStream wi(os, false, true, WriteStream::wsDefault);
573 dim.wid = os.str().size();
580 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
583 InsetMathGrid::drawT(pain, x, y);
586 WriteStream wi(os, false, true, WriteStream::wsDefault);
588 pain.draw(x, y, os.str().c_str());
593 static docstring latexString(InsetMathHull const & inset)
596 // This has to be static, because a preview snippet or a math
597 // macro containing math in text mode (such as $\text{$\phi$}$ or
598 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
599 // first time as a whole, and the second time only the inner math.
600 // In this last case inset.buffer() would be invalid.
601 static Encoding const * encoding = 0;
602 if (inset.isBufferValid())
603 encoding = &(inset.buffer().params().encoding());
604 WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
610 void InsetMathHull::initUnicodeMath() const
612 // Trigger classification of the unicode symbols in this inset
613 docstring const dummy = latexString(*this);
617 void InsetMathHull::addPreview(DocIterator const & inset_pos,
618 graphics::PreviewLoader & /*ploader*/) const
620 if (RenderPreview::previewMath()) {
621 preparePreview(inset_pos);
626 void InsetMathHull::preparePreview(DocIterator const & pos,
627 bool forexport) const
629 // there is no need to do all the macro stuff if we're not
630 // actually going to generate the preview.
631 if (!RenderPreview::previewMath() && !forexport)
634 Buffer const * buffer = pos.buffer();
636 // collect macros at this position
638 buffer->listMacroNames(macros);
639 MacroNameSet::iterator it = macros.begin();
640 MacroNameSet::iterator end = macros.end();
641 odocstringstream macro_preamble;
642 for (; it != end; ++it) {
643 MacroData const * data = buffer->getMacro(*it, pos, true);
645 data->write(macro_preamble, true);
646 macro_preamble << endl;
651 if (forexport && haveNumbers()) {
652 docstring eqstr = from_ascii("equation");
653 CounterMap::const_iterator it = counter_map.find(eqstr);
654 if (it != counter_map.end()) {
655 int num = it->second;
657 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
658 '{' + convert<docstring>(num) + '}' + '\n';
660 for (size_t i = 0; i != numcnts; ++i) {
661 docstring cnt = from_ascii(counters_to_save[i]);
662 it = counter_map.find(cnt);
663 if (it == counter_map.end())
665 int num = it->second;
667 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
668 '{' + convert<docstring>(num) + '}';
671 docstring const snippet = macro_preamble.str() +
672 setcnt + latexString(*this);
673 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
674 preview_->addPreview(snippet, *buffer, forexport);
678 void InsetMathHull::reloadPreview(DocIterator const & pos) const
681 preview_->startLoading(*pos.buffer());
685 void InsetMathHull::loadPreview(DocIterator const & pos) const
687 bool const forexport = true;
688 preparePreview(pos, forexport);
689 preview_->startLoading(*pos.buffer(), forexport);
693 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
695 if (RenderPreview::previewMath()) {
697 cur.screenUpdateFlags(Update::Force);
703 docstring InsetMathHull::label(row_type row) const
705 LASSERT(row < nrows(), return docstring());
706 if (InsetLabel * il = label_[row])
707 return il->screenLabel();
712 void InsetMathHull::label(row_type row, docstring const & label)
714 //lyxerr << "setting label '" << label << "' for row " << row << endl;
718 label_[row] = dummy_pointer;
721 label_[row]->updateLabelAndRefs(label);
723 label_[row]->setParam("name", label);
727 InsetCommandParams p(LABEL_CODE);
729 label_[row] = new InsetLabel(buffer_, p);
731 label_[row]->setBuffer(buffer());
735 void InsetMathHull::numbered(row_type row, Numbered num)
737 numbered_[row] = num;
738 if (!numbered(row) && label_[row]) {
745 bool InsetMathHull::numbered(row_type row) const
747 return numbered_[row] == NUMBER;
751 bool InsetMathHull::ams() const
769 for (size_t row = 0; row < numbered_.size(); ++row)
770 if (numbered_[row] == NOTAG)
776 Inset::DisplayType InsetMathHull::display() const
778 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
783 bool InsetMathHull::numberedType() const
785 if (type_ == hullNone)
787 if (type_ == hullSimple)
789 if (type_ == hullXXAlignAt)
791 if (type_ == hullRegexp)
793 for (row_type row = 0; row < nrows(); ++row)
800 void InsetMathHull::validate(LaTeXFeatures & features) const
802 if (features.runparams().isLaTeX()) {
804 features.require("amsmath");
806 if (type_ == hullRegexp) {
807 features.require("color");
808 string frcol = lcolor.getLaTeXName(Color_regexpframe);
809 string bgcol = "white";
810 features.addPreambleSnippet(
811 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
812 + frcol + string("}{")
813 + bgcol + string("}{\\ensuremath{\\mathtt{#1}}}}"));
814 features.addPreambleSnippet(
815 string("\\newcommand{\\endregexp}{}"));
818 // Validation is necessary only if not using AMS math.
819 // To be safe, we will always run mathedvalidate.
820 //if (features.amsstyle)
823 //features.binom = true;
824 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
825 // it would be better to do this elsewhere, but we can't validate in
826 // InsetMathMatrix and we have no way, outside MathExtern, to know if
827 // we even have any matrices.
828 features.addCSSSnippet(
829 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
830 "table.matrix td{padding: 0.25px;}\n"
831 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
832 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
834 InsetMathGrid::validate(features);
838 void InsetMathHull::header_write(WriteStream & os) const
840 bool n = numberedType();
854 os << "\n\\begin{equation" << star(n) << "}\n";
864 os << "\n\\begin{" << hullName(type_) << star(n) << "}\n";
869 os << "\n\\begin{" << hullName(type_) << star(n) << '}'
870 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
874 os << "\n\\begin{" << hullName(type_) << '}'
875 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
883 os << "\n\\begin{unknown" << star(n) << "}\n";
889 void InsetMathHull::footer_write(WriteStream & os) const
891 bool n = numberedType();
904 os << "\n\\end{equation" << star(n) << "}\n";
916 os << "\n\\end{" << hullName(type_) << star(n) << "}\n";
920 os << "\n\\end{" << hullName(type_) << "}\n";
924 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
925 os << "\\endregexp{}}";
929 os << "\n\\end{unknown" << star(n) << "}\n";
935 bool InsetMathHull::rowChangeOK() const
938 type_ == hullEqnArray || type_ == hullAlign ||
939 type_ == hullFlAlign || type_ == hullAlignAt ||
940 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
941 type_ == hullGather || type_ == hullMultline;
945 bool InsetMathHull::colChangeOK() const
948 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
949 type_ == hullXAlignAt || type_ == hullXXAlignAt;
953 void InsetMathHull::addRow(row_type row)
958 bool numbered = numberedType();
959 // Move the number and raw pointer, do not call label() (bug 7511)
960 InsetLabel * label = dummy_pointer;
961 docstring number = empty_docstring();
962 if (type_ == hullMultline) {
963 if (row + 1 == nrows()) {
964 numbered_[row] = NONUMBER;
965 swap(label, label_[row]);
966 swap(number, numbers_[row]);
971 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
972 numbers_.insert(numbers_.begin() + row + 1, number);
973 label_.insert(label_.begin() + row + 1, label);
974 InsetMathGrid::addRow(row);
978 void InsetMathHull::swapRow(row_type row)
982 if (row + 1 == nrows())
984 swap(numbered_[row], numbered_[row + 1]);
985 swap(numbers_[row], numbers_[row + 1]);
986 swap(label_[row], label_[row + 1]);
987 InsetMathGrid::swapRow(row);
991 void InsetMathHull::delRow(row_type row)
993 if (nrows() <= 1 || !rowChangeOK())
995 if (row + 1 == nrows() && type_ == hullMultline) {
996 swap(numbered_[row - 1], numbered_[row]);
997 swap(numbers_[row - 1], numbers_[row]);
998 swap(label_[row - 1], label_[row]);
999 InsetMathGrid::delRow(row);
1002 InsetMathGrid::delRow(row);
1003 // The last dummy row has no number info nor a label.
1004 // Test nrows() + 1 because we have already erased the row.
1005 if (row == nrows() + 1)
1007 numbered_.erase(numbered_.begin() + row);
1008 numbers_.erase(numbers_.begin() + row);
1010 label_.erase(label_.begin() + row);
1014 void InsetMathHull::addCol(col_type col)
1018 InsetMathGrid::addCol(col);
1022 void InsetMathHull::delCol(col_type col)
1024 if (ncols() <= 1 || !colChangeOK())
1026 InsetMathGrid::delCol(col);
1030 docstring InsetMathHull::nicelabel(row_type row) const
1034 docstring const & val = numbers_[row];
1036 return '(' + val + ')';
1037 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1041 void InsetMathHull::glueall(HullType type)
1044 for (idx_type i = 0; i < nargs(); ++i)
1046 InsetLabel * label = 0;
1047 if (type == hullEquation) {
1048 // preserve first non-empty label
1049 for (row_type row = 0; row < nrows(); ++row) {
1051 label = label_[row];
1057 *this = InsetMathHull(buffer_, hullSimple);
1064 void InsetMathHull::splitTo2Cols()
1066 LASSERT(ncols() == 1, return);
1067 InsetMathGrid::addCol(1);
1068 for (row_type row = 0; row < nrows(); ++row) {
1069 idx_type const i = 2 * row;
1070 pos_type pos = firstRelOp(cell(i));
1071 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1072 cell(i).erase(pos, cell(i).size());
1077 void InsetMathHull::splitTo3Cols()
1079 LASSERT(ncols() < 3, return);
1082 InsetMathGrid::addCol(2);
1083 for (row_type row = 0; row < nrows(); ++row) {
1084 idx_type const i = 3 * row + 1;
1085 if (!cell(i).empty()) {
1086 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1087 cell(i).erase(1, cell(i).size());
1093 void InsetMathHull::changeCols(col_type cols)
1095 if (ncols() == cols)
1097 else if (ncols() < cols) {
1103 while (ncols() < cols)
1104 InsetMathGrid::addCol(ncols());
1110 for (row_type row = 0; row < nrows(); ++row) {
1111 idx_type const i = row * ncols();
1112 for (col_type col = cols; col < ncols(); ++col) {
1113 cell(i + cols - 1).append(cell(i + col));
1117 while (ncols() > cols) {
1118 InsetMathGrid::delCol(ncols() - 1);
1123 HullType InsetMathHull::getType() const
1129 void InsetMathHull::setType(HullType type)
1136 void InsetMathHull::mutate(HullType newtype)
1138 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1140 // we try to move along the chain
1141 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1143 // +-------------------------------------+
1144 // we use eqnarray as intermediate type for mutations that are not
1145 // directly supported because it handles labels and numbering for
1148 if (newtype == type_) {
1152 else if (newtype < hullNone) {
1157 else if (type_ == hullNone) {
1158 setType(hullSimple);
1163 else if (type_ == hullSimple) {
1164 if (newtype == hullNone) {
1168 setType(hullEquation);
1169 numbered(0, label_[0] ? true : false);
1174 else if (type_ == hullEquation) {
1175 if (newtype < type_) {
1176 setType(hullSimple);
1179 } else if (newtype == hullEqnArray) {
1180 // split it "nicely" on the first relop
1182 setType(hullEqnArray);
1183 } else if (newtype == hullMultline || newtype == hullGather) {
1186 // split it "nicely"
1193 else if (type_ == hullEqnArray) {
1194 if (newtype < type_) {
1197 } else { // align & Co.
1204 else if (type_ == hullAlign || type_ == hullAlignAt ||
1205 type_ == hullXAlignAt || type_ == hullFlAlign) {
1206 if (newtype < hullAlign) {
1208 setType(hullEqnArray);
1210 } else if (newtype == hullGather || newtype == hullMultline) {
1213 } else if (newtype == hullXXAlignAt) {
1214 for (row_type row = 0; row < nrows(); ++row)
1215 numbered(row, false);
1222 else if (type_ == hullXXAlignAt) {
1223 for (row_type row = 0; row < nrows(); ++row)
1224 numbered(row, false);
1225 if (newtype < hullAlign) {
1227 setType(hullEqnArray);
1229 } else if (newtype == hullGather || newtype == hullMultline) {
1237 else if (type_ == hullMultline || type_ == hullGather) {
1238 if (newtype == hullGather || newtype == hullMultline)
1240 else if (newtype == hullAlign || newtype == hullFlAlign ||
1241 newtype == hullAlignAt || newtype == hullXAlignAt) {
1244 } else if (newtype == hullXXAlignAt) {
1246 for (row_type row = 0; row < nrows(); ++row)
1247 numbered(row, false);
1251 setType(hullEqnArray);
1257 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1258 << "' to '" << to_utf8(hullName(newtype))
1259 << "' not implemented" << endl;
1264 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1265 bool last_eoln) const
1268 if (numberedType()) {
1269 if (label_[row] && numbered(row)) {
1270 docstring const name =
1271 latex ? escape(label_[row]->getParam("name"))
1272 : label_[row]->getParam("name");
1273 res += "\\label{" + name + '}';
1275 if (type_ != hullMultline) {
1276 if (numbered_[row] == NONUMBER)
1277 res += "\\nonumber ";
1278 else if (numbered_[row] == NOTAG)
1282 // Never add \\ on the last empty line of eqnarray and friends
1284 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1288 void InsetMathHull::write(WriteStream & os) const
1290 ModeSpecifier specifier(os, MATH_MODE);
1292 InsetMathGrid::write(os);
1297 void InsetMathHull::normalize(NormalStream & os) const
1299 os << "[formula " << hullName(type_) << ' ';
1300 InsetMathGrid::normalize(os);
1305 void InsetMathHull::infoize(odocstream & os) const
1307 os << bformat(_("Type: %1$s"), hullName(type_));
1311 void InsetMathHull::check() const
1313 LATTEST(numbered_.size() == nrows());
1314 LATTEST(numbers_.size() == nrows());
1315 LATTEST(label_.size() == nrows());
1319 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1323 idocstringstream iss(func.argument());
1324 iss >> dlang >> extra;
1326 extra = from_ascii("noextra");
1327 string const lang = to_ascii(dlang);
1329 // replace selection with result of computation
1330 if (reduceSelectionToOneCell(cur)) {
1332 asArray(grabAndEraseSelection(cur), ar);
1333 lyxerr << "use selection: " << ar << endl;
1334 cur.insert(pipeThroughExtern(lang, extra, ar));
1338 // only inline, display or eqnarray math is allowed
1339 if (getType() > hullEqnArray) {
1340 frontend::Alert::warning(_("Bad math environment"),
1341 _("Computation cannot be performed for AMS "
1342 "math environments.\nChange the math "
1343 "formula type and try again."));
1348 eq.push_back(MathAtom(new InsetMathChar('=')));
1350 // go to first item in line
1351 cur.idx() -= cur.idx() % ncols();
1354 if (getType() == hullSimple) {
1355 size_type pos = cur.cell().find_last(eq);
1357 if (pos == cur.cell().size()) {
1359 lyxerr << "use whole cell: " << ar << endl;
1361 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1362 lyxerr << "use partial cell form pos: " << pos << endl;
1364 cur.cell().append(eq);
1365 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1366 cur.pos() = cur.lastpos();
1370 if (getType() == hullEquation) {
1371 lyxerr << "use equation inset" << endl;
1372 mutate(hullEqnArray);
1373 MathData & ar = cur.cell();
1374 lyxerr << "use cell: " << ar << endl;
1378 cur.cell() = pipeThroughExtern(lang, extra, ar);
1379 // move to end of line
1380 cur.pos() = cur.lastpos();
1385 lyxerr << "use eqnarray" << endl;
1386 cur.idx() += 2 - cur.idx() % ncols();
1388 MathData ar = cur.cell();
1389 lyxerr << "use cell: " << ar << endl;
1390 // FIXME: temporarily disabled
1396 cur.cell() = pipeThroughExtern(lang, extra, ar);
1397 cur.pos() = cur.lastpos();
1402 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1404 //lyxerr << "action: " << cmd.action() << endl;
1405 switch (cmd.action()) {
1407 case LFUN_FINISHED_BACKWARD:
1408 case LFUN_FINISHED_FORWARD:
1409 case LFUN_FINISHED_RIGHT:
1410 case LFUN_FINISHED_LEFT:
1411 //lyxerr << "action: " << cmd.action() << endl;
1412 InsetMathGrid::doDispatch(cur, cmd);
1415 case LFUN_PARAGRAPH_BREAK:
1416 // just swallow this
1419 case LFUN_NEWLINE_INSERT:
1420 // some magic for the common case
1421 if (type_ == hullSimple || type_ == hullEquation) {
1422 cur.recordUndoInset();
1424 cur.bv().buffer().params().use_package("amsmath") == BufferParams::package_on;
1425 mutate(align ? hullAlign : hullEqnArray);
1426 // mutate() may change labels and such.
1427 cur.forceBufferUpdate();
1428 cur.idx() = nrows() * ncols() - 1;
1429 cur.pos() = cur.lastpos();
1431 InsetMathGrid::doDispatch(cur, cmd);
1434 case LFUN_MATH_NUMBER_TOGGLE: {
1435 //lyxerr << "toggling all numbers" << endl;
1436 cur.recordUndoInset();
1437 bool old = numberedType();
1438 if (type_ == hullMultline)
1439 numbered(nrows() - 1, !old);
1441 for (row_type row = 0; row < nrows(); ++row)
1442 numbered(row, !old);
1444 cur.message(old ? _("No number") : _("Number"));
1445 cur.forceBufferUpdate();
1449 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1450 cur.recordUndoInset();
1451 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1452 bool old = numbered(r);
1453 cur.message(old ? _("No number") : _("Number"));
1455 cur.forceBufferUpdate();
1459 case LFUN_LABEL_INSERT: {
1460 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1461 docstring old_label = label(r);
1462 docstring const default_label = from_ascii("eq:");
1463 if (old_label.empty())
1464 old_label = default_label;
1466 InsetCommandParams p(LABEL_CODE);
1467 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1468 string const data = InsetCommand::params2string(p);
1470 if (cmd.argument().empty())
1471 cur.bv().showDialog("label", data);
1473 FuncRequest fr(LFUN_INSET_INSERT, data);
1479 case LFUN_LABEL_COPY_AS_REFERENCE: {
1481 if (cmd.argument().empty() && &cur.inset() == this)
1482 // if there is no argument and we're inside math, we retrieve
1483 // the row number from the cursor position.
1484 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1486 // if there is an argument, find the corresponding label, else
1487 // check whether there is at least one label.
1488 for (row = 0; row != nrows(); ++row)
1489 if (numbered(row) && label_[row]
1490 && (cmd.argument().empty() || label(row) == cmd.argument()))
1497 InsetCommandParams p(REF_CODE, "ref");
1498 p["reference"] = label(row);
1499 cap::clearSelection();
1500 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1504 case LFUN_WORD_DELETE_FORWARD:
1505 case LFUN_CHAR_DELETE_FORWARD:
1506 if (col(cur.idx()) + 1 == ncols()
1507 && cur.pos() == cur.lastpos()
1508 && !cur.selection()) {
1509 if (!label(row(cur.idx())).empty()) {
1510 cur.recordUndoInset();
1511 label(row(cur.idx()), docstring());
1512 } else if (numbered(row(cur.idx()))) {
1513 cur.recordUndoInset();
1514 numbered(row(cur.idx()), false);
1515 cur.forceBufferUpdate();
1517 InsetMathGrid::doDispatch(cur, cmd);
1521 InsetMathGrid::doDispatch(cur, cmd);
1526 case LFUN_INSET_INSERT: {
1527 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1528 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1529 string const name = cmd.getArg(0);
1530 if (name == "label") {
1531 InsetCommandParams p(LABEL_CODE);
1532 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1533 docstring str = p["name"];
1534 cur.recordUndoInset();
1535 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1539 docstring old = label(r);
1542 // The label will take care of the reference update.
1546 // Newly created inset so initialize it.
1547 label_[r]->initView();
1550 cur.forceBufferUpdate();
1553 InsetMathGrid::doDispatch(cur, cmd);
1557 case LFUN_MATH_EXTERN:
1558 cur.recordUndoInset();
1562 case LFUN_MATH_MUTATE: {
1563 cur.recordUndoInset();
1564 row_type row = cur.row();
1565 col_type col = cur.col();
1566 mutate(hullType(cmd.argument()));
1567 cur.idx() = row * ncols() + col;
1568 if (cur.idx() > cur.lastidx()) {
1569 cur.idx() = cur.lastidx();
1570 cur.pos() = cur.lastpos();
1572 if (cur.pos() > cur.lastpos())
1573 cur.pos() = cur.lastpos();
1575 cur.forceBufferUpdate();
1576 // FIXME: find some more clever handling of the selection,
1577 // i.e. preserve it.
1578 cur.clearSelection();
1579 //cur.dispatched(FINISHED);
1583 case LFUN_MATH_DISPLAY: {
1584 cur.recordUndoInset();
1585 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1587 cur.pos() = cur.lastpos();
1588 //cur.dispatched(FINISHED);
1593 InsetMathGrid::doDispatch(cur, cmd);
1599 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1600 FuncStatus & status) const
1602 switch (cmd.action()) {
1603 case LFUN_FINISHED_BACKWARD:
1604 case LFUN_FINISHED_FORWARD:
1605 case LFUN_FINISHED_RIGHT:
1606 case LFUN_FINISHED_LEFT:
1609 case LFUN_NEWLINE_INSERT:
1610 case LFUN_MATH_EXTERN:
1612 status.setEnabled(true);
1615 // we never allow this in math, and we want to bind enter
1616 // to another actions in command-alternatives
1617 case LFUN_PARAGRAPH_BREAK:
1618 status.setEnabled(false);
1620 case LFUN_MATH_MUTATE: {
1621 HullType const ht = hullType(cmd.argument());
1622 status.setOnOff(type_ == ht);
1623 status.setEnabled(true);
1625 if (ht != hullSimple) {
1626 Cursor tmpcur = cur;
1627 while (!tmpcur.empty()) {
1628 InsetCode code = tmpcur.inset().lyxCode();
1629 if (code == BOX_CODE) {
1631 } else if (code == TABULAR_CODE) {
1632 FuncRequest tmpcmd(LFUN_MATH_DISPLAY);
1633 if (tmpcur.getStatus(tmpcmd, status) && !status.enabled())
1641 case LFUN_MATH_DISPLAY: {
1643 if (cur.depth() > 1) {
1644 Inset const & in = cur[cur.depth()-2].inset();
1645 if (in.lyxCode() == SCRIPT_CODE)
1646 enable = display() != Inline;
1648 status.setEnabled(enable);
1649 status.setOnOff(display() != Inline);
1653 case LFUN_MATH_NUMBER_TOGGLE:
1654 // FIXME: what is the right test, this or the one of
1656 status.setEnabled(display() != Inline);
1657 status.setOnOff(numberedType());
1660 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1661 // FIXME: what is the right test, this or the one of
1663 bool const enable = (type_ == hullMultline)
1664 ? (nrows() - 1 == cur.row())
1665 : display() != Inline;
1666 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1667 status.setEnabled(enable);
1668 status.setOnOff(enable && numbered(r));
1672 case LFUN_LABEL_INSERT:
1673 status.setEnabled(type_ != hullSimple);
1676 case LFUN_LABEL_COPY_AS_REFERENCE: {
1677 bool enabled = false;
1679 if (cmd.argument().empty() && &cur.inset() == this) {
1680 // if there is no argument and we're inside math, we retrieve
1681 // the row number from the cursor position.
1682 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1683 enabled = numberedType() && label_[row] && numbered(row);
1685 // if there is an argument, find the corresponding label, else
1686 // check whether there is at least one label.
1687 for (row_type row = 0; row != nrows(); ++row) {
1688 if (numbered(row) && label_[row] &&
1689 (cmd.argument().empty() || label(row) == cmd.argument())) {
1695 status.setEnabled(enabled);
1699 case LFUN_INSET_INSERT:
1700 if (cmd.getArg(0) == "label") {
1701 status.setEnabled(type_ != hullSimple);
1704 return InsetMathGrid::getStatus(cur, cmd, status);
1706 case LFUN_INSET_MODIFY: {
1707 istringstream is(to_utf8(cmd.argument()));
1711 return InsetMathGrid::getStatus(cur, cmd, status);
1714 && (s == "append-row"
1715 || s == "delete-row"
1716 || s == "copy-row")) {
1717 status.message(bformat(
1718 from_utf8(N_("Can't change number of rows in '%1$s'")),
1720 status.setEnabled(false);
1724 && (s == "append-column"
1725 || s == "delete-column"
1726 || s == "copy-column")) {
1727 status.message(bformat(
1728 from_utf8(N_("Can't change number of columns in '%1$s'")),
1730 status.setEnabled(false);
1733 if ((type_ == hullSimple
1734 || type_ == hullEquation
1735 || type_ == hullNone) &&
1736 (s == "add-hline-above" || s == "add-hline-below")) {
1737 status.message(bformat(
1738 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1740 status.setEnabled(false);
1743 if (s == "add-vline-left" || s == "add-vline-right") {
1744 status.message(bformat(
1745 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1747 status.setEnabled(false);
1750 if (s == "valign-top" || s == "valign-middle"
1751 || s == "valign-bottom" || s == "align-left"
1752 || s == "align-center" || s == "align-right") {
1753 status.setEnabled(false);
1756 return InsetMathGrid::getStatus(cur, cmd, status);
1760 return InsetMathGrid::getStatus(cur, cmd, status);
1763 // This cannot really happen, but inserted to shut-up gcc
1764 return InsetMathGrid::getStatus(cur, cmd, status);
1768 /////////////////////////////////////////////////////////////////////
1772 // simply scrap this function if you want
1773 void InsetMathHull::mutateToText()
1776 // translate to latex
1778 latex(os, false, false);
1779 string str = os.str();
1782 Text * lt = view_->cursor().innerText();
1783 string::const_iterator cit = str.begin();
1784 string::const_iterator end = str.end();
1785 for (; cit != end; ++cit)
1786 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1789 //dispatch(LFUN_ESCAPE);
1794 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1795 docstring const & font)
1797 // this whole function is a hack and won't work for incremental font
1800 if (cur.inset().asInsetMath()->name() == font)
1801 cur.handleFont(to_utf8(font));
1803 cur.handleNest(createInsetMath(font, cur.buffer()));
1809 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1814 font.fromString(to_utf8(arg), b);
1815 if (font.fontInfo().color() != Color_inherit) {
1816 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1817 cur.handleNest(at, 0);
1822 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1825 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1826 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1827 enter_front ? idxFirst(cur) : idxLast(cur);
1828 // The inset formula dimension is not necessarily the same as the
1829 // one of the instant preview image, so we have to indicate to the
1830 // BufferView that a metrics update is needed.
1831 cur.screenUpdateFlags(Update::Force);
1835 void InsetMathHull::revealCodes(Cursor & cur) const
1837 if (!cur.inMathed())
1839 odocstringstream os;
1841 cur.message(os.str());
1843 // write something to the minibuffer
1844 // translate to latex
1848 string str = os.str();
1850 string::size_type pos = 0;
1852 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1855 else if (*it == '\0') {
1857 pos = it - str.begin();
1863 res = res.substr(pos - 30);
1864 if (res.size() > 60)
1865 res = res.substr(0, 60);
1871 /////////////////////////////////////////////////////////////////////
1875 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1878 // FIXME: completely broken
1879 static InsetMathHull * lastformula = 0;
1880 static CursorBase current = DocIterator(ibegin(nucleus()));
1882 static string laststr;
1884 if (lastformula != this || laststr != str) {
1885 //lyxerr << "reset lastformula to " << this << endl;
1888 current = ibegin(nucleus());
1890 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1894 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1896 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1897 CursorSlice & top = it.back();
1898 MathData const & a = top.asInsetMath()->cell(top.idx_);
1899 if (a.matchpart(ar, top.pos_)) {
1900 bv->cursor().setSelection(it, ar.size());
1902 top.pos_ += ar.size();
1908 //lyxerr << "not found!" << endl;
1915 void InsetMathHull::write(ostream & os) const
1917 odocstringstream oss;
1918 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1921 os << to_utf8(oss.str());
1925 void InsetMathHull::read(Lexer & lex)
1928 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1929 operator=(*at->asHullInset());
1933 bool InsetMathHull::readQuiet(Lexer & lex)
1936 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1938 operator=(*at->asHullInset());
1943 int InsetMathHull::plaintext(odocstringstream & os,
1944 OutputParams const & op, size_t max_length) const
1946 // disables ASCII-art for export of equations. See #2275.
1947 if (0 && display()) {
1951 TextPainter tpain(dim.width(), dim.height());
1952 drawT(tpain, 0, dim.ascent());
1954 // reset metrics cache to "real" values
1956 return tpain.textheight();
1959 odocstringstream oss;
1960 Encoding const * const enc = encodings.fromLyXName("utf8");
1961 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1964 if (type_ == hullRegexp)
1967 for (row_type r = 0; r < nrows(); ++r) {
1968 for (col_type c = 0; c < ncols(); ++c)
1969 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
1970 // if it's for the TOC, we write just the first line
1971 // and do not include the newline.
1972 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
1974 if (r < nrows() - 1)
1978 docstring const str = oss.str();
1984 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1989 if (getType() == hullSimple)
1990 name = from_ascii("inlineequation");
1992 name = from_ascii("informalequation");
1994 docstring bname = name;
1995 if (!label(0).empty())
1996 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1998 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
2000 odocstringstream ls;
2001 if (runparams.flavor == OutputParams::XML) {
2002 ms << MTag("alt role='tex' ");
2003 // Workaround for db2latex: db2latex always includes equations with
2004 // \ensuremath{} or \begin{display}\end{display}
2005 // so we strip LyX' math environment
2006 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
2007 InsetMathGrid::write(wi);
2008 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2013 InsetMathGrid::mathmlize(ms);
2018 otexstream ols(ls, texrow);
2019 ms << MTag("alt role='tex'");
2020 latex(ols, runparams);
2021 res = texrow.rows();
2022 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2026 ms << from_ascii("<graphic fileref=\"eqn/");
2027 if (!label(0).empty())
2028 ms << sgml::cleanID(buffer(), runparams, label(0));
2030 ms << sgml::uniqueID(from_ascii("anon"));
2032 if (runparams.flavor == OutputParams::XML)
2033 ms << from_ascii("\"/>");
2035 ms << from_ascii("\">");
2037 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2039 return ms.line() + res;
2043 bool InsetMathHull::haveNumbers() const
2045 bool havenumbers = false;
2046 // inline formulas are never numbered (bug 7351 part 3)
2047 if (getType() == hullSimple)
2049 for (size_t i = 0; i != numbered_.size(); ++i) {
2060 // We need to do something about alignment here.
2062 // This duplicates code from InsetMathGrid, but
2063 // we need access here to number information,
2064 // and we simply do not have that in InsetMathGrid.
2065 void InsetMathHull::htmlize(HtmlStream & os) const
2067 bool const havenumbers = haveNumbers();
2068 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2071 os << cell(index(0, 0));
2075 os << MTag("table", "class='mathtable'");
2076 for (row_type row = 0; row < nrows(); ++row) {
2078 for (col_type col = 0; col < ncols(); ++col) {
2080 os << cell(index(row, col));
2085 docstring const & num = numbers_[row];
2087 os << '(' << num << ')';
2092 os << ETag("table");
2096 // this duplicates code from InsetMathGrid, but
2097 // we need access here to number information,
2098 // and we simply do not have that in InsetMathGrid.
2099 void InsetMathHull::mathmlize(MathStream & os) const
2101 bool const havenumbers = haveNumbers();
2102 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2105 os << MTag("mtable");
2106 char const * const celltag = havetable ? "mtd" : "mrow";
2107 // FIXME There does not seem to be wide support at the moment
2108 // for mlabeledtr, so we have to use just mtr for now.
2109 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2110 char const * const rowtag = "mtr";
2111 for (row_type row = 0; row < nrows(); ++row) {
2114 for (col_type col = 0; col < ncols(); ++col) {
2116 << cell(index(row, col))
2122 docstring const & num = numbers_[row];
2124 os << '(' << num << ')';
2131 os << ETag("mtable");
2135 void InsetMathHull::mathAsLatex(WriteStream & os) const
2137 MathEnsurer ensurer(os, false);
2138 bool havenumbers = haveNumbers();
2139 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2142 os << cell(index(0, 0));
2146 os << "<table class='mathtable'>";
2147 for (row_type row = 0; row < nrows(); ++row) {
2149 for (col_type col = 0; col < ncols(); ++col) {
2150 os << "<td class='math'>";
2151 os << cell(index(row, col));
2156 docstring const & num = numbers_[row];
2158 os << '(' << num << ')';
2167 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2169 BufferParams::MathOutput const mathtype =
2170 buffer().masterBuffer()->params().html_math_output;
2172 bool success = false;
2174 // we output all the labels just at the beginning of the equation.
2175 // this should be fine.
2176 for (size_t i = 0; i != label_.size(); ++i) {
2177 InsetLabel const * const il = label_[i];
2183 // FIXME Eventually we would like to do this inset by inset.
2184 if (mathtype == BufferParams::MathML) {
2185 odocstringstream os;
2190 } catch (MathExportException const &) {}
2192 if (getType() == hullSimple)
2193 xs << html::StartTag("math",
2194 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2196 xs << html::StartTag("math",
2197 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2198 xs << XHTMLStream::ESCAPE_NONE
2200 << html::EndTag("math");
2202 } else if (mathtype == BufferParams::HTML) {
2203 odocstringstream os;
2208 } catch (MathExportException const &) {}
2210 string const tag = (getType() == hullSimple) ? "span" : "div";
2211 xs << html::StartTag(tag, "class='formula'", true)
2212 << XHTMLStream::ESCAPE_NONE
2214 << html::EndTag(tag);
2218 // what we actually want is this:
2220 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2222 // || mathtype == BufferParams::Images
2224 // but what follows is equivalent, since we'll enter only if either (a) we
2225 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2226 // aren't doing LaTeX, in which case we are doing Images.
2227 if (!success && mathtype != BufferParams::LaTeX) {
2228 graphics::PreviewImage const * pimage = 0;
2230 loadPreview(docit_);
2231 pimage = preview_->getPreviewImage(buffer());
2232 // FIXME Do we always have png?
2235 if (pimage || op.dryrun) {
2236 string const filename = pimage ? pimage->filename().onlyFileName()
2237 : "previewimage.png";
2239 // if we are not in the master buffer, then we need to see that the
2240 // generated image is copied there; otherwise, preview fails.
2241 Buffer const * mbuf = buffer().masterBuffer();
2242 if (mbuf != &buffer()) {
2243 string mbtmp = mbuf->temppath();
2244 FileName const mbufimg(support::addName(mbtmp, filename));
2245 pimage->filename().copyTo(mbufimg);
2247 // add the file to the list of files to be exported
2248 op.exportdata->addExternalFile("xhtml", pimage->filename());
2251 string const tag = (getType() == hullSimple) ? "span" : "div";
2253 << html::StartTag(tag)
2254 << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2255 << html::EndTag(tag)
2261 // so we'll pass this test if we've failed everything else, or
2262 // if mathtype was LaTeX, since we won't have entered any of the
2264 if (!success /* || mathtype != BufferParams::LaTeX */) {
2265 // Unfortunately, we cannot use latexString() because we do not want
2266 // $...$ or whatever.
2267 odocstringstream ls;
2268 WriteStream wi(ls, false, true, WriteStream::wsPreview);
2269 ModeSpecifier specifier(wi, MATH_MODE);
2271 docstring const latex = ls.str();
2273 // class='math' allows for use of jsMath
2274 // http://www.math.union.edu/~dpvc/jsMath/
2276 // probably should allow for some kind of customization here
2277 string const tag = (getType() == hullSimple) ? "span" : "div";
2278 xs << html::StartTag(tag, "class='math'")
2280 << html::EndTag(tag)
2287 void InsetMathHull::toString(odocstream & os) const
2289 odocstringstream ods;
2290 plaintext(ods, OutputParams(0));
2295 void InsetMathHull::forOutliner(docstring & os, size_t) const
2297 odocstringstream ods;
2305 string InsetMathHull::contextMenuName() const
2307 return "context-math";
2311 void InsetMathHull::recordLocation(DocIterator const & di)