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 "InsetMathFrac.h"
18 #include "InsetMathGrid.h"
19 #include "InsetMathNest.h"
20 #include "InsetMathScript.h"
21 #include "MathExtern.h"
22 #include "MathFactory.h"
23 #include "MathStream.h"
24 #include "MathSupport.h"
27 #include "BufferParams.h"
28 #include "BufferView.h"
30 #include "CutAndPaste.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
36 #include "LaTeXFeatures.h"
38 #include "MacroTable.h"
39 #include "MathMacro.h"
40 #include "MathMacroTemplate.h"
41 #include "output_xhtml.h"
42 #include "Paragraph.h"
43 #include "ParIterator.h"
45 #include "TextClass.h"
46 #include "TextPainter.h"
47 #include "TocBackend.h"
49 #include "insets/InsetLabel.h"
50 #include "insets/InsetRef.h"
51 #include "insets/RenderPreview.h"
53 #include "graphics/GraphicsImage.h"
54 #include "graphics/PreviewImage.h"
55 #include "graphics/PreviewLoader.h"
57 #include "frontends/alert.h"
58 #include "frontends/Painter.h"
60 #include "support/convert.h"
61 #include "support/lassert.h"
62 #include "support/debug.h"
63 #include "support/filetools.h"
64 #include "support/gettext.h"
65 #include "support/lstrings.h"
70 using namespace lyx::support;
74 using cap::grabAndEraseSelection;
75 using cap::reduceSelectionToOneCell;
79 int getCols(HullType type)
104 // returns position of first relation operator in the array
105 // used for "intelligent splitting"
106 size_t firstRelOp(MathData const & ar)
108 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
109 if ((*it)->isMathRel())
110 return it - ar.begin();
115 char const * star(bool numbered)
117 return numbered ? "" : "*";
121 } // end anon namespace
124 HullType hullType(docstring const & s)
126 if (s == "none") return hullNone;
127 if (s == "simple") return hullSimple;
128 if (s == "equation") return hullEquation;
129 if (s == "eqnarray") return hullEqnArray;
130 if (s == "align") return hullAlign;
131 if (s == "alignat") return hullAlignAt;
132 if (s == "xalignat") return hullXAlignAt;
133 if (s == "xxalignat") return hullXXAlignAt;
134 if (s == "multline") return hullMultline;
135 if (s == "gather") return hullGather;
136 if (s == "flalign") return hullFlAlign;
137 if (s == "regexp") return hullRegexp;
138 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
143 docstring hullName(HullType type)
146 case hullNone: return from_ascii("none");
147 case hullSimple: return from_ascii("simple");
148 case hullEquation: return from_ascii("equation");
149 case hullEqnArray: return from_ascii("eqnarray");
150 case hullAlign: return from_ascii("align");
151 case hullAlignAt: return from_ascii("alignat");
152 case hullXAlignAt: return from_ascii("xalignat");
153 case hullXXAlignAt: return from_ascii("xxalignat");
154 case hullMultline: return from_ascii("multline");
155 case hullGather: return from_ascii("gather");
156 case hullFlAlign: return from_ascii("flalign");
157 case hullRegexp: return from_ascii("regexp");
159 lyxerr << "unknown hull type" << endl;
162 return from_ascii("none");
165 static InsetLabel * dummy_pointer = 0;
167 InsetMathHull::InsetMathHull(Buffer * buf)
168 : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, NUMBER),
169 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
170 preview_(new RenderPreview(this))
172 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
173 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
174 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
175 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
182 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
183 : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, NUMBER),
184 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
185 preview_(new RenderPreview(this))
193 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
199 InsetMathHull::~InsetMathHull()
201 for (size_t i = 0; i < label_.size(); ++i)
206 Inset * InsetMathHull::clone() const
208 return new InsetMathHull(*this);
212 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
216 InsetMathGrid::operator=(other);
218 numbered_ = other.numbered_;
219 numbers_ = other.numbers_;
220 buffer_ = other.buffer_;
221 for (size_t i = 0; i < label_.size(); ++i)
223 label_ = other.label_;
224 for (size_t i = 0; i != label_.size(); ++i) {
226 label_[i] = new InsetLabel(*label_[i]);
228 preview_.reset(new RenderPreview(*other.preview_, this));
234 void InsetMathHull::setBuffer(Buffer & buffer)
236 InsetMathGrid::setBuffer(buffer);
238 for (size_t i = 0; i != label_.size(); ++i) {
240 label_[i]->setBuffer(buffer);
245 // FIXME This should really be controlled by the TOC level, or
246 // something of the sort.
248 const char * counters_to_save[] = {"section", "chapter"};
249 unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
253 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
256 //FIXME: buffer_ should be set at creation for this inset! Problem is
257 // This inset is created at too many places (see Parser::parse1() in
262 // if any of the equations are numbered, then we want to save the values
263 // of some of the counters.
265 BufferParams const & bp = buffer_->params();
266 string const & lang = it->getParLanguage(bp)->code();
268 buffer_->masterBuffer()->params().documentClass().counters();
270 // right now, we only need to do this at export time
271 if (utype == OutputUpdate) {
272 for (size_t i = 0; i < numcnts; ++i) {
273 docstring const cnt = from_ascii(counters_to_save[i]);
274 if (cnts.hasCounter(cnt))
275 counter_map[cnt] = cnts.value(cnt);
279 // this has to be done separately
280 docstring const eqstr = from_ascii("equation");
281 if (cnts.hasCounter(eqstr)) {
282 if (utype == OutputUpdate)
283 counter_map[eqstr] = cnts.value(eqstr);
284 for (size_t i = 0; i != label_.size(); ++i) {
286 cnts.step(eqstr, utype);
287 numbers_[i] = cnts.theCounter(eqstr, lang);
289 numbers_[i] = empty_docstring();
295 for (size_t i = 0; i != label_.size(); ++i) {
297 label_[i]->updateBuffer(it, utype);
300 InsetMathGrid::updateBuffer(it, utype);
304 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active,
305 UpdateType utype) const
308 //FIXME: buffer_ should be set at creation for this inset! Problem is
309 // This inset is created at too many places (see Parser::parse1() in
314 shared_ptr<Toc> toc = buffer().tocBackend().toc("equation");
316 for (row_type row = 0; row != nrows(); ++row) {
320 label_[row]->addToToc(pit, output_active, utype);
321 toc->push_back(TocItem(pit, 0, nicelabel(row), output_active));
326 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
328 if (previewState(&cur.bv())) {
332 return InsetMathNest::editXY(cur, x, y);
336 InsetMath::mode_type InsetMathHull::currentMode() const
340 return UNDECIDED_MODE;
342 // definitely math mode ...
362 bool InsetMathHull::idxFirst(Cursor & cur) const
370 bool InsetMathHull::idxLast(Cursor & cur) const
372 cur.idx() = nargs() - 1;
373 cur.pos() = cur.lastpos();
378 // FIXME: InsetMathGrid should be changed to let the real column alignment be
379 // given by a virtual method like displayColAlign, because the values produced
380 // by defaultColAlign can be invalidated by lfuns such as add-column. For the
381 // moment the values produced by defaultColAlign are not used, notably because
382 // alignment is not implemented in the LyXHTML output.
383 char InsetMathHull::defaultColAlign(col_type col)
385 return colAlign(type_, col);
389 char InsetMathHull::displayColAlign(idx_type idx) const
393 row_type const r = row(idx);
396 if (r == nrows() - 1)
407 return colAlign(type_, col(idx));
411 return InsetMathGrid::displayColAlign(idx);
415 int InsetMathHull::displayColSpace(col_type col) const
417 return colSpace(type_, col);
421 // FIXME: same comment as for defaultColAlign applies.
422 int InsetMathHull::defaultColSpace(col_type col)
424 return colSpace(type_, col);
428 docstring InsetMathHull::standardFont() const
432 return from_ascii("texttt");
434 return from_ascii("lyxnochange");
436 return from_ascii("mathnormal");
441 ColorCode InsetMathHull::standardColor() const
446 return Color_foreground;
454 bool InsetMathHull::previewState(const BufferView *const bv) const
456 if (!editing(bv) && RenderPreview::previewMath()
457 && type_ != hullRegexp)
459 graphics::PreviewImage const * pimage =
460 preview_->getPreviewImage(bv->buffer());
461 return pimage && pimage->image();
468 static const int ERROR_FRAME_WIDTH = 2;
471 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
473 if (previewState(mi.base.bv)) {
474 preview_->metrics(mi, dim);
475 if (previewTooSmall(dim)) {
476 // preview image is too small
477 dim.wid += 2 * ERROR_FRAME_WIDTH;
478 dim.asc += 2 * ERROR_FRAME_WIDTH;
480 // insert a one pixel gap in front of the formula
483 dim.des += displayMargin();
485 // Cache the inset dimension.
486 setDimCache(mi, dim);
490 // FIXME: Changing the same object repeatedly is inefficient.
491 Changer dummy1 = mi.base.changeFontSet(standardFont());
492 Changer dummy2 = mi.base.changeStyle(display() ? LM_ST_DISPLAY : LM_ST_TEXT);
494 // let the cells adjust themselves
495 InsetMathGrid::metrics(mi, dim);
498 dim.asc += displayMargin();
499 dim.des += displayMargin();
502 if (numberedType()) {
503 Changer dummy = mi.base.changeFontSet(from_ascii("mathbf"));
505 for (row_type row = 0; row < nrows(); ++row)
506 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
512 if (type_ == hullRegexp)
514 // make it at least as high as the current font
517 math_font_max_dim(mi.base.font, asc, des);
518 dim.asc = max(dim.asc, asc);
519 dim.des = max(dim.des, des);
520 // Cache the inset dimension.
521 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
522 setDimCache(mi, dim);
526 bool InsetMathHull::previewTooSmall(Dimension const & dim) const
528 return dim.width() <= 10 && dim.height() <= 10;
532 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
534 BufferView const * const bv = pi.base.bv;
535 if (previewState(bv)) {
536 Dimension const dim = dimension(*pi.base.bv);
537 if (previewTooSmall(dim))
539 return graphics::PreviewLoader::backgroundColor();
545 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
547 Dimension const dim = dimension(*pi.base.bv);
548 if (previewTooSmall(dim)) {
549 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
550 dim.wid, dim.asc + dim.des, backgroundColor(pi));
553 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
554 dim.asc + dim.des - 1, pi.backgroundColor(this));
558 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
560 BufferView const * const bv = pi.base.bv;
562 if (type_ == hullRegexp) {
563 Dimension const dim = dimension(*bv);
564 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
565 dim.width() - 2, dim.height() - 2, Color_regexpframe);
568 if (previewState(bv)) {
569 Dimension const dim = dimension(*bv);
570 if (previewTooSmall(dim)) {
571 // we have an extra frame
572 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
574 // one pixel gap in front
575 preview_->draw(pi, x + 1, y);
577 setPosCache(pi, x, y);
581 ColorCode color = pi.selected && lyxrc.use_system_colors
582 ? Color_selectiontext : standardColor();
583 bool const really_change_color = pi.base.font.color() == Color_none;
584 Changer dummy0 = pi.base.font.changeColor(color, really_change_color);
585 Changer dummy1 = pi.base.changeFontSet(standardFont());
586 Changer dummy2 = pi.base.changeStyle(display() ? LM_ST_DISPLAY : LM_ST_TEXT);
588 InsetMathGrid::draw(pi, x + 1, y);
590 if (numberedType()) {
591 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
592 for (row_type row = 0; row < nrows(); ++row) {
593 int const yy = y + rowinfo_[row].offset_;
594 Changer dummy = pi.base.changeFontSet(from_ascii("mathrm"));
595 docstring const nl = nicelabel(row);
599 setPosCache(pi, x, y);
603 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
606 InsetMathGrid::metricsT(mi, dim);
609 TexRow texrow(false);
610 otexrowstream ots(os,texrow);
611 WriteStream wi(ots, false, true, WriteStream::wsDefault);
613 dim.wid = os.str().size();
620 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
623 InsetMathGrid::drawT(pain, x, y);
626 TexRow texrow(false);
627 otexrowstream ots(os,texrow);
628 WriteStream wi(ots, false, true, WriteStream::wsDefault);
630 pain.draw(x, y, os.str().c_str());
635 static docstring latexString(InsetMathHull const & inset)
638 // This has to be static, because a preview snippet or a math
639 // macro containing math in text mode (such as $\text{$\phi$}$ or
640 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
641 // first time as a whole, and the second time only the inner math.
642 // In this last case inset.buffer() would be invalid.
643 static Encoding const * encoding = 0;
644 if (inset.isBufferValid())
645 encoding = &(inset.buffer().params().encoding());
646 TexRow texrow(false);
647 otexrowstream ots(ls,texrow);
648 WriteStream wi(ots, false, true, WriteStream::wsPreview, encoding);
654 void InsetMathHull::initUnicodeMath() const
656 // Trigger classification of the unicode symbols in this inset
657 docstring const dummy = latexString(*this);
661 void InsetMathHull::addPreview(DocIterator const & inset_pos,
662 graphics::PreviewLoader & /*ploader*/) const
664 if (RenderPreview::previewMath()) {
665 preparePreview(inset_pos);
670 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
671 MacroNameSet & macros, MacroNameSet & defs) const
673 MacroNameSet::iterator const end = macros.end();
675 for (size_t i = 0; i < md.size(); ++i) {
676 MathMacro const * mi = md[i].nucleus()->asMacro();
677 MathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
678 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
679 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
680 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
681 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
683 // Look for macros in the arguments of this macro.
684 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
685 usedMacros(mi->cell(idx), pos, macros, defs);
686 // Make sure this is a macro defined in the document
687 // (as we also spot the macros in the symbols file)
688 // or that we have not already accounted for it.
689 docstring const name = mi->name();
690 if (macros.find(name) == end)
693 // Look for macros in the definition of this macro.
694 MathData ar(pos.buffer());
695 MacroData const * data =
696 pos.buffer()->getMacro(name, pos, true);
698 odocstringstream macro_def;
699 data->write(macro_def, true);
701 defs.insert(macro_def.str());
702 asArray(data->definition(), ar);
704 usedMacros(ar, pos, macros, defs);
706 MathData ar(pos.buffer());
707 asArray(mt->definition(), ar);
708 usedMacros(ar, pos, macros, defs);
710 if (!si->nuc().empty())
711 usedMacros(si->nuc(), pos, macros, defs);
713 usedMacros(si->down(), pos, macros, defs);
715 usedMacros(si->up(), pos, macros, defs);
716 } else if (fi || gi) {
717 idx_type nidx = fi ? fi->nargs() : gi->nargs();
718 for (idx_type idx = 0; idx < nidx; ++idx)
719 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
722 usedMacros(ni->cell(0), pos, macros, defs);
728 void InsetMathHull::preparePreview(DocIterator const & pos,
729 bool forexport) const
731 // there is no need to do all the macro stuff if we're not
732 // actually going to generate the preview.
733 if (!RenderPreview::previewMath() && !forexport)
736 Buffer const * buffer = pos.buffer();
738 // collect macros at this position
740 buffer->listMacroNames(macros);
742 // collect definitions only for the macros used in this inset
744 for (idx_type idx = 0; idx < nargs(); ++idx)
745 usedMacros(cell(idx), pos, macros, defs);
747 MacroNameSet::iterator it = defs.begin();
748 MacroNameSet::iterator end = defs.end();
749 docstring macro_preamble;
750 for (; it != end; ++it)
751 macro_preamble.append(*it);
753 // set the font series and size for this snippet
754 DocIterator dit = pos.getInnerText();
755 Paragraph const & par = dit.paragraph();
756 Font font = par.getFontSettings(buffer->params(), dit.pos());
757 font.fontInfo().realize(par.layout().font);
758 string const lsize = font.latexSize();
761 if (font.fontInfo().series() == BOLD_SERIES) {
762 setfont += from_ascii("\\textbf{");
765 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
766 setfont += from_ascii("\\" + lsize + '\n');
769 if (forexport && haveNumbers()) {
770 docstring eqstr = from_ascii("equation");
771 CounterMap::const_iterator it = counter_map.find(eqstr);
772 if (it != counter_map.end()) {
773 int num = it->second;
775 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
776 '{' + convert<docstring>(num) + '}' + '\n';
778 for (size_t i = 0; i != numcnts; ++i) {
779 docstring cnt = from_ascii(counters_to_save[i]);
780 it = counter_map.find(cnt);
781 if (it == counter_map.end())
783 int num = it->second;
785 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
786 '{' + convert<docstring>(num) + '}';
789 docstring const snippet = macro_preamble + setfont + setcnt
790 + latexString(*this) + endfont;
791 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
792 preview_->addPreview(snippet, *buffer, forexport);
796 void InsetMathHull::reloadPreview(DocIterator const & pos) const
799 preview_->startLoading(*pos.buffer());
803 void InsetMathHull::loadPreview(DocIterator const & pos) const
805 bool const forexport = true;
806 preparePreview(pos, forexport);
807 preview_->startLoading(*pos.buffer(), forexport);
811 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
813 if (RenderPreview::previewMath()) {
815 cur.screenUpdateFlags(Update::Force);
821 docstring InsetMathHull::label(row_type row) const
823 LASSERT(row < nrows(), return docstring());
824 if (InsetLabel * il = label_[row])
825 return il->screenLabel();
830 void InsetMathHull::label(row_type row, docstring const & label)
832 //lyxerr << "setting label '" << label << "' for row " << row << endl;
836 label_[row] = dummy_pointer;
839 label_[row]->updateLabelAndRefs(label);
841 label_[row]->setParam("name", label);
845 InsetCommandParams p(LABEL_CODE);
847 label_[row] = new InsetLabel(buffer_, p);
849 label_[row]->setBuffer(buffer());
853 void InsetMathHull::numbered(row_type row, Numbered num)
855 numbered_[row] = num;
856 if (!numbered(row) && label_[row]) {
863 bool InsetMathHull::numbered(row_type row) const
865 return numbered_[row] == NUMBER;
869 bool InsetMathHull::ams() const
889 for (size_t row = 0; row < numbered_.size(); ++row)
890 if (numbered_[row] == NOTAG)
896 Inset::DisplayType InsetMathHull::display() const
919 bool InsetMathHull::numberedType() const
938 for (row_type row = 0; row < nrows(); ++row)
945 void InsetMathHull::validate(LaTeXFeatures & features) const
947 if (features.runparams().isLaTeX()) {
949 features.require("amsmath");
951 if (type_ == hullRegexp) {
952 features.require("color");
953 string frcol = lcolor.getLaTeXName(Color_regexpframe);
954 string bgcol = "white";
955 features.addPreambleSnippet(
956 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
957 + frcol + string("}{")
958 + bgcol + string("}{\\ensuremath{\\mathtt{#1}}}}"));
959 features.addPreambleSnippet(
960 string("\\newcommand{\\endregexp}{}"));
963 // Validation is necessary only if not using AMS math.
964 // To be safe, we will always run mathedvalidate.
965 //if (features.amsstyle)
968 //features.binom = true;
969 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
970 // it would be better to do this elsewhere, but we can't validate in
971 // InsetMathMatrix and we have no way, outside MathExtern, to know if
972 // we even have any matrices.
973 features.addCSSSnippet(
974 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
975 "table.matrix td{padding: 0.25px;}\n"
976 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
977 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
979 InsetMathGrid::validate(features);
983 void InsetMathHull::header_write(WriteStream & os) const
985 bool n = numberedType();
1002 os << "\\begin{equation" << star(n) << "}\n";
1014 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1021 os << "\\begin{" << hullName(type_) << star(n) << '}'
1022 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1028 os << "\\begin{" << hullName(type_) << '}'
1029 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1039 os << "\\begin{unknown" << star(n) << "}\n";
1045 void InsetMathHull::footer_write(WriteStream & os) const
1047 bool n = numberedType();
1062 os << "\\end{equation" << star(n) << "}\n";
1076 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1082 os << "\\end{" << hullName(type_) << "}\n";
1086 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1087 os << "\\endregexp{}}";
1093 os << "\\end{unknown" << star(n) << "}\n";
1099 bool InsetMathHull::allowsTabularFeatures() const
1122 bool InsetMathHull::rowChangeOK() const
1125 type_ == hullEqnArray || type_ == hullAlign ||
1126 type_ == hullFlAlign || type_ == hullAlignAt ||
1127 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1128 type_ == hullGather || type_ == hullMultline;
1132 bool InsetMathHull::colChangeOK() const
1135 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1136 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1140 void InsetMathHull::addRow(row_type row)
1145 bool numbered = numberedType();
1146 // Move the number and raw pointer, do not call label() (bug 7511)
1147 InsetLabel * label = dummy_pointer;
1148 docstring number = empty_docstring();
1149 if (type_ == hullMultline) {
1150 if (row + 1 == nrows()) {
1151 numbered_[row] = NONUMBER;
1152 swap(label, label_[row]);
1153 swap(number, numbers_[row]);
1158 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1159 numbers_.insert(numbers_.begin() + row + 1, number);
1160 label_.insert(label_.begin() + row + 1, label);
1161 InsetMathGrid::addRow(row);
1165 void InsetMathHull::swapRow(row_type row)
1169 if (row + 1 == nrows())
1171 swap(numbered_[row], numbered_[row + 1]);
1172 swap(numbers_[row], numbers_[row + 1]);
1173 swap(label_[row], label_[row + 1]);
1174 InsetMathGrid::swapRow(row);
1178 void InsetMathHull::delRow(row_type row)
1180 if (nrows() <= 1 || !rowChangeOK())
1182 if (row + 1 == nrows() && type_ == hullMultline) {
1183 swap(numbered_[row - 1], numbered_[row]);
1184 swap(numbers_[row - 1], numbers_[row]);
1185 swap(label_[row - 1], label_[row]);
1186 InsetMathGrid::delRow(row);
1189 InsetMathGrid::delRow(row);
1190 // The last dummy row has no number info nor a label.
1191 // Test nrows() + 1 because we have already erased the row.
1192 if (row == nrows() + 1)
1194 numbered_.erase(numbered_.begin() + row);
1195 numbers_.erase(numbers_.begin() + row);
1197 label_.erase(label_.begin() + row);
1201 void InsetMathHull::addCol(col_type col)
1205 InsetMathGrid::addCol(col);
1209 void InsetMathHull::delCol(col_type col)
1211 if (ncols() <= 1 || !colChangeOK())
1213 InsetMathGrid::delCol(col);
1217 docstring InsetMathHull::nicelabel(row_type row) const
1221 docstring const & val = numbers_[row];
1223 return '(' + val + ')';
1224 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1228 void InsetMathHull::glueall(HullType type)
1231 for (idx_type i = 0; i < nargs(); ++i)
1233 InsetLabel * label = 0;
1234 if (type == hullEquation) {
1235 // preserve first non-empty label
1236 for (row_type row = 0; row < nrows(); ++row) {
1238 label = label_[row];
1244 *this = InsetMathHull(buffer_, hullSimple);
1251 void InsetMathHull::splitTo2Cols()
1253 LASSERT(ncols() == 1, return);
1254 InsetMathGrid::addCol(1);
1255 for (row_type row = 0; row < nrows(); ++row) {
1256 idx_type const i = 2 * row;
1257 pos_type pos = firstRelOp(cell(i));
1258 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1259 cell(i).erase(pos, cell(i).size());
1264 void InsetMathHull::splitTo3Cols()
1266 LASSERT(ncols() < 3, return);
1269 InsetMathGrid::addCol(2);
1270 for (row_type row = 0; row < nrows(); ++row) {
1271 idx_type const i = 3 * row + 1;
1272 if (!cell(i).empty()) {
1273 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1274 cell(i).erase(1, cell(i).size());
1280 void InsetMathHull::changeCols(col_type cols)
1282 if (ncols() == cols)
1284 else if (ncols() < cols) {
1290 while (ncols() < cols)
1291 InsetMathGrid::addCol(ncols());
1297 for (row_type row = 0; row < nrows(); ++row) {
1298 idx_type const i = row * ncols();
1299 for (col_type col = cols; col < ncols(); ++col) {
1300 cell(i + cols - 1).append(cell(i + col));
1304 while (ncols() > cols) {
1305 InsetMathGrid::delCol(ncols() - 1);
1310 HullType InsetMathHull::getType() const
1316 void InsetMathHull::setType(HullType type)
1323 bool InsetMathHull::isMutable(HullType type)
1347 void InsetMathHull::mutate(HullType newtype)
1349 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1351 if (newtype == type_)
1354 // This guards the algorithm below it, which is designed with certain types
1356 if (!isMutable(newtype) || !isMutable(type_)) {
1357 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1358 << "' to '" << to_utf8(hullName(newtype))
1359 << "' not implemented" << endl;
1363 // we try to move along the chain
1364 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1366 // +-------------------------------------+
1367 // we use eqnarray as intermediate type for mutations that are not
1368 // directly supported because it handles labels and numbering for
1373 setType(hullSimple);
1379 if (newtype == hullNone) {
1383 setType(hullEquation);
1384 numbered(0, label_[0] ? true : false);
1393 setType(hullSimple);
1398 // split it "nicely" on the first relop
1400 setType(hullEqnArray);
1408 // split it "nicely"
1443 setType(hullEqnArray);
1452 for (row_type row = 0; row < nrows(); ++row)
1453 numbered(row, false);
1463 for (row_type row = 0; row < nrows(); ++row)
1464 numbered(row, false);
1471 setType(hullEqnArray);
1501 for (row_type row = 0; row < nrows(); ++row)
1502 numbered(row, false);
1506 // first we mutate to EqnArray
1508 setType(hullEqnArray);
1515 // we passed the guard so we should not be here
1516 LASSERT("Mutation not implemented, but should have been.", return);
1522 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1523 bool last_eoln) const
1526 if (numberedType()) {
1527 if (label_[row] && numbered(row)) {
1528 docstring const name =
1529 latex ? escape(label_[row]->getParam("name"))
1530 : label_[row]->getParam("name");
1531 res += "\\label{" + name + '}';
1533 if (type_ != hullMultline) {
1534 if (numbered_[row] == NONUMBER)
1535 res += "\\nonumber ";
1536 else if (numbered_[row] == NOTAG)
1540 // Never add \\ on the last empty line of eqnarray and friends
1542 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1545 void InsetMathHull::write(WriteStream & os) const
1547 ModeSpecifier specifier(os, MATH_MODE);
1549 InsetMathGrid::write(os);
1554 void InsetMathHull::normalize(NormalStream & os) const
1556 os << "[formula " << hullName(type_) << ' ';
1557 InsetMathGrid::normalize(os);
1562 void InsetMathHull::infoize(odocstream & os) const
1564 os << bformat(_("Type: %1$s"), hullName(type_));
1568 void InsetMathHull::check() const
1570 LATTEST(numbered_.size() == nrows());
1571 LATTEST(numbers_.size() == nrows());
1572 LATTEST(label_.size() == nrows());
1576 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1580 idocstringstream iss(func.argument());
1581 iss >> dlang >> extra;
1583 extra = from_ascii("noextra");
1584 string const lang = to_ascii(dlang);
1586 // replace selection with result of computation
1587 if (reduceSelectionToOneCell(cur)) {
1589 asArray(grabAndEraseSelection(cur), ar);
1590 lyxerr << "use selection: " << ar << endl;
1591 cur.insert(pipeThroughExtern(lang, extra, ar));
1595 // only inline, display or eqnarray math is allowed
1596 switch (getType()) {
1602 frontend::Alert::warning(_("Bad math environment"),
1603 _("Computation cannot be performed for AMS "
1604 "math environments.\nChange the math "
1605 "formula type and try again."));
1610 eq.push_back(MathAtom(new InsetMathChar('=')));
1612 // go to first item in line
1613 cur.idx() -= cur.idx() % ncols();
1616 if (getType() == hullSimple) {
1617 size_type pos = cur.cell().find_last(eq);
1619 if (pos == cur.cell().size()) {
1621 lyxerr << "use whole cell: " << ar << endl;
1623 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1624 lyxerr << "use partial cell form pos: " << pos << endl;
1626 cur.cell().append(eq);
1627 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1628 cur.pos() = cur.lastpos();
1632 if (getType() == hullEquation) {
1633 lyxerr << "use equation inset" << endl;
1634 mutate(hullEqnArray);
1635 MathData & ar = cur.cell();
1636 lyxerr << "use cell: " << ar << endl;
1640 cur.cell() = pipeThroughExtern(lang, extra, ar);
1641 // move to end of line
1642 cur.pos() = cur.lastpos();
1647 lyxerr << "use eqnarray" << endl;
1648 cur.idx() += 2 - cur.idx() % ncols();
1650 MathData ar = cur.cell();
1651 lyxerr << "use cell: " << ar << endl;
1652 // FIXME: temporarily disabled
1658 cur.cell() = pipeThroughExtern(lang, extra, ar);
1659 cur.pos() = cur.lastpos();
1664 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1666 //lyxerr << "action: " << cmd.action() << endl;
1667 switch (cmd.action()) {
1669 case LFUN_FINISHED_BACKWARD:
1670 case LFUN_FINISHED_FORWARD:
1671 case LFUN_FINISHED_RIGHT:
1672 case LFUN_FINISHED_LEFT:
1673 //lyxerr << "action: " << cmd.action() << endl;
1674 InsetMathGrid::doDispatch(cur, cmd);
1677 case LFUN_PARAGRAPH_BREAK:
1678 // just swallow this
1681 case LFUN_NEWLINE_INSERT:
1682 // some magic for the common case
1683 if (type_ == hullSimple || type_ == hullEquation) {
1684 cur.recordUndoInset();
1686 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1687 mutate(align ? hullAlign : hullEqnArray);
1688 // mutate() may change labels and such.
1689 cur.forceBufferUpdate();
1690 cur.idx() = nrows() * ncols() - 1;
1691 cur.pos() = cur.lastpos();
1693 InsetMathGrid::doDispatch(cur, cmd);
1696 case LFUN_MATH_NUMBER_TOGGLE: {
1697 //lyxerr << "toggling all numbers" << endl;
1698 cur.recordUndoInset();
1699 bool old = numberedType();
1700 if (type_ == hullMultline)
1701 numbered(nrows() - 1, !old);
1703 for (row_type row = 0; row < nrows(); ++row)
1704 numbered(row, !old);
1706 cur.message(old ? _("No number") : _("Number"));
1707 cur.forceBufferUpdate();
1711 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1712 cur.recordUndoInset();
1713 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1714 bool old = numbered(r);
1715 cur.message(old ? _("No number") : _("Number"));
1717 cur.forceBufferUpdate();
1721 case LFUN_LABEL_INSERT: {
1722 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1723 docstring old_label = label(r);
1724 docstring const default_label = from_ascii("eq:");
1725 if (old_label.empty())
1726 old_label = default_label;
1728 InsetCommandParams p(LABEL_CODE);
1729 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1730 string const data = InsetCommand::params2string(p);
1732 if (cmd.argument().empty())
1733 cur.bv().showDialog("label", data);
1735 FuncRequest fr(LFUN_INSET_INSERT, data);
1741 case LFUN_LABEL_COPY_AS_REFERENCE: {
1743 if (cmd.argument().empty() && &cur.inset() == this)
1744 // if there is no argument and we're inside math, we retrieve
1745 // the row number from the cursor position.
1746 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1748 // if there is an argument, find the corresponding label, else
1749 // check whether there is at least one label.
1750 for (row = 0; row != nrows(); ++row)
1751 if (numbered(row) && label_[row]
1752 && (cmd.argument().empty() || label(row) == cmd.argument()))
1759 InsetCommandParams p(REF_CODE, "ref");
1760 p["reference"] = label(row);
1761 cap::clearSelection();
1762 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1766 case LFUN_WORD_DELETE_FORWARD:
1767 case LFUN_CHAR_DELETE_FORWARD:
1768 if (col(cur.idx()) + 1 == ncols()
1769 && cur.pos() == cur.lastpos()
1770 && !cur.selection()) {
1771 if (!label(row(cur.idx())).empty()) {
1772 cur.recordUndoInset();
1773 label(row(cur.idx()), docstring());
1774 } else if (numbered(row(cur.idx()))) {
1775 cur.recordUndoInset();
1776 numbered(row(cur.idx()), false);
1777 cur.forceBufferUpdate();
1779 InsetMathGrid::doDispatch(cur, cmd);
1783 InsetMathGrid::doDispatch(cur, cmd);
1788 case LFUN_INSET_INSERT: {
1789 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1790 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1791 string const name = cmd.getArg(0);
1792 if (name == "label") {
1793 InsetCommandParams p(LABEL_CODE);
1794 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1795 docstring str = p["name"];
1796 cur.recordUndoInset();
1797 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1801 docstring old = label(r);
1804 // The label will take care of the reference update.
1808 // Newly created inset so initialize it.
1809 label_[r]->initView();
1812 cur.forceBufferUpdate();
1815 InsetMathGrid::doDispatch(cur, cmd);
1819 case LFUN_MATH_EXTERN:
1820 cur.recordUndoInset();
1824 case LFUN_MATH_MUTATE: {
1825 cur.recordUndoInset();
1826 row_type row = cur.row();
1827 col_type col = cur.col();
1828 mutate(hullType(cmd.argument()));
1829 cur.idx() = row * ncols() + col;
1830 if (cur.idx() > cur.lastidx()) {
1831 cur.idx() = cur.lastidx();
1832 cur.pos() = cur.lastpos();
1834 if (cur.pos() > cur.lastpos())
1835 cur.pos() = cur.lastpos();
1837 cur.forceBufferUpdate();
1838 // FIXME: find some more clever handling of the selection,
1839 // i.e. preserve it.
1840 cur.clearSelection();
1841 //cur.dispatched(FINISHED);
1845 case LFUN_MATH_DISPLAY: {
1846 cur.recordUndoInset();
1847 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1848 // if the cursor is in a cell that got merged, move it to
1849 // start of the hull inset.
1850 if (cur.idx() > 0) {
1854 if (cur.pos() > cur.lastpos())
1855 cur.pos() = cur.lastpos();
1860 case LFUN_TABULAR_FEATURE:
1861 if (!allowsTabularFeatures())
1864 InsetMathGrid::doDispatch(cur, cmd);
1868 InsetMathGrid::doDispatch(cur, cmd);
1876 bool allowDisplayMath(Cursor const & cur)
1878 LATTEST(cur.depth() > 1);
1879 Cursor tmpcur = cur;
1882 FuncRequest cmd(LFUN_MATH_DISPLAY);
1883 return tmpcur.getStatus(cmd, status) && status.enabled();
1889 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1890 FuncStatus & status) const
1892 switch (cmd.action()) {
1893 case LFUN_FINISHED_BACKWARD:
1894 case LFUN_FINISHED_FORWARD:
1895 case LFUN_FINISHED_RIGHT:
1896 case LFUN_FINISHED_LEFT:
1899 case LFUN_NEWLINE_INSERT:
1900 case LFUN_MATH_EXTERN:
1902 status.setEnabled(true);
1905 // we never allow this in math, and we want to bind enter
1906 // to another actions in command-alternatives
1907 case LFUN_PARAGRAPH_BREAK:
1908 status.setEnabled(false);
1910 case LFUN_MATH_MUTATE: {
1911 HullType const ht = hullType(cmd.argument());
1912 status.setOnOff(type_ == ht);
1913 status.setEnabled(isMutable(ht) && isMutable(type_));
1915 if (ht != hullSimple && status.enabled())
1916 status.setEnabled(allowDisplayMath(cur));
1919 case LFUN_MATH_DISPLAY: {
1920 status.setEnabled(display() != Inline || allowDisplayMath(cur));
1921 status.setOnOff(display() != Inline);
1925 case LFUN_MATH_NUMBER_TOGGLE:
1926 // FIXME: what is the right test, this or the one of
1928 status.setEnabled(display() != Inline);
1929 status.setOnOff(numberedType());
1932 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1933 // FIXME: what is the right test, this or the one of
1935 bool const enable = (type_ == hullMultline)
1936 ? (nrows() - 1 == cur.row())
1937 : display() != Inline;
1938 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1939 status.setEnabled(enable);
1940 status.setOnOff(enable && numbered(r));
1944 case LFUN_LABEL_INSERT:
1945 status.setEnabled(type_ != hullSimple);
1948 case LFUN_LABEL_COPY_AS_REFERENCE: {
1949 bool enabled = false;
1951 if (cmd.argument().empty() && &cur.inset() == this) {
1952 // if there is no argument and we're inside math, we retrieve
1953 // the row number from the cursor position.
1954 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1955 enabled = numberedType() && label_[row] && numbered(row);
1957 // if there is an argument, find the corresponding label, else
1958 // check whether there is at least one label.
1959 for (row_type row = 0; row != nrows(); ++row) {
1960 if (numbered(row) && label_[row] &&
1961 (cmd.argument().empty() || label(row) == cmd.argument())) {
1967 status.setEnabled(enabled);
1971 case LFUN_INSET_INSERT:
1972 if (cmd.getArg(0) == "label") {
1973 status.setEnabled(type_ != hullSimple);
1976 return InsetMathGrid::getStatus(cur, cmd, status);
1978 case LFUN_TABULAR_FEATURE: {
1979 if (!allowsTabularFeatures())
1981 string s = cmd.getArg(0);
1983 && (s == "append-row"
1984 || s == "delete-row"
1985 || s == "copy-row")) {
1986 status.message(bformat(
1987 from_utf8(N_("Can't change number of rows in '%1$s'")),
1989 status.setEnabled(false);
1993 && (s == "append-column"
1994 || s == "delete-column"
1995 || s == "copy-column")) {
1996 status.message(bformat(
1997 from_utf8(N_("Can't change number of columns in '%1$s'")),
1999 status.setEnabled(false);
2002 if (s == "add-vline-left" || s == "add-vline-right") {
2003 status.message(bformat(
2004 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2006 status.setEnabled(false);
2009 if (s == "valign-top" || s == "valign-middle"
2010 || s == "valign-bottom" || s == "align-left"
2011 || s == "align-center" || s == "align-right") {
2012 status.setEnabled(false);
2015 return InsetMathGrid::getStatus(cur, cmd, status);
2019 return InsetMathGrid::getStatus(cur, cmd, status);
2022 // This cannot really happen, but inserted to shut-up gcc
2023 return InsetMathGrid::getStatus(cur, cmd, status);
2027 /////////////////////////////////////////////////////////////////////
2031 // simply scrap this function if you want
2032 void InsetMathHull::mutateToText()
2035 // translate to latex
2037 latex(os, false, false);
2038 string str = os.str();
2041 Text * lt = view_->cursor().innerText();
2042 string::const_iterator cit = str.begin();
2043 string::const_iterator end = str.end();
2044 for (; cit != end; ++cit)
2045 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2048 //dispatch(LFUN_ESCAPE);
2053 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2054 docstring const & font)
2056 // this whole function is a hack and won't work for incremental font
2059 if (cur.inset().asInsetMath()->name() == font)
2060 cur.handleFont(to_utf8(font));
2062 cur.handleNest(createInsetMath(font, cur.buffer()));
2068 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2073 font.fromString(to_utf8(arg), b);
2074 if (font.fontInfo().color() != Color_inherit) {
2075 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2076 cur.handleNest(at, 0);
2081 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2084 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
2085 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
2086 enter_front ? idxFirst(cur) : idxLast(cur);
2087 // The inset formula dimension is not necessarily the same as the
2088 // one of the instant preview image, so we have to indicate to the
2089 // BufferView that a metrics update is needed.
2090 cur.screenUpdateFlags(Update::Force);
2094 void InsetMathHull::revealCodes(Cursor & cur) const
2096 if (!cur.inMathed())
2098 odocstringstream os;
2100 cur.message(os.str());
2102 // write something to the minibuffer
2103 // translate to latex
2107 string str = os.str();
2109 string::size_type pos = 0;
2111 for (string::iterator it = str.begin(); it != str.end(); ++it) {
2114 else if (*it == '\0') {
2116 pos = it - str.begin();
2122 res = res.substr(pos - 30);
2123 if (res.size() > 60)
2124 res = res.substr(0, 60);
2130 /////////////////////////////////////////////////////////////////////
2134 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2137 // FIXME: completely broken
2138 static InsetMathHull * lastformula = 0;
2139 static CursorBase current = DocIterator(ibegin(nucleus()));
2141 static string laststr;
2143 if (lastformula != this || laststr != str) {
2144 //lyxerr << "reset lastformula to " << this << endl;
2147 current = ibegin(nucleus());
2149 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2153 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2155 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2156 CursorSlice & top = it.back();
2157 MathData const & a = top.asInsetMath()->cell(top.idx_);
2158 if (a.matchpart(ar, top.pos_)) {
2159 bv->cursor().setSelection(it, ar.size());
2161 top.pos_ += ar.size();
2167 //lyxerr << "not found!" << endl;
2174 void InsetMathHull::write(ostream & os) const
2176 odocstringstream oss;
2177 TexRow texrow(false);
2178 otexrowstream ots(oss,texrow);
2179 WriteStream wi(ots, false, false, WriteStream::wsDefault);
2182 os << to_utf8(oss.str());
2186 void InsetMathHull::read(Lexer & lex)
2189 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2190 operator=(*at->asHullInset());
2194 bool InsetMathHull::readQuiet(Lexer & lex)
2197 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2199 operator=(*at->asHullInset());
2204 int InsetMathHull::plaintext(odocstringstream & os,
2205 OutputParams const & op, size_t max_length) const
2207 // disables ASCII-art for export of equations. See #2275.
2208 if (0 && display()) {
2212 TextPainter tpain(dim.width(), dim.height());
2213 drawT(tpain, 0, dim.ascent());
2215 // reset metrics cache to "real" values
2217 return tpain.textheight();
2220 odocstringstream oss;
2221 TexRow texrow(false);
2222 otexrowstream ots(oss,texrow);
2223 Encoding const * const enc = encodings.fromLyXName("utf8");
2224 WriteStream wi(ots, false, true, WriteStream::wsDefault, enc);
2227 if (type_ == hullRegexp)
2230 for (row_type r = 0; r < nrows(); ++r) {
2231 for (col_type c = 0; c < ncols(); ++c)
2232 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2233 // if it's for the TOC, we write just the first line
2234 // and do not include the newline.
2235 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2237 if (r < nrows() - 1)
2241 docstring const str = oss.str();
2247 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
2252 if (getType() == hullSimple)
2253 name = from_ascii("inlineequation");
2255 name = from_ascii("informalequation");
2257 docstring bname = name;
2258 if (!label(0).empty())
2259 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
2261 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
2263 odocstringstream ls;
2265 otexstream ols(ls, texrow);
2266 if (runparams.flavor == OutputParams::XML) {
2267 ms << MTag("alt role='tex' ");
2268 // Workaround for db2latex: db2latex always includes equations with
2269 // \ensuremath{} or \begin{display}\end{display}
2270 // so we strip LyX' math environment
2271 WriteStream wi(ols, false, false, WriteStream::wsDefault, runparams.encoding);
2272 InsetMathGrid::write(wi);
2273 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2278 InsetMathGrid::mathmlize(ms);
2281 ms << MTag("alt role='tex'");
2282 latex(ols, runparams);
2283 res = texrow.rows();
2284 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2288 ms << from_ascii("<graphic fileref=\"eqn/");
2289 if (!label(0).empty())
2290 ms << sgml::cleanID(buffer(), runparams, label(0));
2292 ms << sgml::uniqueID(from_ascii("anon"));
2294 if (runparams.flavor == OutputParams::XML)
2295 ms << from_ascii("\"/>");
2297 ms << from_ascii("\">");
2299 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2301 return ms.line() + res;
2305 bool InsetMathHull::haveNumbers() const
2307 bool havenumbers = false;
2308 // inline formulas are never numbered (bug 7351 part 3)
2309 if (getType() == hullSimple)
2311 for (size_t i = 0; i != numbered_.size(); ++i) {
2322 // We need to do something about alignment here.
2324 // This duplicates code from InsetMathGrid, but
2325 // we need access here to number information,
2326 // and we simply do not have that in InsetMathGrid.
2327 void InsetMathHull::htmlize(HtmlStream & os) const
2329 bool const havenumbers = haveNumbers();
2330 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2333 os << cell(index(0, 0));
2337 os << MTag("table", "class='mathtable'");
2338 for (row_type row = 0; row < nrows(); ++row) {
2340 for (col_type col = 0; col < ncols(); ++col) {
2342 os << cell(index(row, col));
2347 docstring const & num = numbers_[row];
2349 os << '(' << num << ')';
2354 os << ETag("table");
2358 // this duplicates code from InsetMathGrid, but
2359 // we need access here to number information,
2360 // and we simply do not have that in InsetMathGrid.
2361 void InsetMathHull::mathmlize(MathStream & os) const
2363 bool const havenumbers = haveNumbers();
2364 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2367 os << MTag("mtable");
2368 char const * const celltag = havetable ? "mtd" : "mrow";
2369 // FIXME There does not seem to be wide support at the moment
2370 // for mlabeledtr, so we have to use just mtr for now.
2371 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2372 char const * const rowtag = "mtr";
2373 for (row_type row = 0; row < nrows(); ++row) {
2376 for (col_type col = 0; col < ncols(); ++col) {
2378 << cell(index(row, col))
2384 docstring const & num = numbers_[row];
2386 os << '(' << num << ')';
2393 os << ETag("mtable");
2397 void InsetMathHull::mathAsLatex(WriteStream & os) const
2399 MathEnsurer ensurer(os, false);
2400 bool havenumbers = haveNumbers();
2401 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2404 os << cell(index(0, 0));
2408 os << "<table class='mathtable'>";
2409 for (row_type row = 0; row < nrows(); ++row) {
2411 for (col_type col = 0; col < ncols(); ++col) {
2412 os << "<td class='math'>";
2413 os << cell(index(row, col));
2418 docstring const & num = numbers_[row];
2420 os << '(' << num << ')';
2429 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2431 BufferParams::MathOutput const mathtype =
2432 buffer().masterBuffer()->params().html_math_output;
2434 bool success = false;
2436 // we output all the labels just at the beginning of the equation.
2437 // this should be fine.
2438 for (size_t i = 0; i != label_.size(); ++i) {
2439 InsetLabel const * const il = label_[i];
2445 // FIXME Eventually we would like to do this inset by inset.
2446 if (mathtype == BufferParams::MathML) {
2447 odocstringstream os;
2452 } catch (MathExportException const &) {}
2454 if (getType() == hullSimple)
2455 xs << html::StartTag("math",
2456 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2458 xs << html::StartTag("math",
2459 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2460 xs << XHTMLStream::ESCAPE_NONE
2462 << html::EndTag("math");
2464 } else if (mathtype == BufferParams::HTML) {
2465 odocstringstream os;
2470 } catch (MathExportException const &) {}
2472 string const tag = (getType() == hullSimple) ? "span" : "div";
2473 xs << html::StartTag(tag, "class='formula'", true)
2474 << XHTMLStream::ESCAPE_NONE
2476 << html::EndTag(tag);
2480 // what we actually want is this:
2482 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2484 // || mathtype == BufferParams::Images
2486 // but what follows is equivalent, since we'll enter only if either (a) we
2487 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2488 // aren't doing LaTeX, in which case we are doing Images.
2489 if (!success && mathtype != BufferParams::LaTeX) {
2490 graphics::PreviewImage const * pimage = 0;
2492 loadPreview(docit_);
2493 pimage = preview_->getPreviewImage(buffer());
2494 // FIXME Do we always have png?
2497 if (pimage || op.dryrun) {
2498 string const filename = pimage ? pimage->filename().onlyFileName()
2499 : "previewimage.png";
2501 // if we are not in the master buffer, then we need to see that the
2502 // generated image is copied there; otherwise, preview fails.
2503 Buffer const * mbuf = buffer().masterBuffer();
2504 if (mbuf != &buffer()) {
2505 string mbtmp = mbuf->temppath();
2506 FileName const mbufimg(support::addName(mbtmp, filename));
2507 pimage->filename().copyTo(mbufimg);
2509 // add the file to the list of files to be exported
2510 op.exportdata->addExternalFile("xhtml", pimage->filename());
2513 string const tag = (getType() == hullSimple) ? "span" : "div";
2515 << html::StartTag(tag)
2516 << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2517 << html::EndTag(tag)
2523 // so we'll pass this test if we've failed everything else, or
2524 // if mathtype was LaTeX, since we won't have entered any of the
2526 if (!success /* || mathtype != BufferParams::LaTeX */) {
2527 // Unfortunately, we cannot use latexString() because we do not want
2528 // $...$ or whatever.
2529 odocstringstream ls;
2530 TexRow texrow(false);
2531 otexrowstream ots(ls,texrow);
2532 WriteStream wi(ots, false, true, WriteStream::wsPreview);
2533 ModeSpecifier specifier(wi, MATH_MODE);
2535 docstring const latex = ls.str();
2537 // class='math' allows for use of jsMath
2538 // http://www.math.union.edu/~dpvc/jsMath/
2540 // probably should allow for some kind of customization here
2541 string const tag = (getType() == hullSimple) ? "span" : "div";
2542 xs << html::StartTag(tag, "class='math'")
2544 << html::EndTag(tag)
2551 void InsetMathHull::toString(odocstream & os) const
2553 odocstringstream ods;
2554 plaintext(ods, OutputParams(0));
2559 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2561 odocstringstream ods;
2564 // FIXME: this results in spilling TeX into the LyXHTML output since the
2565 // outliner is used to generate the LyXHTML list of figures/etc.
2571 string InsetMathHull::contextMenuName() const
2573 return "context-math";
2577 void InsetMathHull::recordLocation(DocIterator const & di)