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/debug.h"
63 #include "support/gettext.h"
64 #include "support/filetools.h"
65 #include "support/lassert.h"
66 #include "support/lstrings.h"
67 #include "support/RefChanger.h"
72 using namespace lyx::support;
76 using cap::grabAndEraseSelection;
77 using cap::reduceSelectionToOneCell;
81 int getCols(HullType type)
106 // returns position of first relation operator in the array
107 // used for "intelligent splitting"
108 size_t firstRelOp(MathData const & ar)
110 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
111 if ((*it)->isMathRel())
112 return it - ar.begin();
117 char const * star(bool numbered)
119 return numbered ? "" : "*";
123 } // end anon namespace
126 HullType hullType(docstring const & s)
128 if (s == "none") return hullNone;
129 if (s == "simple") return hullSimple;
130 if (s == "equation") return hullEquation;
131 if (s == "eqnarray") return hullEqnArray;
132 if (s == "align") return hullAlign;
133 if (s == "alignat") return hullAlignAt;
134 if (s == "xalignat") return hullXAlignAt;
135 if (s == "xxalignat") return hullXXAlignAt;
136 if (s == "multline") return hullMultline;
137 if (s == "gather") return hullGather;
138 if (s == "flalign") return hullFlAlign;
139 if (s == "regexp") return hullRegexp;
140 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
145 docstring hullName(HullType type)
148 case hullNone: return from_ascii("none");
149 case hullSimple: return from_ascii("simple");
150 case hullEquation: return from_ascii("equation");
151 case hullEqnArray: return from_ascii("eqnarray");
152 case hullAlign: return from_ascii("align");
153 case hullAlignAt: return from_ascii("alignat");
154 case hullXAlignAt: return from_ascii("xalignat");
155 case hullXXAlignAt: return from_ascii("xxalignat");
156 case hullMultline: return from_ascii("multline");
157 case hullGather: return from_ascii("gather");
158 case hullFlAlign: return from_ascii("flalign");
159 case hullRegexp: return from_ascii("regexp");
161 lyxerr << "unknown hull type" << endl;
164 return from_ascii("none");
167 static InsetLabel * dummy_pointer = 0;
169 InsetMathHull::InsetMathHull(Buffer * buf)
170 : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, NUMBER),
171 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
172 preview_(new RenderPreview(this))
174 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
175 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
176 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
177 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
184 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
185 : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, NUMBER),
186 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
187 preview_(new RenderPreview(this))
195 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
201 InsetMathHull::~InsetMathHull()
203 for (size_t i = 0; i < label_.size(); ++i)
208 Inset * InsetMathHull::clone() const
210 return new InsetMathHull(*this);
214 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
218 InsetMathGrid::operator=(other);
220 numbered_ = other.numbered_;
221 numbers_ = other.numbers_;
222 buffer_ = other.buffer_;
223 for (size_t i = 0; i < label_.size(); ++i)
225 label_ = other.label_;
226 for (size_t i = 0; i != label_.size(); ++i) {
228 label_[i] = new InsetLabel(*label_[i]);
230 preview_.reset(new RenderPreview(*other.preview_, this));
236 void InsetMathHull::setBuffer(Buffer & buffer)
238 InsetMathGrid::setBuffer(buffer);
240 for (size_t i = 0; i != label_.size(); ++i) {
242 label_[i]->setBuffer(buffer);
247 // FIXME This should really be controlled by the TOC level, or
248 // something of the sort.
250 const char * counters_to_save[] = {"section", "chapter"};
251 unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
255 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
258 //FIXME: buffer_ should be set at creation for this inset! Problem is
259 // This inset is created at too many places (see Parser::parse1() in
264 // if any of the equations are numbered, then we want to save the values
265 // of some of the counters.
267 BufferParams const & bp = buffer_->params();
268 string const & lang = it->getParLanguage(bp)->code();
270 buffer_->masterBuffer()->params().documentClass().counters();
272 // right now, we only need to do this at export time
273 if (utype == OutputUpdate) {
274 for (size_t i = 0; i < numcnts; ++i) {
275 docstring const cnt = from_ascii(counters_to_save[i]);
276 if (cnts.hasCounter(cnt))
277 counter_map[cnt] = cnts.value(cnt);
281 // this has to be done separately
282 docstring const eqstr = from_ascii("equation");
283 if (cnts.hasCounter(eqstr)) {
284 if (utype == OutputUpdate)
285 counter_map[eqstr] = cnts.value(eqstr);
286 for (size_t i = 0; i != label_.size(); ++i) {
288 cnts.step(eqstr, utype);
289 numbers_[i] = cnts.theCounter(eqstr, lang);
291 numbers_[i] = empty_docstring();
297 for (size_t i = 0; i != label_.size(); ++i) {
299 label_[i]->updateBuffer(it, utype);
302 InsetMathGrid::updateBuffer(it, utype);
306 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active,
307 UpdateType utype) const
310 //FIXME: buffer_ should be set at creation for this inset! Problem is
311 // This inset is created at too many places (see Parser::parse1() in
316 shared_ptr<Toc> toc = buffer().tocBackend().toc("equation");
318 for (row_type row = 0; row != nrows(); ++row) {
322 label_[row]->addToToc(pit, output_active, utype);
323 toc->push_back(TocItem(pit, 0, nicelabel(row), output_active));
328 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
330 if (previewState(&cur.bv())) {
334 return InsetMathNest::editXY(cur, x, y);
338 InsetMath::mode_type InsetMathHull::currentMode() const
342 return UNDECIDED_MODE;
344 // definitely math mode ...
364 bool InsetMathHull::idxFirst(Cursor & cur) const
372 bool InsetMathHull::idxLast(Cursor & cur) const
374 cur.idx() = nargs() - 1;
375 cur.pos() = cur.lastpos();
380 // FIXME: InsetMathGrid should be changed to let the real column alignment be
381 // given by a virtual method like displayColAlign, because the values produced
382 // by defaultColAlign can be invalidated by lfuns such as add-column. For the
383 // moment the values produced by defaultColAlign are not used, notably because
384 // alignment is not implemented in the LyXHTML output.
385 char InsetMathHull::defaultColAlign(col_type col)
387 return colAlign(type_, col);
391 char InsetMathHull::displayColAlign(idx_type idx) const
395 row_type const r = row(idx);
398 if (r == nrows() - 1)
409 return colAlign(type_, col(idx));
413 return InsetMathGrid::displayColAlign(idx);
417 int InsetMathHull::displayColSpace(col_type col) const
419 return colSpace(type_, col);
423 // FIXME: same comment as for defaultColAlign applies.
424 int InsetMathHull::defaultColSpace(col_type col)
426 return colSpace(type_, col);
430 string InsetMathHull::standardFont() const
436 return "lyxnochange";
443 ColorCode InsetMathHull::standardColor() const
448 return Color_foreground;
456 bool InsetMathHull::previewState(const BufferView *const bv) const
458 if (!editing(bv) && RenderPreview::previewMath()
459 && type_ != hullRegexp)
461 graphics::PreviewImage const * pimage =
462 preview_->getPreviewImage(bv->buffer());
463 return pimage && pimage->image();
470 static const int ERROR_FRAME_WIDTH = 2;
473 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
475 if (previewState(mi.base.bv)) {
476 preview_->metrics(mi, dim);
477 if (previewTooSmall(dim)) {
478 // preview image is too small
479 dim.wid += 2 * ERROR_FRAME_WIDTH;
480 dim.asc += 2 * ERROR_FRAME_WIDTH;
482 // insert a one pixel gap in front of the formula
485 dim.des += displayMargin();
487 // Cache the inset dimension.
488 setDimCache(mi, dim);
492 // FIXME: Changing the same object repeatedly is inefficient.
493 Changer dummy1 = mi.base.changeFontSet(standardFont());
494 Changer dummy2 = mi.base.changeStyle(display() ? LM_ST_DISPLAY : LM_ST_TEXT);
496 // let the cells adjust themselves
497 InsetMathGrid::metrics(mi, dim);
500 dim.asc += displayMargin();
501 dim.des += displayMargin();
504 if (numberedType()) {
505 Changer dummy = mi.base.changeFontSet("mathbf");
507 for (row_type row = 0; row < nrows(); ++row)
508 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
514 if (type_ == hullRegexp)
516 // make it at least as high as the current font
519 math_font_max_dim(mi.base.font, asc, des);
520 dim.asc = max(dim.asc, asc);
521 dim.des = max(dim.des, des);
522 // Cache the inset dimension.
523 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
524 setDimCache(mi, dim);
528 bool InsetMathHull::previewTooSmall(Dimension const & dim) const
530 return dim.width() <= 10 && dim.height() <= 10;
534 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
536 BufferView const * const bv = pi.base.bv;
537 if (previewState(bv)) {
538 Dimension const dim = dimension(*pi.base.bv);
539 if (previewTooSmall(dim))
541 return graphics::PreviewLoader::backgroundColor();
547 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
549 Dimension const dim = dimension(*pi.base.bv);
550 if (previewTooSmall(dim)) {
551 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
552 dim.wid, dim.asc + dim.des, backgroundColor(pi));
555 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
556 dim.asc + dim.des - 1, pi.backgroundColor(this));
560 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
562 BufferView const * const bv = pi.base.bv;
563 Dimension const dim = dimension(*bv);
565 if (type_ == hullRegexp) {
566 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
567 dim.width() - 2, dim.height() - 2, Color_regexpframe);
570 if (previewState(bv)) {
571 // Do not draw change tracking cue if taken care of by RowPainter
573 Changer dummy = make_change(pi.change_, Change(), !canPaintChange(*bv));
574 if (previewTooSmall(dim)) {
575 // we have an extra frame
576 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
578 // one pixel gap in front
579 preview_->draw(pi, x + 1, y);
581 setPosCache(pi, x, y);
585 ColorCode color = pi.selected && lyxrc.use_system_colors
586 ? Color_selectiontext : standardColor();
587 bool const really_change_color = pi.base.font.color() == Color_none;
588 Changer dummy0 = pi.base.font.changeColor(color, really_change_color);
589 Changer dummy1 = pi.base.changeFontSet(standardFont());
590 Changer dummy2 = pi.base.changeStyle(display() ? LM_ST_DISPLAY : LM_ST_TEXT);
592 InsetMathGrid::draw(pi, x + 1, y);
594 if (numberedType()) {
595 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
596 for (row_type row = 0; row < nrows(); ++row) {
597 int const yy = y + rowinfo_[row].offset_;
598 Changer dummy = pi.base.changeFontSet("mathrm");
599 docstring const nl = nicelabel(row);
603 // drawing change line
604 if (canPaintChange(*bv))
605 pi.change_.paintCue(pi, x + 1, y + 1 - dim.asc,
606 x + dim.wid, y + dim.des);
607 setPosCache(pi, x, y);
611 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
614 InsetMathGrid::metricsT(mi, dim);
617 TexRow texrow(false);
618 otexrowstream ots(os,texrow);
619 WriteStream wi(ots, false, true, WriteStream::wsDefault);
621 dim.wid = os.str().size();
628 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
631 InsetMathGrid::drawT(pain, x, y);
634 TexRow texrow(false);
635 otexrowstream ots(os,texrow);
636 WriteStream wi(ots, false, true, WriteStream::wsDefault);
638 pain.draw(x, y, os.str().c_str());
643 static docstring latexString(InsetMathHull const & inset)
646 // This has to be static, because a preview snippet or a math
647 // macro containing math in text mode (such as $\text{$\phi$}$ or
648 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
649 // first time as a whole, and the second time only the inner math.
650 // In this last case inset.buffer() would be invalid.
651 static Encoding const * encoding = 0;
652 if (inset.isBufferValid())
653 encoding = &(inset.buffer().params().encoding());
654 TexRow texrow(false);
655 otexrowstream ots(ls,texrow);
656 WriteStream wi(ots, false, true, WriteStream::wsPreview, encoding);
662 void InsetMathHull::initUnicodeMath() const
664 // Trigger classification of the unicode symbols in this inset
665 docstring const dummy = latexString(*this);
669 void InsetMathHull::addPreview(DocIterator const & inset_pos,
670 graphics::PreviewLoader & /*ploader*/) const
672 if (RenderPreview::previewMath()) {
673 preparePreview(inset_pos);
678 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
679 MacroNameSet & macros, MacroNameSet & defs) const
681 MacroNameSet::iterator const end = macros.end();
683 for (size_t i = 0; i < md.size(); ++i) {
684 MathMacro const * mi = md[i].nucleus()->asMacro();
685 MathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
686 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
687 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
688 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
689 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
691 // Look for macros in the arguments of this macro.
692 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
693 usedMacros(mi->cell(idx), pos, macros, defs);
694 // Make sure this is a macro defined in the document
695 // (as we also spot the macros in the symbols file)
696 // or that we have not already accounted for it.
697 docstring const name = mi->name();
698 if (macros.find(name) == end)
701 // Look for macros in the definition of this macro.
702 MathData ar(pos.buffer());
703 MacroData const * data =
704 pos.buffer()->getMacro(name, pos, true);
706 odocstringstream macro_def;
707 data->write(macro_def, true);
709 defs.insert(macro_def.str());
710 asArray(data->definition(), ar);
712 usedMacros(ar, pos, macros, defs);
714 MathData ar(pos.buffer());
715 asArray(mt->definition(), ar);
716 usedMacros(ar, pos, macros, defs);
718 if (!si->nuc().empty())
719 usedMacros(si->nuc(), pos, macros, defs);
721 usedMacros(si->down(), pos, macros, defs);
723 usedMacros(si->up(), pos, macros, defs);
724 } else if (fi || gi) {
725 idx_type nidx = fi ? fi->nargs() : gi->nargs();
726 for (idx_type idx = 0; idx < nidx; ++idx)
727 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
730 usedMacros(ni->cell(0), pos, macros, defs);
736 void InsetMathHull::preparePreview(DocIterator const & pos,
737 bool forexport) const
739 // there is no need to do all the macro stuff if we're not
740 // actually going to generate the preview.
741 if (!RenderPreview::previewMath() && !forexport)
744 Buffer const * buffer = pos.buffer();
746 // collect macros at this position
748 buffer->listMacroNames(macros);
750 // collect definitions only for the macros used in this inset
752 for (idx_type idx = 0; idx < nargs(); ++idx)
753 usedMacros(cell(idx), pos, macros, defs);
755 MacroNameSet::iterator it = defs.begin();
756 MacroNameSet::iterator end = defs.end();
757 docstring macro_preamble;
758 for (; it != end; ++it)
759 macro_preamble.append(*it);
761 // set the font series and size for this snippet
762 DocIterator dit = pos.getInnerText();
763 Paragraph const & par = dit.paragraph();
764 Font font = par.getFontSettings(buffer->params(), dit.pos());
765 font.fontInfo().realize(par.layout().font);
766 string const lsize = font.latexSize();
769 if (font.fontInfo().series() == BOLD_SERIES) {
770 setfont += from_ascii("\\textbf{");
773 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
774 setfont += from_ascii("\\" + lsize + '\n');
777 if (forexport && haveNumbers()) {
778 docstring eqstr = from_ascii("equation");
779 CounterMap::const_iterator it = counter_map.find(eqstr);
780 if (it != counter_map.end()) {
781 int num = it->second;
783 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
784 '{' + convert<docstring>(num) + '}' + '\n';
786 for (size_t i = 0; i != numcnts; ++i) {
787 docstring cnt = from_ascii(counters_to_save[i]);
788 it = counter_map.find(cnt);
789 if (it == counter_map.end())
791 int num = it->second;
793 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
794 '{' + convert<docstring>(num) + '}';
797 docstring const snippet = macro_preamble + setfont + setcnt
798 + latexString(*this) + endfont;
799 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
800 preview_->addPreview(snippet, *buffer, forexport);
804 void InsetMathHull::reloadPreview(DocIterator const & pos) const
807 preview_->startLoading(*pos.buffer());
811 void InsetMathHull::loadPreview(DocIterator const & pos) const
813 bool const forexport = true;
814 preparePreview(pos, forexport);
815 preview_->startLoading(*pos.buffer(), forexport);
819 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
821 if (RenderPreview::previewMath()) {
823 cur.screenUpdateFlags(Update::Force);
829 docstring InsetMathHull::label(row_type row) const
831 LASSERT(row < nrows(), return docstring());
832 if (InsetLabel * il = label_[row])
833 return il->screenLabel();
838 void InsetMathHull::label(row_type row, docstring const & label)
840 //lyxerr << "setting label '" << label << "' for row " << row << endl;
844 label_[row] = dummy_pointer;
847 label_[row]->updateLabelAndRefs(label);
849 label_[row]->setParam("name", label);
853 InsetCommandParams p(LABEL_CODE);
855 label_[row] = new InsetLabel(buffer_, p);
857 label_[row]->setBuffer(buffer());
861 void InsetMathHull::numbered(row_type row, Numbered num)
863 numbered_[row] = num;
864 if (!numbered(row) && label_[row]) {
871 bool InsetMathHull::numbered(row_type row) const
873 return numbered_[row] == NUMBER;
877 bool InsetMathHull::ams() const
897 for (size_t row = 0; row < numbered_.size(); ++row)
898 if (numbered_[row] == NOTAG)
904 Inset::DisplayType InsetMathHull::display() const
927 bool InsetMathHull::numberedType() const
946 for (row_type row = 0; row < nrows(); ++row)
953 void InsetMathHull::validate(LaTeXFeatures & features) const
955 if (features.runparams().isLaTeX()) {
957 features.require("amsmath");
959 if (type_ == hullRegexp) {
960 features.require("color");
961 string frcol = lcolor.getLaTeXName(Color_regexpframe);
962 string bgcol = "white";
963 features.addPreambleSnippet(
964 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
965 + frcol + string("}{")
966 + bgcol + string("}{\\ensuremath{\\mathtt{#1}}}}"));
967 features.addPreambleSnippet(
968 string("\\newcommand{\\endregexp}{}"));
971 // Validation is necessary only if not using AMS math.
972 // To be safe, we will always run mathedvalidate.
973 //if (features.amsstyle)
976 //features.binom = true;
977 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
978 // it would be better to do this elsewhere, but we can't validate in
979 // InsetMathMatrix and we have no way, outside MathExtern, to know if
980 // we even have any matrices.
981 features.addCSSSnippet(
982 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
983 "table.matrix td{padding: 0.25px;}\n"
984 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
985 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
987 InsetMathGrid::validate(features);
991 void InsetMathHull::header_write(WriteStream & os) const
993 bool n = numberedType();
1002 if (cell(0).empty())
1010 os << "\\begin{equation" << star(n) << "}\n";
1022 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1029 os << "\\begin{" << hullName(type_) << star(n) << '}'
1030 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1036 os << "\\begin{" << hullName(type_) << '}'
1037 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1047 os << "\\begin{unknown" << star(n) << "}\n";
1053 void InsetMathHull::footer_write(WriteStream & os) const
1055 bool n = numberedType();
1070 os << "\\end{equation" << star(n) << "}\n";
1084 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1090 os << "\\end{" << hullName(type_) << "}\n";
1094 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1095 os << "\\endregexp{}}";
1101 os << "\\end{unknown" << star(n) << "}\n";
1107 bool InsetMathHull::allowsTabularFeatures() const
1130 bool InsetMathHull::rowChangeOK() const
1133 type_ == hullEqnArray || type_ == hullAlign ||
1134 type_ == hullFlAlign || type_ == hullAlignAt ||
1135 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1136 type_ == hullGather || type_ == hullMultline;
1140 bool InsetMathHull::colChangeOK() const
1143 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1144 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1148 void InsetMathHull::addRow(row_type row)
1153 bool numbered = numberedType();
1154 // Move the number and raw pointer, do not call label() (bug 7511)
1155 InsetLabel * label = dummy_pointer;
1156 docstring number = empty_docstring();
1157 if (type_ == hullMultline) {
1158 if (row + 1 == nrows()) {
1159 numbered_[row] = NONUMBER;
1160 swap(label, label_[row]);
1161 swap(number, numbers_[row]);
1166 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1167 numbers_.insert(numbers_.begin() + row + 1, number);
1168 label_.insert(label_.begin() + row + 1, label);
1169 InsetMathGrid::addRow(row);
1173 void InsetMathHull::swapRow(row_type row)
1177 if (row + 1 == nrows())
1179 swap(numbered_[row], numbered_[row + 1]);
1180 swap(numbers_[row], numbers_[row + 1]);
1181 swap(label_[row], label_[row + 1]);
1182 InsetMathGrid::swapRow(row);
1186 void InsetMathHull::delRow(row_type row)
1188 if (nrows() <= 1 || !rowChangeOK())
1190 if (row + 1 == nrows() && type_ == hullMultline) {
1191 swap(numbered_[row - 1], numbered_[row]);
1192 swap(numbers_[row - 1], numbers_[row]);
1193 swap(label_[row - 1], label_[row]);
1194 InsetMathGrid::delRow(row);
1197 InsetMathGrid::delRow(row);
1198 // The last dummy row has no number info nor a label.
1199 // Test nrows() + 1 because we have already erased the row.
1200 if (row == nrows() + 1)
1202 numbered_.erase(numbered_.begin() + row);
1203 numbers_.erase(numbers_.begin() + row);
1205 label_.erase(label_.begin() + row);
1209 void InsetMathHull::addCol(col_type col)
1213 InsetMathGrid::addCol(col);
1217 void InsetMathHull::delCol(col_type col)
1219 if (ncols() <= 1 || !colChangeOK())
1221 InsetMathGrid::delCol(col);
1225 docstring InsetMathHull::nicelabel(row_type row) const
1229 docstring const & val = numbers_[row];
1231 return '(' + val + ')';
1232 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1236 void InsetMathHull::glueall(HullType type)
1239 for (idx_type i = 0; i < nargs(); ++i)
1241 InsetLabel * label = 0;
1242 if (type == hullEquation) {
1243 // preserve first non-empty label
1244 for (row_type row = 0; row < nrows(); ++row) {
1246 label = label_[row];
1252 *this = InsetMathHull(buffer_, hullSimple);
1259 void InsetMathHull::splitTo2Cols()
1261 LASSERT(ncols() == 1, return);
1262 InsetMathGrid::addCol(1);
1263 for (row_type row = 0; row < nrows(); ++row) {
1264 idx_type const i = 2 * row;
1265 pos_type pos = firstRelOp(cell(i));
1266 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1267 cell(i).erase(pos, cell(i).size());
1272 void InsetMathHull::splitTo3Cols()
1274 LASSERT(ncols() < 3, return);
1277 InsetMathGrid::addCol(2);
1278 for (row_type row = 0; row < nrows(); ++row) {
1279 idx_type const i = 3 * row + 1;
1280 if (!cell(i).empty()) {
1281 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1282 cell(i).erase(1, cell(i).size());
1288 void InsetMathHull::changeCols(col_type cols)
1290 if (ncols() == cols)
1292 else if (ncols() < cols) {
1298 while (ncols() < cols)
1299 InsetMathGrid::addCol(ncols());
1305 for (row_type row = 0; row < nrows(); ++row) {
1306 idx_type const i = row * ncols();
1307 for (col_type col = cols; col < ncols(); ++col) {
1308 cell(i + cols - 1).append(cell(i + col));
1312 while (ncols() > cols) {
1313 InsetMathGrid::delCol(ncols() - 1);
1318 HullType InsetMathHull::getType() const
1324 void InsetMathHull::setType(HullType type)
1331 bool InsetMathHull::isMutable(HullType type)
1355 void InsetMathHull::mutate(HullType newtype)
1357 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1359 if (newtype == type_)
1362 // This guards the algorithm below it, which is designed with certain types
1364 if (!isMutable(newtype) || !isMutable(type_)) {
1365 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1366 << "' to '" << to_utf8(hullName(newtype))
1367 << "' not implemented" << endl;
1371 // we try to move along the chain
1372 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1374 // +-------------------------------------+
1375 // we use eqnarray as intermediate type for mutations that are not
1376 // directly supported because it handles labels and numbering for
1381 setType(hullSimple);
1387 if (newtype == hullNone) {
1391 setType(hullEquation);
1392 numbered(0, label_[0] ? true : false);
1401 setType(hullSimple);
1406 // split it "nicely" on the first relop
1408 setType(hullEqnArray);
1416 // split it "nicely"
1451 setType(hullEqnArray);
1460 for (row_type row = 0; row < nrows(); ++row)
1461 numbered(row, false);
1471 for (row_type row = 0; row < nrows(); ++row)
1472 numbered(row, false);
1479 setType(hullEqnArray);
1509 for (row_type row = 0; row < nrows(); ++row)
1510 numbered(row, false);
1514 // first we mutate to EqnArray
1516 setType(hullEqnArray);
1523 // we passed the guard so we should not be here
1524 LASSERT("Mutation not implemented, but should have been.", return);
1530 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1531 bool last_eoln) const
1534 if (numberedType()) {
1535 if (label_[row] && numbered(row)) {
1536 docstring const name =
1537 latex ? escape(label_[row]->getParam("name"))
1538 : label_[row]->getParam("name");
1539 res += "\\label{" + name + '}';
1541 if (type_ != hullMultline) {
1542 if (numbered_[row] == NONUMBER)
1543 res += "\\nonumber ";
1544 else if (numbered_[row] == NOTAG)
1548 // Never add \\ on the last empty line of eqnarray and friends
1550 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1553 void InsetMathHull::write(WriteStream & os) const
1555 ModeSpecifier specifier(os, MATH_MODE);
1557 InsetMathGrid::write(os);
1562 void InsetMathHull::normalize(NormalStream & os) const
1564 os << "[formula " << hullName(type_) << ' ';
1565 InsetMathGrid::normalize(os);
1570 void InsetMathHull::infoize(odocstream & os) const
1572 os << bformat(_("Type: %1$s"), hullName(type_));
1576 void InsetMathHull::check() const
1578 LATTEST(numbered_.size() == nrows());
1579 LATTEST(numbers_.size() == nrows());
1580 LATTEST(label_.size() == nrows());
1584 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1588 idocstringstream iss(func.argument());
1589 iss >> dlang >> extra;
1591 extra = from_ascii("noextra");
1592 string const lang = to_ascii(dlang);
1594 // replace selection with result of computation
1595 if (reduceSelectionToOneCell(cur)) {
1597 asArray(grabAndEraseSelection(cur), ar);
1598 lyxerr << "use selection: " << ar << endl;
1599 cur.insert(pipeThroughExtern(lang, extra, ar));
1603 // only inline, display or eqnarray math is allowed
1604 switch (getType()) {
1610 frontend::Alert::warning(_("Bad math environment"),
1611 _("Computation cannot be performed for AMS "
1612 "math environments.\nChange the math "
1613 "formula type and try again."));
1618 eq.push_back(MathAtom(new InsetMathChar('=')));
1620 // go to first item in line
1621 cur.idx() -= cur.idx() % ncols();
1624 if (getType() == hullSimple) {
1625 size_type pos = cur.cell().find_last(eq);
1627 if (pos == cur.cell().size()) {
1629 lyxerr << "use whole cell: " << ar << endl;
1631 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1632 lyxerr << "use partial cell form pos: " << pos << endl;
1634 cur.cell().append(eq);
1635 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1636 cur.pos() = cur.lastpos();
1640 if (getType() == hullEquation) {
1641 lyxerr << "use equation inset" << endl;
1642 mutate(hullEqnArray);
1643 MathData & ar = cur.cell();
1644 lyxerr << "use cell: " << ar << endl;
1648 cur.cell() = pipeThroughExtern(lang, extra, ar);
1649 // move to end of line
1650 cur.pos() = cur.lastpos();
1655 lyxerr << "use eqnarray" << endl;
1656 cur.idx() += 2 - cur.idx() % ncols();
1658 MathData ar = cur.cell();
1659 lyxerr << "use cell: " << ar << endl;
1660 // FIXME: temporarily disabled
1666 cur.cell() = pipeThroughExtern(lang, extra, ar);
1667 cur.pos() = cur.lastpos();
1672 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1674 //lyxerr << "action: " << cmd.action() << endl;
1675 switch (cmd.action()) {
1677 case LFUN_FINISHED_BACKWARD:
1678 case LFUN_FINISHED_FORWARD:
1679 case LFUN_FINISHED_RIGHT:
1680 case LFUN_FINISHED_LEFT:
1681 //lyxerr << "action: " << cmd.action() << endl;
1682 InsetMathGrid::doDispatch(cur, cmd);
1685 case LFUN_PARAGRAPH_BREAK:
1686 // just swallow this
1689 case LFUN_NEWLINE_INSERT:
1690 // some magic for the common case
1691 if (type_ == hullSimple || type_ == hullEquation) {
1692 cur.recordUndoInset();
1694 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1695 mutate(align ? hullAlign : hullEqnArray);
1696 // mutate() may change labels and such.
1697 cur.forceBufferUpdate();
1698 cur.idx() = nrows() * ncols() - 1;
1699 cur.pos() = cur.lastpos();
1701 InsetMathGrid::doDispatch(cur, cmd);
1704 case LFUN_MATH_NUMBER_TOGGLE: {
1705 //lyxerr << "toggling all numbers" << endl;
1706 cur.recordUndoInset();
1707 bool old = numberedType();
1708 if (type_ == hullMultline)
1709 numbered(nrows() - 1, !old);
1711 for (row_type row = 0; row < nrows(); ++row)
1712 numbered(row, !old);
1714 cur.message(old ? _("No number") : _("Number"));
1715 cur.forceBufferUpdate();
1719 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1720 cur.recordUndoInset();
1721 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1722 bool old = numbered(r);
1723 cur.message(old ? _("No number") : _("Number"));
1725 cur.forceBufferUpdate();
1729 case LFUN_LABEL_INSERT: {
1730 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1731 docstring old_label = label(r);
1732 docstring const default_label = from_ascii("eq:");
1733 if (old_label.empty())
1734 old_label = default_label;
1736 InsetCommandParams p(LABEL_CODE);
1737 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1738 string const data = InsetCommand::params2string(p);
1740 if (cmd.argument().empty())
1741 cur.bv().showDialog("label", data);
1743 FuncRequest fr(LFUN_INSET_INSERT, data);
1749 case LFUN_LABEL_COPY_AS_REFERENCE: {
1751 if (cmd.argument().empty() && &cur.inset() == this)
1752 // if there is no argument and we're inside math, we retrieve
1753 // the row number from the cursor position.
1754 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1756 // if there is an argument, find the corresponding label, else
1757 // check whether there is at least one label.
1758 for (row = 0; row != nrows(); ++row)
1759 if (numbered(row) && label_[row]
1760 && (cmd.argument().empty() || label(row) == cmd.argument()))
1767 InsetCommandParams p(REF_CODE, "ref");
1768 p["reference"] = label(row);
1769 cap::clearSelection();
1770 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1774 case LFUN_WORD_DELETE_FORWARD:
1775 case LFUN_CHAR_DELETE_FORWARD:
1776 if (col(cur.idx()) + 1 == ncols()
1777 && cur.pos() == cur.lastpos()
1778 && !cur.selection()) {
1779 if (!label(row(cur.idx())).empty()) {
1780 cur.recordUndoInset();
1781 label(row(cur.idx()), docstring());
1782 } else if (numbered(row(cur.idx()))) {
1783 cur.recordUndoInset();
1784 numbered(row(cur.idx()), false);
1785 cur.forceBufferUpdate();
1787 InsetMathGrid::doDispatch(cur, cmd);
1791 InsetMathGrid::doDispatch(cur, cmd);
1796 case LFUN_INSET_INSERT: {
1797 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1798 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1799 string const name = cmd.getArg(0);
1800 if (name == "label") {
1801 InsetCommandParams p(LABEL_CODE);
1802 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1803 docstring str = p["name"];
1804 cur.recordUndoInset();
1805 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1809 docstring old = label(r);
1812 // The label will take care of the reference update.
1816 // Newly created inset so initialize it.
1817 label_[r]->initView();
1820 cur.forceBufferUpdate();
1823 InsetMathGrid::doDispatch(cur, cmd);
1827 case LFUN_MATH_EXTERN:
1828 cur.recordUndoInset();
1832 case LFUN_MATH_MUTATE: {
1833 cur.recordUndoInset();
1834 row_type row = cur.row();
1835 col_type col = cur.col();
1836 mutate(hullType(cmd.argument()));
1837 cur.idx() = row * ncols() + col;
1838 if (cur.idx() > cur.lastidx()) {
1839 cur.idx() = cur.lastidx();
1840 cur.pos() = cur.lastpos();
1842 if (cur.pos() > cur.lastpos())
1843 cur.pos() = cur.lastpos();
1845 cur.forceBufferUpdate();
1846 // FIXME: find some more clever handling of the selection,
1847 // i.e. preserve it.
1848 cur.clearSelection();
1849 //cur.dispatched(FINISHED);
1853 case LFUN_MATH_DISPLAY: {
1854 cur.recordUndoInset();
1855 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1856 // if the cursor is in a cell that got merged, move it to
1857 // start of the hull inset.
1858 if (cur.idx() > 0) {
1862 if (cur.pos() > cur.lastpos())
1863 cur.pos() = cur.lastpos();
1868 case LFUN_TABULAR_FEATURE:
1869 if (!allowsTabularFeatures())
1872 InsetMathGrid::doDispatch(cur, cmd);
1876 InsetMathGrid::doDispatch(cur, cmd);
1884 bool allowDisplayMath(Cursor const & cur)
1886 LATTEST(cur.depth() > 1);
1887 Cursor tmpcur = cur;
1890 FuncRequest cmd(LFUN_MATH_DISPLAY);
1891 return tmpcur.getStatus(cmd, status) && status.enabled();
1897 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1898 FuncStatus & status) const
1900 switch (cmd.action()) {
1901 case LFUN_FINISHED_BACKWARD:
1902 case LFUN_FINISHED_FORWARD:
1903 case LFUN_FINISHED_RIGHT:
1904 case LFUN_FINISHED_LEFT:
1907 case LFUN_NEWLINE_INSERT:
1908 case LFUN_MATH_EXTERN:
1910 status.setEnabled(true);
1913 // we never allow this in math, and we want to bind enter
1914 // to another actions in command-alternatives
1915 case LFUN_PARAGRAPH_BREAK:
1916 status.setEnabled(false);
1918 case LFUN_MATH_MUTATE: {
1919 HullType const ht = hullType(cmd.argument());
1920 status.setOnOff(type_ == ht);
1921 status.setEnabled(isMutable(ht) && isMutable(type_));
1923 if (ht != hullSimple && status.enabled())
1924 status.setEnabled(allowDisplayMath(cur));
1927 case LFUN_MATH_DISPLAY: {
1928 status.setEnabled(display() != Inline || allowDisplayMath(cur));
1929 status.setOnOff(display() != Inline);
1933 case LFUN_MATH_NUMBER_TOGGLE:
1934 // FIXME: what is the right test, this or the one of
1936 status.setEnabled(display() != Inline);
1937 status.setOnOff(numberedType());
1940 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1941 // FIXME: what is the right test, this or the one of
1943 bool const enable = (type_ == hullMultline)
1944 ? (nrows() - 1 == cur.row())
1945 : display() != Inline;
1946 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1947 status.setEnabled(enable);
1948 status.setOnOff(enable && numbered(r));
1952 case LFUN_LABEL_INSERT:
1953 status.setEnabled(type_ != hullSimple);
1956 case LFUN_LABEL_COPY_AS_REFERENCE: {
1957 bool enabled = false;
1959 if (cmd.argument().empty() && &cur.inset() == this) {
1960 // if there is no argument and we're inside math, we retrieve
1961 // the row number from the cursor position.
1962 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1963 enabled = numberedType() && label_[row] && numbered(row);
1965 // if there is an argument, find the corresponding label, else
1966 // check whether there is at least one label.
1967 for (row_type row = 0; row != nrows(); ++row) {
1968 if (numbered(row) && label_[row] &&
1969 (cmd.argument().empty() || label(row) == cmd.argument())) {
1975 status.setEnabled(enabled);
1979 case LFUN_INSET_INSERT:
1980 if (cmd.getArg(0) == "label") {
1981 status.setEnabled(type_ != hullSimple);
1984 return InsetMathGrid::getStatus(cur, cmd, status);
1986 case LFUN_TABULAR_FEATURE: {
1987 if (!allowsTabularFeatures())
1989 string s = cmd.getArg(0);
1991 && (s == "append-row"
1992 || s == "delete-row"
1993 || s == "copy-row")) {
1994 status.message(bformat(
1995 from_utf8(N_("Can't change number of rows in '%1$s'")),
1997 status.setEnabled(false);
2001 && (s == "append-column"
2002 || s == "delete-column"
2003 || s == "copy-column")) {
2004 status.message(bformat(
2005 from_utf8(N_("Can't change number of columns in '%1$s'")),
2007 status.setEnabled(false);
2010 if (s == "add-vline-left" || s == "add-vline-right") {
2011 status.message(bformat(
2012 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2014 status.setEnabled(false);
2017 if (s == "valign-top" || s == "valign-middle"
2018 || s == "valign-bottom" || s == "align-left"
2019 || s == "align-center" || s == "align-right") {
2020 status.setEnabled(false);
2023 return InsetMathGrid::getStatus(cur, cmd, status);
2027 return InsetMathGrid::getStatus(cur, cmd, status);
2030 // This cannot really happen, but inserted to shut-up gcc
2031 return InsetMathGrid::getStatus(cur, cmd, status);
2035 /////////////////////////////////////////////////////////////////////
2039 // simply scrap this function if you want
2040 void InsetMathHull::mutateToText()
2043 // translate to latex
2045 latex(os, false, false);
2046 string str = os.str();
2049 Text * lt = view_->cursor().innerText();
2050 string::const_iterator cit = str.begin();
2051 string::const_iterator end = str.end();
2052 for (; cit != end; ++cit)
2053 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2056 //dispatch(LFUN_ESCAPE);
2061 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2062 docstring const & font)
2064 // this whole function is a hack and won't work for incremental font
2067 if (cur.inset().asInsetMath()->name() == font)
2068 cur.handleFont(to_utf8(font));
2070 cur.handleNest(createInsetMath(font, cur.buffer()));
2076 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2081 font.fromString(to_utf8(arg), b);
2082 if (font.fontInfo().color() != Color_inherit) {
2083 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2084 cur.handleNest(at, 0);
2089 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2092 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
2093 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
2094 enter_front ? idxFirst(cur) : idxLast(cur);
2095 // The inset formula dimension is not necessarily the same as the
2096 // one of the instant preview image, so we have to indicate to the
2097 // BufferView that a metrics update is needed.
2098 cur.screenUpdateFlags(Update::Force);
2102 void InsetMathHull::revealCodes(Cursor & cur) const
2104 if (!cur.inMathed())
2106 odocstringstream os;
2108 cur.message(os.str());
2110 // write something to the minibuffer
2111 // translate to latex
2115 string str = os.str();
2117 string::size_type pos = 0;
2119 for (string::iterator it = str.begin(); it != str.end(); ++it) {
2122 else if (*it == '\0') {
2124 pos = it - str.begin();
2130 res = res.substr(pos - 30);
2131 if (res.size() > 60)
2132 res = res.substr(0, 60);
2138 /////////////////////////////////////////////////////////////////////
2142 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2145 // FIXME: completely broken
2146 static InsetMathHull * lastformula = 0;
2147 static CursorBase current = DocIterator(ibegin(nucleus()));
2149 static string laststr;
2151 if (lastformula != this || laststr != str) {
2152 //lyxerr << "reset lastformula to " << this << endl;
2155 current = ibegin(nucleus());
2157 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2161 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2163 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2164 CursorSlice & top = it.back();
2165 MathData const & a = top.asInsetMath()->cell(top.idx_);
2166 if (a.matchpart(ar, top.pos_)) {
2167 bv->cursor().setSelection(it, ar.size());
2169 top.pos_ += ar.size();
2175 //lyxerr << "not found!" << endl;
2182 void InsetMathHull::write(ostream & os) const
2184 odocstringstream oss;
2185 TexRow texrow(false);
2186 otexrowstream ots(oss,texrow);
2187 WriteStream wi(ots, false, false, WriteStream::wsDefault);
2190 os << to_utf8(oss.str());
2194 void InsetMathHull::read(Lexer & lex)
2197 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2198 operator=(*at->asHullInset());
2202 bool InsetMathHull::readQuiet(Lexer & lex)
2205 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2207 operator=(*at->asHullInset());
2212 int InsetMathHull::plaintext(odocstringstream & os,
2213 OutputParams const & op, size_t max_length) const
2215 // disables ASCII-art for export of equations. See #2275.
2216 if (0 && display()) {
2220 TextPainter tpain(dim.width(), dim.height());
2221 drawT(tpain, 0, dim.ascent());
2223 // reset metrics cache to "real" values
2225 return tpain.textheight();
2228 odocstringstream oss;
2229 TexRow texrow(false);
2230 otexrowstream ots(oss,texrow);
2231 Encoding const * const enc = encodings.fromLyXName("utf8");
2232 WriteStream wi(ots, false, true, WriteStream::wsDefault, enc);
2235 if (type_ == hullRegexp)
2238 for (row_type r = 0; r < nrows(); ++r) {
2239 for (col_type c = 0; c < ncols(); ++c)
2240 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2241 // if it's for the TOC, we write just the first line
2242 // and do not include the newline.
2243 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2245 if (r < nrows() - 1)
2249 docstring const str = oss.str();
2255 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
2260 if (getType() == hullSimple)
2261 name = from_ascii("inlineequation");
2263 name = from_ascii("informalequation");
2265 docstring bname = name;
2266 if (!label(0).empty())
2267 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
2269 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
2271 odocstringstream ls;
2273 otexstream ols(ls, texrow);
2274 if (runparams.flavor == OutputParams::XML) {
2275 ms << MTag("alt role='tex' ");
2276 // Workaround for db2latex: db2latex always includes equations with
2277 // \ensuremath{} or \begin{display}\end{display}
2278 // so we strip LyX' math environment
2279 WriteStream wi(ols, false, false, WriteStream::wsDefault, runparams.encoding);
2280 InsetMathGrid::write(wi);
2281 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2286 InsetMathGrid::mathmlize(ms);
2289 ms << MTag("alt role='tex'");
2290 latex(ols, runparams);
2291 res = texrow.rows();
2292 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2296 ms << from_ascii("<graphic fileref=\"eqn/");
2297 if (!label(0).empty())
2298 ms << sgml::cleanID(buffer(), runparams, label(0));
2300 ms << sgml::uniqueID(from_ascii("anon"));
2302 if (runparams.flavor == OutputParams::XML)
2303 ms << from_ascii("\"/>");
2305 ms << from_ascii("\">");
2307 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2309 return ms.line() + res;
2313 bool InsetMathHull::haveNumbers() const
2315 bool havenumbers = false;
2316 // inline formulas are never numbered (bug 7351 part 3)
2317 if (getType() == hullSimple)
2319 for (size_t i = 0; i != numbered_.size(); ++i) {
2330 // We need to do something about alignment here.
2332 // This duplicates code from InsetMathGrid, but
2333 // we need access here to number information,
2334 // and we simply do not have that in InsetMathGrid.
2335 void InsetMathHull::htmlize(HtmlStream & os) const
2337 bool const havenumbers = haveNumbers();
2338 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2341 os << cell(index(0, 0));
2345 os << MTag("table", "class='mathtable'");
2346 for (row_type row = 0; row < nrows(); ++row) {
2348 for (col_type col = 0; col < ncols(); ++col) {
2350 os << cell(index(row, col));
2355 docstring const & num = numbers_[row];
2357 os << '(' << num << ')';
2362 os << ETag("table");
2366 // this duplicates code from InsetMathGrid, but
2367 // we need access here to number information,
2368 // and we simply do not have that in InsetMathGrid.
2369 void InsetMathHull::mathmlize(MathStream & os) const
2371 bool const havenumbers = haveNumbers();
2372 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2375 os << MTag("mtable");
2376 char const * const celltag = havetable ? "mtd" : "mrow";
2377 // FIXME There does not seem to be wide support at the moment
2378 // for mlabeledtr, so we have to use just mtr for now.
2379 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2380 char const * const rowtag = "mtr";
2381 for (row_type row = 0; row < nrows(); ++row) {
2384 for (col_type col = 0; col < ncols(); ++col) {
2386 << cell(index(row, col))
2392 docstring const & num = numbers_[row];
2394 os << '(' << num << ')';
2401 os << ETag("mtable");
2405 void InsetMathHull::mathAsLatex(WriteStream & os) const
2407 MathEnsurer ensurer(os, false);
2408 bool havenumbers = haveNumbers();
2409 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2412 os << cell(index(0, 0));
2416 os << "<table class='mathtable'>";
2417 for (row_type row = 0; row < nrows(); ++row) {
2419 for (col_type col = 0; col < ncols(); ++col) {
2420 os << "<td class='math'>";
2421 os << cell(index(row, col));
2426 docstring const & num = numbers_[row];
2428 os << '(' << num << ')';
2437 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2439 BufferParams::MathOutput const mathtype =
2440 buffer().masterBuffer()->params().html_math_output;
2442 bool success = false;
2444 // we output all the labels just at the beginning of the equation.
2445 // this should be fine.
2446 for (size_t i = 0; i != label_.size(); ++i) {
2447 InsetLabel const * const il = label_[i];
2453 // FIXME Eventually we would like to do this inset by inset.
2454 if (mathtype == BufferParams::MathML) {
2455 odocstringstream os;
2460 } catch (MathExportException const &) {}
2462 if (getType() == hullSimple)
2463 xs << html::StartTag("math",
2464 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2466 xs << html::StartTag("math",
2467 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2468 xs << XHTMLStream::ESCAPE_NONE
2470 << html::EndTag("math");
2472 } else if (mathtype == BufferParams::HTML) {
2473 odocstringstream os;
2478 } catch (MathExportException const &) {}
2480 string const tag = (getType() == hullSimple) ? "span" : "div";
2481 xs << html::StartTag(tag, "class='formula'", true)
2482 << XHTMLStream::ESCAPE_NONE
2484 << html::EndTag(tag);
2488 // what we actually want is this:
2490 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2492 // || mathtype == BufferParams::Images
2494 // but what follows is equivalent, since we'll enter only if either (a) we
2495 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2496 // aren't doing LaTeX.
2498 // so this is for Images.
2499 if (!success && mathtype != BufferParams::LaTeX) {
2500 graphics::PreviewImage const * pimage = 0;
2502 loadPreview(docit_);
2503 pimage = preview_->getPreviewImage(buffer());
2504 // FIXME Do we always have png?
2507 if (pimage || op.dryrun) {
2508 string const filename = pimage ? pimage->filename().onlyFileName()
2509 : "previewimage.png";
2511 // if we are not in the master buffer, then we need to see that the
2512 // generated image is copied there; otherwise, preview fails.
2513 Buffer const * mbuf = buffer().masterBuffer();
2514 if (mbuf != &buffer()) {
2515 string mbtmp = mbuf->temppath();
2516 FileName const mbufimg(support::addName(mbtmp, filename));
2517 pimage->filename().copyTo(mbufimg);
2519 // add the file to the list of files to be exported
2520 op.exportdata->addExternalFile("xhtml", pimage->filename());
2523 string const tag = (getType() == hullSimple) ? "span" : "div";
2525 << html::StartTag(tag, "style = \"text-align: center;\"")
2526 << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2527 << html::EndTag(tag)
2533 // so we'll pass this test if we've failed everything else, or
2534 // if mathtype was LaTeX, since we won't have entered any of the
2536 if (!success /* || mathtype != BufferParams::LaTeX */) {
2537 // Unfortunately, we cannot use latexString() because we do not want
2538 // $...$ or whatever.
2539 odocstringstream ls;
2540 TexRow texrow(false);
2541 otexrowstream ots(ls,texrow);
2542 WriteStream wi(ots, false, true, WriteStream::wsPreview);
2543 ModeSpecifier specifier(wi, MATH_MODE);
2545 docstring const latex = ls.str();
2547 // class='math' allows for use of jsMath
2548 // http://www.math.union.edu/~dpvc/jsMath/
2550 // probably should allow for some kind of customization here
2551 string const tag = (getType() == hullSimple) ? "span" : "div";
2552 xs << html::StartTag(tag, "class='math'")
2554 << html::EndTag(tag)
2561 void InsetMathHull::toString(odocstream & os) const
2563 odocstringstream ods;
2564 plaintext(ods, OutputParams(0));
2569 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2571 odocstringstream ods;
2574 // FIXME: this results in spilling TeX into the LyXHTML output since the
2575 // outliner is used to generate the LyXHTML list of figures/etc.
2581 string InsetMathHull::contextMenuName() const
2583 return "context-math";
2587 void InsetMathHull::recordLocation(DocIterator const & di)
2593 bool InsetMathHull::canPaintChange(BufferView const &) const
2595 // We let RowPainter do it seamlessly for inline insets
2596 return display() != Inline;