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 "MetricsInfo.h"
42 #include "output_xhtml.h"
43 #include "Paragraph.h"
44 #include "ParIterator.h"
46 #include "TextClass.h"
47 #include "TextPainter.h"
48 #include "TocBackend.h"
50 #include "insets/InsetLabel.h"
51 #include "insets/InsetRef.h"
52 #include "insets/RenderPreview.h"
54 #include "graphics/GraphicsImage.h"
55 #include "graphics/PreviewImage.h"
56 #include "graphics/PreviewLoader.h"
58 #include "frontends/alert.h"
59 #include "frontends/Painter.h"
61 #include "support/convert.h"
62 #include "support/lassert.h"
63 #include "support/debug.h"
64 #include "support/filetools.h"
65 #include "support/gettext.h"
66 #include "support/lstrings.h"
71 using namespace lyx::support;
75 using cap::grabAndEraseSelection;
76 using cap::reduceSelectionToOneCell;
80 int getCols(HullType type)
105 // returns position of first relation operator in the array
106 // used for "intelligent splitting"
107 size_t firstRelOp(MathData const & ar)
109 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
110 if ((*it)->isMathRel())
111 return it - ar.begin();
116 char const * star(bool numbered)
118 return numbered ? "" : "*";
122 } // end anon namespace
125 HullType hullType(docstring const & s)
127 if (s == "none") return hullNone;
128 if (s == "simple") return hullSimple;
129 if (s == "equation") return hullEquation;
130 if (s == "eqnarray") return hullEqnArray;
131 if (s == "align") return hullAlign;
132 if (s == "alignat") return hullAlignAt;
133 if (s == "xalignat") return hullXAlignAt;
134 if (s == "xxalignat") return hullXXAlignAt;
135 if (s == "multline") return hullMultline;
136 if (s == "gather") return hullGather;
137 if (s == "flalign") return hullFlAlign;
138 if (s == "regexp") return hullRegexp;
139 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
144 docstring hullName(HullType type)
147 case hullNone: return from_ascii("none");
148 case hullSimple: return from_ascii("simple");
149 case hullEquation: return from_ascii("equation");
150 case hullEqnArray: return from_ascii("eqnarray");
151 case hullAlign: return from_ascii("align");
152 case hullAlignAt: return from_ascii("alignat");
153 case hullXAlignAt: return from_ascii("xalignat");
154 case hullXXAlignAt: return from_ascii("xxalignat");
155 case hullMultline: return from_ascii("multline");
156 case hullGather: return from_ascii("gather");
157 case hullFlAlign: return from_ascii("flalign");
158 case hullRegexp: return from_ascii("regexp");
160 lyxerr << "unknown hull type" << endl;
163 return from_ascii("none");
166 static InsetLabel * dummy_pointer = 0;
168 InsetMathHull::InsetMathHull(Buffer * buf)
169 : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, NUMBER),
170 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
171 preview_(new RenderPreview(this))
173 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
174 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
175 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
176 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
183 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
184 : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, NUMBER),
185 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
186 preview_(new RenderPreview(this))
194 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
200 InsetMathHull::~InsetMathHull()
202 for (size_t i = 0; i < label_.size(); ++i)
207 Inset * InsetMathHull::clone() const
209 return new InsetMathHull(*this);
213 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
217 InsetMathGrid::operator=(other);
219 numbered_ = other.numbered_;
220 numbers_ = other.numbers_;
221 buffer_ = other.buffer_;
222 for (size_t i = 0; i < label_.size(); ++i)
224 label_ = other.label_;
225 for (size_t i = 0; i != label_.size(); ++i) {
227 label_[i] = new InsetLabel(*label_[i]);
229 preview_.reset(new RenderPreview(*other.preview_, this));
235 void InsetMathHull::setBuffer(Buffer & buffer)
237 InsetMathGrid::setBuffer(buffer);
239 for (size_t i = 0; i != label_.size(); ++i) {
241 label_[i]->setBuffer(buffer);
246 // FIXME This should really be controlled by the TOC level, or
247 // something of the sort.
249 const char * counters_to_save[] = {"section", "chapter"};
250 unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
254 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
257 //FIXME: buffer_ should be set at creation for this inset! Problem is
258 // This inset is created at too many places (see Parser::parse1() in
263 // if any of the equations are numbered, then we want to save the values
264 // of some of the counters.
266 BufferParams const & bp = buffer_->params();
267 string const & lang = it->getParLanguage(bp)->code();
269 buffer_->masterBuffer()->params().documentClass().counters();
271 // right now, we only need to do this at export time
272 if (utype == OutputUpdate) {
273 for (size_t i = 0; i < numcnts; ++i) {
274 docstring const cnt = from_ascii(counters_to_save[i]);
275 if (cnts.hasCounter(cnt))
276 counter_map[cnt] = cnts.value(cnt);
280 // this has to be done separately
281 docstring const eqstr = from_ascii("equation");
282 if (cnts.hasCounter(eqstr)) {
283 if (utype == OutputUpdate)
284 counter_map[eqstr] = cnts.value(eqstr);
285 for (size_t i = 0; i != label_.size(); ++i) {
287 cnts.step(eqstr, utype);
288 numbers_[i] = cnts.theCounter(eqstr, lang);
290 numbers_[i] = empty_docstring();
296 for (size_t i = 0; i != label_.size(); ++i) {
298 label_[i]->updateBuffer(it, utype);
301 InsetMathGrid::updateBuffer(it, utype);
305 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active,
306 UpdateType utype) const
309 //FIXME: buffer_ should be set at creation for this inset! Problem is
310 // This inset is created at too many places (see Parser::parse1() in
315 shared_ptr<Toc> toc = buffer().tocBackend().toc("equation");
317 for (row_type row = 0; row != nrows(); ++row) {
321 label_[row]->addToToc(pit, output_active, utype);
322 toc->push_back(TocItem(pit, 0, nicelabel(row), output_active));
327 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
329 if (previewState(&cur.bv())) {
333 return InsetMathNest::editXY(cur, x, y);
337 InsetMath::mode_type InsetMathHull::currentMode() const
341 return UNDECIDED_MODE;
343 // definitely math mode ...
363 bool InsetMathHull::idxFirst(Cursor & cur) const
371 bool InsetMathHull::idxLast(Cursor & cur) const
373 cur.idx() = nargs() - 1;
374 cur.pos() = cur.lastpos();
379 // FIXME: InsetMathGrid should be changed to let the real column alignment be
380 // given by a virtual method like displayColAlign, because the values produced
381 // by defaultColAlign can be invalidated by lfuns such as add-column. For the
382 // moment the values produced by defaultColAlign are not used, notably because
383 // alignment is not implemented in the LyXHTML output.
384 char InsetMathHull::defaultColAlign(col_type col)
386 return colAlign(type_, col);
390 char InsetMathHull::displayColAlign(idx_type idx) const
394 row_type const r = row(idx);
397 if (r == nrows() - 1)
408 return colAlign(type_, col(idx));
412 return InsetMathGrid::displayColAlign(idx);
416 int InsetMathHull::displayColSpace(col_type col) const
418 return colSpace(type_, col);
422 // FIXME: same comment as for defaultColAlign applies.
423 int InsetMathHull::defaultColSpace(col_type col)
425 return colSpace(type_, col);
429 string InsetMathHull::standardFont() const
435 return "lyxnochange";
442 ColorCode InsetMathHull::standardColor() const
447 return Color_foreground;
455 bool InsetMathHull::previewState(const BufferView *const bv) const
457 if (!editing(bv) && RenderPreview::previewMath()
458 && type_ != hullRegexp)
460 graphics::PreviewImage const * pimage =
461 preview_->getPreviewImage(bv->buffer());
462 return pimage && pimage->image();
469 static const int ERROR_FRAME_WIDTH = 2;
472 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
474 if (previewState(mi.base.bv)) {
475 preview_->metrics(mi, dim);
476 if (previewTooSmall(dim)) {
477 // preview image is too small
478 dim.wid += 2 * ERROR_FRAME_WIDTH;
479 dim.asc += 2 * ERROR_FRAME_WIDTH;
481 // insert a one pixel gap in front of the formula
484 dim.des += displayMargin();
486 // Cache the inset dimension.
487 setDimCache(mi, dim);
491 // FIXME: Changing the same object repeatedly is inefficient.
492 Changer dummy1 = mi.base.changeFontSet(standardFont());
493 Changer dummy2 = mi.base.changeStyle(display() ? LM_ST_DISPLAY : LM_ST_TEXT);
495 // let the cells adjust themselves
496 InsetMathGrid::metrics(mi, dim);
499 dim.asc += displayMargin();
500 dim.des += displayMargin();
503 if (numberedType()) {
504 Changer dummy = mi.base.changeFontSet("mathbf");
506 for (row_type row = 0; row < nrows(); ++row)
507 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
513 if (type_ == hullRegexp)
515 // make it at least as high as the current font
518 math_font_max_dim(mi.base.font, asc, des);
519 dim.asc = max(dim.asc, asc);
520 dim.des = max(dim.des, des);
521 // Cache the inset dimension.
522 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
523 setDimCache(mi, dim);
527 bool InsetMathHull::previewTooSmall(Dimension const & dim) const
529 return dim.width() <= 10 && dim.height() <= 10;
533 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
535 BufferView const * const bv = pi.base.bv;
536 if (previewState(bv)) {
537 Dimension const dim = dimension(*pi.base.bv);
538 if (previewTooSmall(dim))
540 return graphics::PreviewLoader::backgroundColor();
546 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
548 Dimension const dim = dimension(*pi.base.bv);
549 if (previewTooSmall(dim)) {
550 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
551 dim.wid, dim.asc + dim.des, backgroundColor(pi));
554 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
555 dim.asc + dim.des - 1, pi.backgroundColor(this));
559 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
561 BufferView const * const bv = pi.base.bv;
563 if (type_ == hullRegexp) {
564 Dimension const dim = dimension(*bv);
565 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
566 dim.width() - 2, dim.height() - 2, Color_regexpframe);
569 if (previewState(bv)) {
570 Dimension const dim = dimension(*bv);
571 if (previewTooSmall(dim)) {
572 // we have an extra frame
573 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
575 // one pixel gap in front
576 preview_->draw(pi, x + 1, y);
578 setPosCache(pi, x, y);
582 ColorCode color = pi.selected && lyxrc.use_system_colors
583 ? Color_selectiontext : standardColor();
584 bool const really_change_color = pi.base.font.color() == Color_none;
585 Changer dummy0 = pi.base.font.changeColor(color, really_change_color);
586 Changer dummy1 = pi.base.changeFontSet(standardFont());
587 Changer dummy2 = pi.base.changeStyle(display() ? LM_ST_DISPLAY : LM_ST_TEXT);
589 InsetMathGrid::draw(pi, x + 1, y);
591 if (numberedType()) {
592 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
593 for (row_type row = 0; row < nrows(); ++row) {
594 int const yy = y + rowinfo_[row].offset_;
595 Changer dummy = pi.base.changeFontSet("mathrm");
596 docstring const nl = nicelabel(row);
600 setPosCache(pi, x, y);
604 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
607 InsetMathGrid::metricsT(mi, dim);
610 TexRow texrow(false);
611 otexrowstream ots(os,texrow);
612 WriteStream wi(ots, false, true, WriteStream::wsDefault);
614 dim.wid = os.str().size();
621 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
624 InsetMathGrid::drawT(pain, x, y);
627 TexRow texrow(false);
628 otexrowstream ots(os,texrow);
629 WriteStream wi(ots, false, true, WriteStream::wsDefault);
631 pain.draw(x, y, os.str().c_str());
636 static docstring latexString(InsetMathHull const & inset)
639 // This has to be static, because a preview snippet or a math
640 // macro containing math in text mode (such as $\text{$\phi$}$ or
641 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
642 // first time as a whole, and the second time only the inner math.
643 // In this last case inset.buffer() would be invalid.
644 static Encoding const * encoding = 0;
645 if (inset.isBufferValid())
646 encoding = &(inset.buffer().params().encoding());
647 TexRow texrow(false);
648 otexrowstream ots(ls,texrow);
649 WriteStream wi(ots, false, true, WriteStream::wsPreview, encoding);
655 void InsetMathHull::initUnicodeMath() const
657 // Trigger classification of the unicode symbols in this inset
658 docstring const dummy = latexString(*this);
662 void InsetMathHull::addPreview(DocIterator const & inset_pos,
663 graphics::PreviewLoader & /*ploader*/) const
665 if (RenderPreview::previewMath()) {
666 preparePreview(inset_pos);
671 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
672 MacroNameSet & macros, MacroNameSet & defs) const
674 MacroNameSet::iterator const end = macros.end();
676 for (size_t i = 0; i < md.size(); ++i) {
677 MathMacro const * mi = md[i].nucleus()->asMacro();
678 MathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
679 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
680 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
681 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
682 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
684 // Look for macros in the arguments of this macro.
685 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
686 usedMacros(mi->cell(idx), pos, macros, defs);
687 // Make sure this is a macro defined in the document
688 // (as we also spot the macros in the symbols file)
689 // or that we have not already accounted for it.
690 docstring const name = mi->name();
691 if (macros.find(name) == end)
694 // Look for macros in the definition of this macro.
695 MathData ar(pos.buffer());
696 MacroData const * data =
697 pos.buffer()->getMacro(name, pos, true);
699 odocstringstream macro_def;
700 data->write(macro_def, true);
702 defs.insert(macro_def.str());
703 asArray(data->definition(), ar);
705 usedMacros(ar, pos, macros, defs);
707 MathData ar(pos.buffer());
708 asArray(mt->definition(), ar);
709 usedMacros(ar, pos, macros, defs);
711 if (!si->nuc().empty())
712 usedMacros(si->nuc(), pos, macros, defs);
714 usedMacros(si->down(), pos, macros, defs);
716 usedMacros(si->up(), pos, macros, defs);
717 } else if (fi || gi) {
718 idx_type nidx = fi ? fi->nargs() : gi->nargs();
719 for (idx_type idx = 0; idx < nidx; ++idx)
720 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
723 usedMacros(ni->cell(0), pos, macros, defs);
729 void InsetMathHull::preparePreview(DocIterator const & pos,
730 bool forexport) const
732 // there is no need to do all the macro stuff if we're not
733 // actually going to generate the preview.
734 if (!RenderPreview::previewMath() && !forexport)
737 Buffer const * buffer = pos.buffer();
739 // collect macros at this position
741 buffer->listMacroNames(macros);
743 // collect definitions only for the macros used in this inset
745 for (idx_type idx = 0; idx < nargs(); ++idx)
746 usedMacros(cell(idx), pos, macros, defs);
748 MacroNameSet::iterator it = defs.begin();
749 MacroNameSet::iterator end = defs.end();
750 docstring macro_preamble;
751 for (; it != end; ++it)
752 macro_preamble.append(*it);
754 // set the font series and size for this snippet
755 DocIterator dit = pos.getInnerText();
756 Paragraph const & par = dit.paragraph();
757 Font font = par.getFontSettings(buffer->params(), dit.pos());
758 font.fontInfo().realize(par.layout().font);
759 string const lsize = font.latexSize();
762 if (font.fontInfo().series() == BOLD_SERIES) {
763 setfont += from_ascii("\\textbf{");
766 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
767 setfont += from_ascii("\\" + lsize + '\n');
770 if (forexport && haveNumbers()) {
771 docstring eqstr = from_ascii("equation");
772 CounterMap::const_iterator it = counter_map.find(eqstr);
773 if (it != counter_map.end()) {
774 int num = it->second;
776 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
777 '{' + convert<docstring>(num) + '}' + '\n';
779 for (size_t i = 0; i != numcnts; ++i) {
780 docstring cnt = from_ascii(counters_to_save[i]);
781 it = counter_map.find(cnt);
782 if (it == counter_map.end())
784 int num = it->second;
786 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
787 '{' + convert<docstring>(num) + '}';
790 docstring const snippet = macro_preamble + setfont + setcnt
791 + latexString(*this) + endfont;
792 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
793 preview_->addPreview(snippet, *buffer, forexport);
797 void InsetMathHull::reloadPreview(DocIterator const & pos) const
800 preview_->startLoading(*pos.buffer());
804 void InsetMathHull::loadPreview(DocIterator const & pos) const
806 bool const forexport = true;
807 preparePreview(pos, forexport);
808 preview_->startLoading(*pos.buffer(), forexport);
812 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
814 if (RenderPreview::previewMath()) {
816 cur.screenUpdateFlags(Update::Force);
822 docstring InsetMathHull::label(row_type row) const
824 LASSERT(row < nrows(), return docstring());
825 if (InsetLabel * il = label_[row])
826 return il->screenLabel();
831 void InsetMathHull::label(row_type row, docstring const & label)
833 //lyxerr << "setting label '" << label << "' for row " << row << endl;
837 label_[row] = dummy_pointer;
840 label_[row]->updateLabelAndRefs(label);
842 label_[row]->setParam("name", label);
846 InsetCommandParams p(LABEL_CODE);
848 label_[row] = new InsetLabel(buffer_, p);
850 label_[row]->setBuffer(buffer());
854 void InsetMathHull::numbered(row_type row, Numbered num)
856 numbered_[row] = num;
857 if (!numbered(row) && label_[row]) {
864 bool InsetMathHull::numbered(row_type row) const
866 return numbered_[row] == NUMBER;
870 bool InsetMathHull::ams() const
890 for (size_t row = 0; row < numbered_.size(); ++row)
891 if (numbered_[row] == NOTAG)
897 Inset::DisplayType InsetMathHull::display() const
920 bool InsetMathHull::numberedType() const
939 for (row_type row = 0; row < nrows(); ++row)
946 void InsetMathHull::validate(LaTeXFeatures & features) const
948 if (features.runparams().isLaTeX()) {
950 features.require("amsmath");
952 if (type_ == hullRegexp) {
953 features.require("color");
954 string frcol = lcolor.getLaTeXName(Color_regexpframe);
955 string bgcol = "white";
956 features.addPreambleSnippet(
957 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
958 + frcol + string("}{")
959 + bgcol + string("}{\\ensuremath{\\mathtt{#1}}}}"));
960 features.addPreambleSnippet(
961 string("\\newcommand{\\endregexp}{}"));
964 // Validation is necessary only if not using AMS math.
965 // To be safe, we will always run mathedvalidate.
966 //if (features.amsstyle)
969 //features.binom = true;
970 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
971 // it would be better to do this elsewhere, but we can't validate in
972 // InsetMathMatrix and we have no way, outside MathExtern, to know if
973 // we even have any matrices.
974 features.addCSSSnippet(
975 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
976 "table.matrix td{padding: 0.25px;}\n"
977 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
978 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
980 InsetMathGrid::validate(features);
984 void InsetMathHull::header_write(WriteStream & os) const
986 bool n = numberedType();
1003 os << "\\begin{equation" << star(n) << "}\n";
1015 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1022 os << "\\begin{" << hullName(type_) << star(n) << '}'
1023 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1029 os << "\\begin{" << hullName(type_) << '}'
1030 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1040 os << "\\begin{unknown" << star(n) << "}\n";
1046 void InsetMathHull::footer_write(WriteStream & os) const
1048 bool n = numberedType();
1063 os << "\\end{equation" << star(n) << "}\n";
1077 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1083 os << "\\end{" << hullName(type_) << "}\n";
1087 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1088 os << "\\endregexp{}}";
1094 os << "\\end{unknown" << star(n) << "}\n";
1100 bool InsetMathHull::allowsTabularFeatures() const
1123 bool InsetMathHull::rowChangeOK() const
1126 type_ == hullEqnArray || type_ == hullAlign ||
1127 type_ == hullFlAlign || type_ == hullAlignAt ||
1128 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1129 type_ == hullGather || type_ == hullMultline;
1133 bool InsetMathHull::colChangeOK() const
1136 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1137 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1141 void InsetMathHull::addRow(row_type row)
1146 bool numbered = numberedType();
1147 // Move the number and raw pointer, do not call label() (bug 7511)
1148 InsetLabel * label = dummy_pointer;
1149 docstring number = empty_docstring();
1150 if (type_ == hullMultline) {
1151 if (row + 1 == nrows()) {
1152 numbered_[row] = NONUMBER;
1153 swap(label, label_[row]);
1154 swap(number, numbers_[row]);
1159 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1160 numbers_.insert(numbers_.begin() + row + 1, number);
1161 label_.insert(label_.begin() + row + 1, label);
1162 InsetMathGrid::addRow(row);
1166 void InsetMathHull::swapRow(row_type row)
1170 if (row + 1 == nrows())
1172 swap(numbered_[row], numbered_[row + 1]);
1173 swap(numbers_[row], numbers_[row + 1]);
1174 swap(label_[row], label_[row + 1]);
1175 InsetMathGrid::swapRow(row);
1179 void InsetMathHull::delRow(row_type row)
1181 if (nrows() <= 1 || !rowChangeOK())
1183 if (row + 1 == nrows() && type_ == hullMultline) {
1184 swap(numbered_[row - 1], numbered_[row]);
1185 swap(numbers_[row - 1], numbers_[row]);
1186 swap(label_[row - 1], label_[row]);
1187 InsetMathGrid::delRow(row);
1190 InsetMathGrid::delRow(row);
1191 // The last dummy row has no number info nor a label.
1192 // Test nrows() + 1 because we have already erased the row.
1193 if (row == nrows() + 1)
1195 numbered_.erase(numbered_.begin() + row);
1196 numbers_.erase(numbers_.begin() + row);
1198 label_.erase(label_.begin() + row);
1202 void InsetMathHull::addCol(col_type col)
1206 InsetMathGrid::addCol(col);
1210 void InsetMathHull::delCol(col_type col)
1212 if (ncols() <= 1 || !colChangeOK())
1214 InsetMathGrid::delCol(col);
1218 docstring InsetMathHull::nicelabel(row_type row) const
1222 docstring const & val = numbers_[row];
1224 return '(' + val + ')';
1225 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1229 void InsetMathHull::glueall(HullType type)
1232 for (idx_type i = 0; i < nargs(); ++i)
1234 InsetLabel * label = 0;
1235 if (type == hullEquation) {
1236 // preserve first non-empty label
1237 for (row_type row = 0; row < nrows(); ++row) {
1239 label = label_[row];
1245 *this = InsetMathHull(buffer_, hullSimple);
1252 void InsetMathHull::splitTo2Cols()
1254 LASSERT(ncols() == 1, return);
1255 InsetMathGrid::addCol(1);
1256 for (row_type row = 0; row < nrows(); ++row) {
1257 idx_type const i = 2 * row;
1258 pos_type pos = firstRelOp(cell(i));
1259 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1260 cell(i).erase(pos, cell(i).size());
1265 void InsetMathHull::splitTo3Cols()
1267 LASSERT(ncols() < 3, return);
1270 InsetMathGrid::addCol(2);
1271 for (row_type row = 0; row < nrows(); ++row) {
1272 idx_type const i = 3 * row + 1;
1273 if (!cell(i).empty()) {
1274 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1275 cell(i).erase(1, cell(i).size());
1281 void InsetMathHull::changeCols(col_type cols)
1283 if (ncols() == cols)
1285 else if (ncols() < cols) {
1291 while (ncols() < cols)
1292 InsetMathGrid::addCol(ncols());
1298 for (row_type row = 0; row < nrows(); ++row) {
1299 idx_type const i = row * ncols();
1300 for (col_type col = cols; col < ncols(); ++col) {
1301 cell(i + cols - 1).append(cell(i + col));
1305 while (ncols() > cols) {
1306 InsetMathGrid::delCol(ncols() - 1);
1311 HullType InsetMathHull::getType() const
1317 void InsetMathHull::setType(HullType type)
1324 bool InsetMathHull::isMutable(HullType type)
1348 void InsetMathHull::mutate(HullType newtype)
1350 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1352 if (newtype == type_)
1355 // This guards the algorithm below it, which is designed with certain types
1357 if (!isMutable(newtype) || !isMutable(type_)) {
1358 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1359 << "' to '" << to_utf8(hullName(newtype))
1360 << "' not implemented" << endl;
1364 // we try to move along the chain
1365 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1367 // +-------------------------------------+
1368 // we use eqnarray as intermediate type for mutations that are not
1369 // directly supported because it handles labels and numbering for
1374 setType(hullSimple);
1380 if (newtype == hullNone) {
1384 setType(hullEquation);
1385 numbered(0, label_[0] ? true : false);
1394 setType(hullSimple);
1399 // split it "nicely" on the first relop
1401 setType(hullEqnArray);
1409 // split it "nicely"
1444 setType(hullEqnArray);
1453 for (row_type row = 0; row < nrows(); ++row)
1454 numbered(row, false);
1464 for (row_type row = 0; row < nrows(); ++row)
1465 numbered(row, false);
1472 setType(hullEqnArray);
1502 for (row_type row = 0; row < nrows(); ++row)
1503 numbered(row, false);
1507 // first we mutate to EqnArray
1509 setType(hullEqnArray);
1516 // we passed the guard so we should not be here
1517 LASSERT("Mutation not implemented, but should have been.", return);
1523 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1524 bool last_eoln) const
1527 if (numberedType()) {
1528 if (label_[row] && numbered(row)) {
1529 docstring const name =
1530 latex ? escape(label_[row]->getParam("name"))
1531 : label_[row]->getParam("name");
1532 res += "\\label{" + name + '}';
1534 if (type_ != hullMultline) {
1535 if (numbered_[row] == NONUMBER)
1536 res += "\\nonumber ";
1537 else if (numbered_[row] == NOTAG)
1541 // Never add \\ on the last empty line of eqnarray and friends
1543 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1546 void InsetMathHull::write(WriteStream & os) const
1548 ModeSpecifier specifier(os, MATH_MODE);
1550 InsetMathGrid::write(os);
1555 void InsetMathHull::normalize(NormalStream & os) const
1557 os << "[formula " << hullName(type_) << ' ';
1558 InsetMathGrid::normalize(os);
1563 void InsetMathHull::infoize(odocstream & os) const
1565 os << bformat(_("Type: %1$s"), hullName(type_));
1569 void InsetMathHull::check() const
1571 LATTEST(numbered_.size() == nrows());
1572 LATTEST(numbers_.size() == nrows());
1573 LATTEST(label_.size() == nrows());
1577 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1581 idocstringstream iss(func.argument());
1582 iss >> dlang >> extra;
1584 extra = from_ascii("noextra");
1585 string const lang = to_ascii(dlang);
1587 // replace selection with result of computation
1588 if (reduceSelectionToOneCell(cur)) {
1590 asArray(grabAndEraseSelection(cur), ar);
1591 lyxerr << "use selection: " << ar << endl;
1592 cur.insert(pipeThroughExtern(lang, extra, ar));
1596 // only inline, display or eqnarray math is allowed
1597 switch (getType()) {
1603 frontend::Alert::warning(_("Bad math environment"),
1604 _("Computation cannot be performed for AMS "
1605 "math environments.\nChange the math "
1606 "formula type and try again."));
1611 eq.push_back(MathAtom(new InsetMathChar('=')));
1613 // go to first item in line
1614 cur.idx() -= cur.idx() % ncols();
1617 if (getType() == hullSimple) {
1618 size_type pos = cur.cell().find_last(eq);
1620 if (pos == cur.cell().size()) {
1622 lyxerr << "use whole cell: " << ar << endl;
1624 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1625 lyxerr << "use partial cell form pos: " << pos << endl;
1627 cur.cell().append(eq);
1628 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1629 cur.pos() = cur.lastpos();
1633 if (getType() == hullEquation) {
1634 lyxerr << "use equation inset" << endl;
1635 mutate(hullEqnArray);
1636 MathData & ar = cur.cell();
1637 lyxerr << "use cell: " << ar << endl;
1641 cur.cell() = pipeThroughExtern(lang, extra, ar);
1642 // move to end of line
1643 cur.pos() = cur.lastpos();
1648 lyxerr << "use eqnarray" << endl;
1649 cur.idx() += 2 - cur.idx() % ncols();
1651 MathData ar = cur.cell();
1652 lyxerr << "use cell: " << ar << endl;
1653 // FIXME: temporarily disabled
1659 cur.cell() = pipeThroughExtern(lang, extra, ar);
1660 cur.pos() = cur.lastpos();
1665 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1667 //lyxerr << "action: " << cmd.action() << endl;
1668 switch (cmd.action()) {
1670 case LFUN_FINISHED_BACKWARD:
1671 case LFUN_FINISHED_FORWARD:
1672 case LFUN_FINISHED_RIGHT:
1673 case LFUN_FINISHED_LEFT:
1674 //lyxerr << "action: " << cmd.action() << endl;
1675 InsetMathGrid::doDispatch(cur, cmd);
1678 case LFUN_PARAGRAPH_BREAK:
1679 // just swallow this
1682 case LFUN_NEWLINE_INSERT:
1683 // some magic for the common case
1684 if (type_ == hullSimple || type_ == hullEquation) {
1685 cur.recordUndoInset();
1687 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1688 mutate(align ? hullAlign : hullEqnArray);
1689 // mutate() may change labels and such.
1690 cur.forceBufferUpdate();
1691 cur.idx() = nrows() * ncols() - 1;
1692 cur.pos() = cur.lastpos();
1694 InsetMathGrid::doDispatch(cur, cmd);
1697 case LFUN_MATH_NUMBER_TOGGLE: {
1698 //lyxerr << "toggling all numbers" << endl;
1699 cur.recordUndoInset();
1700 bool old = numberedType();
1701 if (type_ == hullMultline)
1702 numbered(nrows() - 1, !old);
1704 for (row_type row = 0; row < nrows(); ++row)
1705 numbered(row, !old);
1707 cur.message(old ? _("No number") : _("Number"));
1708 cur.forceBufferUpdate();
1712 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1713 cur.recordUndoInset();
1714 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1715 bool old = numbered(r);
1716 cur.message(old ? _("No number") : _("Number"));
1718 cur.forceBufferUpdate();
1722 case LFUN_LABEL_INSERT: {
1723 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1724 docstring old_label = label(r);
1725 docstring const default_label = from_ascii("eq:");
1726 if (old_label.empty())
1727 old_label = default_label;
1729 InsetCommandParams p(LABEL_CODE);
1730 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1731 string const data = InsetCommand::params2string(p);
1733 if (cmd.argument().empty())
1734 cur.bv().showDialog("label", data);
1736 FuncRequest fr(LFUN_INSET_INSERT, data);
1742 case LFUN_LABEL_COPY_AS_REFERENCE: {
1744 if (cmd.argument().empty() && &cur.inset() == this)
1745 // if there is no argument and we're inside math, we retrieve
1746 // the row number from the cursor position.
1747 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1749 // if there is an argument, find the corresponding label, else
1750 // check whether there is at least one label.
1751 for (row = 0; row != nrows(); ++row)
1752 if (numbered(row) && label_[row]
1753 && (cmd.argument().empty() || label(row) == cmd.argument()))
1760 InsetCommandParams p(REF_CODE, "ref");
1761 p["reference"] = label(row);
1762 cap::clearSelection();
1763 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1767 case LFUN_WORD_DELETE_FORWARD:
1768 case LFUN_CHAR_DELETE_FORWARD:
1769 if (col(cur.idx()) + 1 == ncols()
1770 && cur.pos() == cur.lastpos()
1771 && !cur.selection()) {
1772 if (!label(row(cur.idx())).empty()) {
1773 cur.recordUndoInset();
1774 label(row(cur.idx()), docstring());
1775 } else if (numbered(row(cur.idx()))) {
1776 cur.recordUndoInset();
1777 numbered(row(cur.idx()), false);
1778 cur.forceBufferUpdate();
1780 InsetMathGrid::doDispatch(cur, cmd);
1784 InsetMathGrid::doDispatch(cur, cmd);
1789 case LFUN_INSET_INSERT: {
1790 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1791 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1792 string const name = cmd.getArg(0);
1793 if (name == "label") {
1794 InsetCommandParams p(LABEL_CODE);
1795 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1796 docstring str = p["name"];
1797 cur.recordUndoInset();
1798 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1802 docstring old = label(r);
1805 // The label will take care of the reference update.
1809 // Newly created inset so initialize it.
1810 label_[r]->initView();
1813 cur.forceBufferUpdate();
1816 InsetMathGrid::doDispatch(cur, cmd);
1820 case LFUN_MATH_EXTERN:
1821 cur.recordUndoInset();
1825 case LFUN_MATH_MUTATE: {
1826 cur.recordUndoInset();
1827 row_type row = cur.row();
1828 col_type col = cur.col();
1829 mutate(hullType(cmd.argument()));
1830 cur.idx() = row * ncols() + col;
1831 if (cur.idx() > cur.lastidx()) {
1832 cur.idx() = cur.lastidx();
1833 cur.pos() = cur.lastpos();
1835 if (cur.pos() > cur.lastpos())
1836 cur.pos() = cur.lastpos();
1838 cur.forceBufferUpdate();
1839 // FIXME: find some more clever handling of the selection,
1840 // i.e. preserve it.
1841 cur.clearSelection();
1842 //cur.dispatched(FINISHED);
1846 case LFUN_MATH_DISPLAY: {
1847 cur.recordUndoInset();
1848 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1849 // if the cursor is in a cell that got merged, move it to
1850 // start of the hull inset.
1851 if (cur.idx() > 0) {
1855 if (cur.pos() > cur.lastpos())
1856 cur.pos() = cur.lastpos();
1861 case LFUN_TABULAR_FEATURE:
1862 if (!allowsTabularFeatures())
1865 InsetMathGrid::doDispatch(cur, cmd);
1869 InsetMathGrid::doDispatch(cur, cmd);
1877 bool allowDisplayMath(Cursor const & cur)
1879 LATTEST(cur.depth() > 1);
1880 Cursor tmpcur = cur;
1883 FuncRequest cmd(LFUN_MATH_DISPLAY);
1884 return tmpcur.getStatus(cmd, status) && status.enabled();
1890 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1891 FuncStatus & status) const
1893 switch (cmd.action()) {
1894 case LFUN_FINISHED_BACKWARD:
1895 case LFUN_FINISHED_FORWARD:
1896 case LFUN_FINISHED_RIGHT:
1897 case LFUN_FINISHED_LEFT:
1900 case LFUN_NEWLINE_INSERT:
1901 case LFUN_MATH_EXTERN:
1903 status.setEnabled(true);
1906 // we never allow this in math, and we want to bind enter
1907 // to another actions in command-alternatives
1908 case LFUN_PARAGRAPH_BREAK:
1909 status.setEnabled(false);
1911 case LFUN_MATH_MUTATE: {
1912 HullType const ht = hullType(cmd.argument());
1913 status.setOnOff(type_ == ht);
1914 status.setEnabled(isMutable(ht) && isMutable(type_));
1916 if (ht != hullSimple && status.enabled())
1917 status.setEnabled(allowDisplayMath(cur));
1920 case LFUN_MATH_DISPLAY: {
1921 status.setEnabled(display() != Inline || allowDisplayMath(cur));
1922 status.setOnOff(display() != Inline);
1926 case LFUN_MATH_NUMBER_TOGGLE:
1927 // FIXME: what is the right test, this or the one of
1929 status.setEnabled(display() != Inline);
1930 status.setOnOff(numberedType());
1933 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1934 // FIXME: what is the right test, this or the one of
1936 bool const enable = (type_ == hullMultline)
1937 ? (nrows() - 1 == cur.row())
1938 : display() != Inline;
1939 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1940 status.setEnabled(enable);
1941 status.setOnOff(enable && numbered(r));
1945 case LFUN_LABEL_INSERT:
1946 status.setEnabled(type_ != hullSimple);
1949 case LFUN_LABEL_COPY_AS_REFERENCE: {
1950 bool enabled = false;
1952 if (cmd.argument().empty() && &cur.inset() == this) {
1953 // if there is no argument and we're inside math, we retrieve
1954 // the row number from the cursor position.
1955 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1956 enabled = numberedType() && label_[row] && numbered(row);
1958 // if there is an argument, find the corresponding label, else
1959 // check whether there is at least one label.
1960 for (row_type row = 0; row != nrows(); ++row) {
1961 if (numbered(row) && label_[row] &&
1962 (cmd.argument().empty() || label(row) == cmd.argument())) {
1968 status.setEnabled(enabled);
1972 case LFUN_INSET_INSERT:
1973 if (cmd.getArg(0) == "label") {
1974 status.setEnabled(type_ != hullSimple);
1977 return InsetMathGrid::getStatus(cur, cmd, status);
1979 case LFUN_TABULAR_FEATURE: {
1980 if (!allowsTabularFeatures())
1982 string s = cmd.getArg(0);
1984 && (s == "append-row"
1985 || s == "delete-row"
1986 || s == "copy-row")) {
1987 status.message(bformat(
1988 from_utf8(N_("Can't change number of rows in '%1$s'")),
1990 status.setEnabled(false);
1994 && (s == "append-column"
1995 || s == "delete-column"
1996 || s == "copy-column")) {
1997 status.message(bformat(
1998 from_utf8(N_("Can't change number of columns in '%1$s'")),
2000 status.setEnabled(false);
2003 if (s == "add-vline-left" || s == "add-vline-right") {
2004 status.message(bformat(
2005 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2007 status.setEnabled(false);
2010 if (s == "valign-top" || s == "valign-middle"
2011 || s == "valign-bottom" || s == "align-left"
2012 || s == "align-center" || s == "align-right") {
2013 status.setEnabled(false);
2016 return InsetMathGrid::getStatus(cur, cmd, status);
2020 return InsetMathGrid::getStatus(cur, cmd, status);
2023 // This cannot really happen, but inserted to shut-up gcc
2024 return InsetMathGrid::getStatus(cur, cmd, status);
2028 /////////////////////////////////////////////////////////////////////
2032 // simply scrap this function if you want
2033 void InsetMathHull::mutateToText()
2036 // translate to latex
2038 latex(os, false, false);
2039 string str = os.str();
2042 Text * lt = view_->cursor().innerText();
2043 string::const_iterator cit = str.begin();
2044 string::const_iterator end = str.end();
2045 for (; cit != end; ++cit)
2046 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2049 //dispatch(LFUN_ESCAPE);
2054 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2055 docstring const & font)
2057 // this whole function is a hack and won't work for incremental font
2060 if (cur.inset().asInsetMath()->name() == font)
2061 cur.handleFont(to_utf8(font));
2063 cur.handleNest(createInsetMath(font, cur.buffer()));
2069 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2074 font.fromString(to_utf8(arg), b);
2075 if (font.fontInfo().color() != Color_inherit) {
2076 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2077 cur.handleNest(at, 0);
2082 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2085 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
2086 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
2087 enter_front ? idxFirst(cur) : idxLast(cur);
2088 // The inset formula dimension is not necessarily the same as the
2089 // one of the instant preview image, so we have to indicate to the
2090 // BufferView that a metrics update is needed.
2091 cur.screenUpdateFlags(Update::Force);
2095 void InsetMathHull::revealCodes(Cursor & cur) const
2097 if (!cur.inMathed())
2099 odocstringstream os;
2101 cur.message(os.str());
2103 // write something to the minibuffer
2104 // translate to latex
2108 string str = os.str();
2110 string::size_type pos = 0;
2112 for (string::iterator it = str.begin(); it != str.end(); ++it) {
2115 else if (*it == '\0') {
2117 pos = it - str.begin();
2123 res = res.substr(pos - 30);
2124 if (res.size() > 60)
2125 res = res.substr(0, 60);
2131 /////////////////////////////////////////////////////////////////////
2135 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2138 // FIXME: completely broken
2139 static InsetMathHull * lastformula = 0;
2140 static CursorBase current = DocIterator(ibegin(nucleus()));
2142 static string laststr;
2144 if (lastformula != this || laststr != str) {
2145 //lyxerr << "reset lastformula to " << this << endl;
2148 current = ibegin(nucleus());
2150 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2154 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2156 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2157 CursorSlice & top = it.back();
2158 MathData const & a = top.asInsetMath()->cell(top.idx_);
2159 if (a.matchpart(ar, top.pos_)) {
2160 bv->cursor().setSelection(it, ar.size());
2162 top.pos_ += ar.size();
2168 //lyxerr << "not found!" << endl;
2175 void InsetMathHull::write(ostream & os) const
2177 odocstringstream oss;
2178 TexRow texrow(false);
2179 otexrowstream ots(oss,texrow);
2180 WriteStream wi(ots, false, false, WriteStream::wsDefault);
2183 os << to_utf8(oss.str());
2187 void InsetMathHull::read(Lexer & lex)
2190 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2191 operator=(*at->asHullInset());
2195 bool InsetMathHull::readQuiet(Lexer & lex)
2198 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2200 operator=(*at->asHullInset());
2205 int InsetMathHull::plaintext(odocstringstream & os,
2206 OutputParams const & op, size_t max_length) const
2208 // disables ASCII-art for export of equations. See #2275.
2209 if (0 && display()) {
2213 TextPainter tpain(dim.width(), dim.height());
2214 drawT(tpain, 0, dim.ascent());
2216 // reset metrics cache to "real" values
2218 return tpain.textheight();
2221 odocstringstream oss;
2222 TexRow texrow(false);
2223 otexrowstream ots(oss,texrow);
2224 Encoding const * const enc = encodings.fromLyXName("utf8");
2225 WriteStream wi(ots, false, true, WriteStream::wsDefault, enc);
2228 if (type_ == hullRegexp)
2231 for (row_type r = 0; r < nrows(); ++r) {
2232 for (col_type c = 0; c < ncols(); ++c)
2233 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2234 // if it's for the TOC, we write just the first line
2235 // and do not include the newline.
2236 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2238 if (r < nrows() - 1)
2242 docstring const str = oss.str();
2248 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
2253 if (getType() == hullSimple)
2254 name = from_ascii("inlineequation");
2256 name = from_ascii("informalequation");
2258 docstring bname = name;
2259 if (!label(0).empty())
2260 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
2262 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
2264 odocstringstream ls;
2266 otexstream ols(ls, texrow);
2267 if (runparams.flavor == OutputParams::XML) {
2268 ms << MTag("alt role='tex' ");
2269 // Workaround for db2latex: db2latex always includes equations with
2270 // \ensuremath{} or \begin{display}\end{display}
2271 // so we strip LyX' math environment
2272 WriteStream wi(ols, false, false, WriteStream::wsDefault, runparams.encoding);
2273 InsetMathGrid::write(wi);
2274 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2279 InsetMathGrid::mathmlize(ms);
2282 ms << MTag("alt role='tex'");
2283 latex(ols, runparams);
2284 res = texrow.rows();
2285 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2289 ms << from_ascii("<graphic fileref=\"eqn/");
2290 if (!label(0).empty())
2291 ms << sgml::cleanID(buffer(), runparams, label(0));
2293 ms << sgml::uniqueID(from_ascii("anon"));
2295 if (runparams.flavor == OutputParams::XML)
2296 ms << from_ascii("\"/>");
2298 ms << from_ascii("\">");
2300 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2302 return ms.line() + res;
2306 bool InsetMathHull::haveNumbers() const
2308 bool havenumbers = false;
2309 // inline formulas are never numbered (bug 7351 part 3)
2310 if (getType() == hullSimple)
2312 for (size_t i = 0; i != numbered_.size(); ++i) {
2323 // We need to do something about alignment here.
2325 // This duplicates code from InsetMathGrid, but
2326 // we need access here to number information,
2327 // and we simply do not have that in InsetMathGrid.
2328 void InsetMathHull::htmlize(HtmlStream & os) const
2330 bool const havenumbers = haveNumbers();
2331 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2334 os << cell(index(0, 0));
2338 os << MTag("table", "class='mathtable'");
2339 for (row_type row = 0; row < nrows(); ++row) {
2341 for (col_type col = 0; col < ncols(); ++col) {
2343 os << cell(index(row, col));
2348 docstring const & num = numbers_[row];
2350 os << '(' << num << ')';
2355 os << ETag("table");
2359 // this duplicates code from InsetMathGrid, but
2360 // we need access here to number information,
2361 // and we simply do not have that in InsetMathGrid.
2362 void InsetMathHull::mathmlize(MathStream & os) const
2364 bool const havenumbers = haveNumbers();
2365 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2368 os << MTag("mtable");
2369 char const * const celltag = havetable ? "mtd" : "mrow";
2370 // FIXME There does not seem to be wide support at the moment
2371 // for mlabeledtr, so we have to use just mtr for now.
2372 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2373 char const * const rowtag = "mtr";
2374 for (row_type row = 0; row < nrows(); ++row) {
2377 for (col_type col = 0; col < ncols(); ++col) {
2379 << cell(index(row, col))
2385 docstring const & num = numbers_[row];
2387 os << '(' << num << ')';
2394 os << ETag("mtable");
2398 void InsetMathHull::mathAsLatex(WriteStream & os) const
2400 MathEnsurer ensurer(os, false);
2401 bool havenumbers = haveNumbers();
2402 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2405 os << cell(index(0, 0));
2409 os << "<table class='mathtable'>";
2410 for (row_type row = 0; row < nrows(); ++row) {
2412 for (col_type col = 0; col < ncols(); ++col) {
2413 os << "<td class='math'>";
2414 os << cell(index(row, col));
2419 docstring const & num = numbers_[row];
2421 os << '(' << num << ')';
2430 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2432 BufferParams::MathOutput const mathtype =
2433 buffer().masterBuffer()->params().html_math_output;
2435 bool success = false;
2437 // we output all the labels just at the beginning of the equation.
2438 // this should be fine.
2439 for (size_t i = 0; i != label_.size(); ++i) {
2440 InsetLabel const * const il = label_[i];
2446 // FIXME Eventually we would like to do this inset by inset.
2447 if (mathtype == BufferParams::MathML) {
2448 odocstringstream os;
2453 } catch (MathExportException const &) {}
2455 if (getType() == hullSimple)
2456 xs << html::StartTag("math",
2457 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2459 xs << html::StartTag("math",
2460 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2461 xs << XHTMLStream::ESCAPE_NONE
2463 << html::EndTag("math");
2465 } else if (mathtype == BufferParams::HTML) {
2466 odocstringstream os;
2471 } catch (MathExportException const &) {}
2473 string const tag = (getType() == hullSimple) ? "span" : "div";
2474 xs << html::StartTag(tag, "class='formula'", true)
2475 << XHTMLStream::ESCAPE_NONE
2477 << html::EndTag(tag);
2481 // what we actually want is this:
2483 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2485 // || mathtype == BufferParams::Images
2487 // but what follows is equivalent, since we'll enter only if either (a) we
2488 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2489 // aren't doing LaTeX.
2491 // so this is for Images.
2492 if (!success && mathtype != BufferParams::LaTeX) {
2493 graphics::PreviewImage const * pimage = 0;
2495 loadPreview(docit_);
2496 pimage = preview_->getPreviewImage(buffer());
2497 // FIXME Do we always have png?
2500 if (pimage || op.dryrun) {
2501 string const filename = pimage ? pimage->filename().onlyFileName()
2502 : "previewimage.png";
2504 // if we are not in the master buffer, then we need to see that the
2505 // generated image is copied there; otherwise, preview fails.
2506 Buffer const * mbuf = buffer().masterBuffer();
2507 if (mbuf != &buffer()) {
2508 string mbtmp = mbuf->temppath();
2509 FileName const mbufimg(support::addName(mbtmp, filename));
2510 pimage->filename().copyTo(mbufimg);
2512 // add the file to the list of files to be exported
2513 op.exportdata->addExternalFile("xhtml", pimage->filename());
2516 string const tag = (getType() == hullSimple) ? "span" : "div";
2518 << html::StartTag(tag, "style = \"text-align: center;\"")
2519 << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2520 << html::EndTag(tag)
2526 // so we'll pass this test if we've failed everything else, or
2527 // if mathtype was LaTeX, since we won't have entered any of the
2529 if (!success /* || mathtype != BufferParams::LaTeX */) {
2530 // Unfortunately, we cannot use latexString() because we do not want
2531 // $...$ or whatever.
2532 odocstringstream ls;
2533 TexRow texrow(false);
2534 otexrowstream ots(ls,texrow);
2535 WriteStream wi(ots, false, true, WriteStream::wsPreview);
2536 ModeSpecifier specifier(wi, MATH_MODE);
2538 docstring const latex = ls.str();
2540 // class='math' allows for use of jsMath
2541 // http://www.math.union.edu/~dpvc/jsMath/
2543 // probably should allow for some kind of customization here
2544 string const tag = (getType() == hullSimple) ? "span" : "div";
2545 xs << html::StartTag(tag, "class='math'")
2547 << html::EndTag(tag)
2554 void InsetMathHull::toString(odocstream & os) const
2556 odocstringstream ods;
2557 plaintext(ods, OutputParams(0));
2562 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2564 odocstringstream ods;
2567 // FIXME: this results in spilling TeX into the LyXHTML output since the
2568 // outliner is used to generate the LyXHTML list of figures/etc.
2574 string InsetMathHull::contextMenuName() const
2576 return "context-math";
2580 void InsetMathHull::recordLocation(DocIterator const & di)