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"
47 #include "TextClass.h"
48 #include "TextPainter.h"
49 #include "TocBackend.h"
51 #include "insets/InsetLabel.h"
52 #include "insets/InsetRef.h"
53 #include "insets/RenderPreview.h"
55 #include "graphics/GraphicsImage.h"
56 #include "graphics/PreviewImage.h"
57 #include "graphics/PreviewLoader.h"
59 #include "frontends/alert.h"
60 #include "frontends/Painter.h"
62 #include "support/convert.h"
63 #include "support/debug.h"
64 #include "support/gettext.h"
65 #include "support/filetools.h"
66 #include "support/lassert.h"
67 #include "support/lstrings.h"
68 #include "support/RefChanger.h"
73 using namespace lyx::support;
77 using cap::grabAndEraseSelection;
78 using cap::reduceSelectionToOneCell;
82 int getCols(HullType type)
107 // returns position of first relation operator in the array
108 // used for "intelligent splitting"
109 size_t firstRelOp(MathData const & ar)
111 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
112 if ((*it)->isMathRel())
113 return it - ar.begin();
118 char const * star(bool numbered)
120 return numbered ? "" : "*";
124 } // end anon namespace
127 HullType hullType(docstring const & s)
129 if (s == "none") return hullNone;
130 if (s == "simple") return hullSimple;
131 if (s == "equation") return hullEquation;
132 if (s == "eqnarray") return hullEqnArray;
133 if (s == "align") return hullAlign;
134 if (s == "alignat") return hullAlignAt;
135 if (s == "xalignat") return hullXAlignAt;
136 if (s == "xxalignat") return hullXXAlignAt;
137 if (s == "multline") return hullMultline;
138 if (s == "gather") return hullGather;
139 if (s == "flalign") return hullFlAlign;
140 if (s == "regexp") return hullRegexp;
141 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
146 docstring hullName(HullType type)
149 case hullNone: return from_ascii("none");
150 case hullSimple: return from_ascii("simple");
151 case hullEquation: return from_ascii("equation");
152 case hullEqnArray: return from_ascii("eqnarray");
153 case hullAlign: return from_ascii("align");
154 case hullAlignAt: return from_ascii("alignat");
155 case hullXAlignAt: return from_ascii("xalignat");
156 case hullXXAlignAt: return from_ascii("xxalignat");
157 case hullMultline: return from_ascii("multline");
158 case hullGather: return from_ascii("gather");
159 case hullFlAlign: return from_ascii("flalign");
160 case hullRegexp: return from_ascii("regexp");
162 lyxerr << "unknown hull type" << endl;
165 return from_ascii("none");
168 static InsetLabel * dummy_pointer = 0;
170 InsetMathHull::InsetMathHull(Buffer * buf)
171 : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, NUMBER),
172 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
173 preview_(new RenderPreview(this))
175 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
176 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
177 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
178 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
185 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
186 : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, NUMBER),
187 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
188 preview_(new RenderPreview(this))
196 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
202 InsetMathHull::~InsetMathHull()
204 for (size_t i = 0; i < label_.size(); ++i)
209 Inset * InsetMathHull::clone() const
211 return new InsetMathHull(*this);
215 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
219 InsetMathGrid::operator=(other);
221 numbered_ = other.numbered_;
222 numbers_ = other.numbers_;
223 buffer_ = other.buffer_;
224 for (size_t i = 0; i < label_.size(); ++i)
226 label_ = other.label_;
227 for (size_t i = 0; i != label_.size(); ++i) {
229 label_[i] = new InsetLabel(*label_[i]);
231 preview_.reset(new RenderPreview(*other.preview_, this));
237 void InsetMathHull::setBuffer(Buffer & buffer)
239 InsetMathGrid::setBuffer(buffer);
241 for (size_t i = 0; i != label_.size(); ++i) {
243 label_[i]->setBuffer(buffer);
248 // FIXME This should really be controlled by the TOC level, or
249 // something of the sort.
251 const char * counters_to_save[] = {"section", "chapter"};
252 unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
256 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
259 //FIXME: buffer_ should be set at creation for this inset! Problem is
260 // This inset is created at too many places (see Parser::parse1() in
265 // if any of the equations are numbered, then we want to save the values
266 // of some of the counters.
268 BufferParams const & bp = buffer_->params();
269 string const & lang = it->getParLanguage(bp)->code();
271 buffer_->masterBuffer()->params().documentClass().counters();
273 // right now, we only need to do this at export time
274 if (utype == OutputUpdate) {
275 for (size_t i = 0; i < numcnts; ++i) {
276 docstring const cnt = from_ascii(counters_to_save[i]);
277 if (cnts.hasCounter(cnt))
278 counter_map[cnt] = cnts.value(cnt);
282 // this has to be done separately
283 docstring const eqstr = from_ascii("equation");
284 if (cnts.hasCounter(eqstr)) {
285 if (utype == OutputUpdate)
286 counter_map[eqstr] = cnts.value(eqstr);
287 for (size_t i = 0; i != label_.size(); ++i) {
289 cnts.step(eqstr, utype);
290 numbers_[i] = cnts.theCounter(eqstr, lang);
292 numbers_[i] = empty_docstring();
298 for (size_t i = 0; i != label_.size(); ++i) {
300 label_[i]->updateBuffer(it, utype);
303 InsetMathGrid::updateBuffer(it, utype);
307 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active,
308 UpdateType utype) const
311 //FIXME: buffer_ should be set at creation for this inset! Problem is
312 // This inset is created at too many places (see Parser::parse1() in
317 shared_ptr<Toc> toc = buffer().tocBackend().toc("equation");
319 for (row_type row = 0; row != nrows(); ++row) {
323 label_[row]->addToToc(pit, output_active, utype);
324 toc->push_back(TocItem(pit, 0, nicelabel(row), output_active));
329 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
331 if (previewState(&cur.bv())) {
335 return InsetMathNest::editXY(cur, x, y);
339 InsetMath::mode_type InsetMathHull::currentMode() const
343 return UNDECIDED_MODE;
345 // definitely math mode ...
365 bool InsetMathHull::idxFirst(Cursor & cur) const
373 bool InsetMathHull::idxLast(Cursor & cur) const
375 cur.idx() = nargs() - 1;
376 cur.pos() = cur.lastpos();
381 // FIXME: InsetMathGrid should be changed to let the real column alignment be
382 // given by a virtual method like displayColAlign, because the values produced
383 // by defaultColAlign can be invalidated by lfuns such as add-column. For the
384 // moment the values produced by defaultColAlign are not used, notably because
385 // alignment is not implemented in the LyXHTML output.
386 char InsetMathHull::defaultColAlign(col_type col)
388 return colAlign(type_, col);
392 char InsetMathHull::displayColAlign(idx_type idx) const
396 row_type const r = row(idx);
399 if (r == nrows() - 1)
410 return colAlign(type_, col(idx));
414 return InsetMathGrid::displayColAlign(idx);
418 int InsetMathHull::displayColSpace(col_type col) const
420 return colSpace(type_, col);
424 // FIXME: same comment as for defaultColAlign applies.
425 int InsetMathHull::defaultColSpace(col_type col)
427 return colSpace(type_, col);
431 string InsetMathHull::standardFont() const
437 return "lyxnochange";
444 ColorCode InsetMathHull::standardColor() const
449 return Color_foreground;
457 bool InsetMathHull::previewState(const BufferView *const bv) const
459 if (!editing(bv) && RenderPreview::previewMath()
460 && type_ != hullRegexp)
462 graphics::PreviewImage const * pimage =
463 preview_->getPreviewImage(bv->buffer());
464 return pimage && pimage->image();
471 static const int ERROR_FRAME_WIDTH = 2;
474 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
476 if (previewState(mi.base.bv)) {
477 preview_->metrics(mi, dim);
478 if (previewTooSmall(dim)) {
479 // preview image is too small
480 dim.wid += 2 * ERROR_FRAME_WIDTH;
481 dim.asc += 2 * ERROR_FRAME_WIDTH;
483 // insert a one pixel gap in front of the formula
486 dim.des += displayMargin();
488 // Cache the inset dimension.
489 setDimCache(mi, dim);
493 // FIXME: Changing the same object repeatedly is inefficient.
494 Changer dummy1 = mi.base.changeFontSet(standardFont());
495 Changer dummy2 = mi.base.changeStyle(display() ? LM_ST_DISPLAY : LM_ST_TEXT);
497 // let the cells adjust themselves
498 InsetMathGrid::metrics(mi, dim);
501 dim.asc += displayMargin();
502 dim.des += displayMargin();
505 if (numberedType()) {
506 Changer dummy = mi.base.changeFontSet("mathbf");
508 for (row_type row = 0; row < nrows(); ++row)
509 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
515 if (type_ == hullRegexp)
517 // make it at least as high as the current font
520 math_font_max_dim(mi.base.font, asc, des);
521 dim.asc = max(dim.asc, asc);
522 dim.des = max(dim.des, des);
523 // Cache the inset dimension.
524 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
525 setDimCache(mi, dim);
529 bool InsetMathHull::previewTooSmall(Dimension const & dim) const
531 return dim.width() <= 10 && dim.height() <= 10;
535 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
537 BufferView const * const bv = pi.base.bv;
538 if (previewState(bv)) {
539 Dimension const dim = dimension(*pi.base.bv);
540 if (previewTooSmall(dim))
542 return graphics::PreviewLoader::backgroundColor();
548 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
550 Dimension const dim = dimension(*pi.base.bv);
551 if (previewTooSmall(dim)) {
552 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
553 dim.wid, dim.asc + dim.des, backgroundColor(pi));
556 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
557 dim.asc + dim.des - 1, pi.backgroundColor(this));
561 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
563 BufferView const * const bv = pi.base.bv;
564 Dimension const dim = dimension(*bv);
566 if (type_ == hullRegexp)
567 pi.pain.rectangle(x + 2, y - dim.ascent() + 1,
568 dim.width() - 3, 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 otexrowstream ots(os);
618 WriteStream wi(ots, false, true, WriteStream::wsDefault);
620 dim.wid = os.str().size();
627 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
630 InsetMathGrid::drawT(pain, x, y);
633 otexrowstream ots(os);
634 WriteStream wi(ots, false, true, WriteStream::wsDefault);
636 pain.draw(x, y, os.str().c_str());
641 static docstring latexString(InsetMathHull const & inset)
644 // This has to be static, because a preview snippet or a math
645 // macro containing math in text mode (such as $\text{$\phi$}$ or
646 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
647 // first time as a whole, and the second time only the inner math.
648 // In this last case inset.buffer() would be invalid.
649 static Encoding const * encoding = 0;
650 if (inset.isBufferValid())
651 encoding = &(inset.buffer().params().encoding());
652 otexrowstream ots(ls);
653 WriteStream wi(ots, false, true, WriteStream::wsPreview, encoding);
659 void InsetMathHull::initUnicodeMath() const
661 // Trigger classification of the unicode symbols in this inset
662 docstring const dummy = latexString(*this);
666 void InsetMathHull::addPreview(DocIterator const & inset_pos,
667 graphics::PreviewLoader & /*ploader*/) const
669 if (RenderPreview::previewMath()) {
670 preparePreview(inset_pos);
675 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
676 MacroNameSet & macros, MacroNameSet & defs) const
678 MacroNameSet::iterator const end = macros.end();
680 for (size_t i = 0; i < md.size(); ++i) {
681 MathMacro const * mi = md[i].nucleus()->asMacro();
682 MathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
683 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
684 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
685 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
686 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
688 // Look for macros in the arguments of this macro.
689 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
690 usedMacros(mi->cell(idx), pos, macros, defs);
691 // Make sure this is a macro defined in the document
692 // (as we also spot the macros in the symbols file)
693 // or that we have not already accounted for it.
694 docstring const name = mi->name();
695 if (macros.find(name) == end)
698 // Look for macros in the definition of this macro.
699 MathData ar(pos.buffer());
700 MacroData const * data =
701 pos.buffer()->getMacro(name, pos, true);
703 odocstringstream macro_def;
704 data->write(macro_def, true);
706 defs.insert(macro_def.str());
707 asArray(data->definition(), ar);
709 usedMacros(ar, pos, macros, defs);
711 MathData ar(pos.buffer());
712 asArray(mt->definition(), ar);
713 usedMacros(ar, pos, macros, defs);
715 if (!si->nuc().empty())
716 usedMacros(si->nuc(), pos, macros, defs);
718 usedMacros(si->down(), pos, macros, defs);
720 usedMacros(si->up(), pos, macros, defs);
721 } else if (fi || gi) {
722 idx_type nidx = fi ? fi->nargs() : gi->nargs();
723 for (idx_type idx = 0; idx < nidx; ++idx)
724 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
727 usedMacros(ni->cell(0), pos, macros, defs);
733 void InsetMathHull::preparePreview(DocIterator const & pos,
734 bool forexport) const
736 // there is no need to do all the macro stuff if we're not
737 // actually going to generate the preview.
738 if (!RenderPreview::previewMath() && !forexport)
741 Buffer const * buffer = pos.buffer();
743 // collect macros at this position
745 buffer->listMacroNames(macros);
747 // collect definitions only for the macros used in this inset
749 for (idx_type idx = 0; idx < nargs(); ++idx)
750 usedMacros(cell(idx), pos, macros, defs);
752 MacroNameSet::iterator it = defs.begin();
753 MacroNameSet::iterator end = defs.end();
754 docstring macro_preamble;
755 for (; it != end; ++it)
756 macro_preamble.append(*it);
758 // set the font series and size for this snippet
759 DocIterator dit = pos.getInnerText();
760 Paragraph const & par = dit.paragraph();
761 Font font = par.getFontSettings(buffer->params(), dit.pos());
762 font.fontInfo().realize(par.layout().font);
763 string const lsize = font.latexSize();
766 if (font.fontInfo().series() == BOLD_SERIES) {
767 setfont += from_ascii("\\textbf{");
770 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
771 setfont += from_ascii("\\" + lsize + '\n');
774 if (forexport && haveNumbers()) {
775 docstring eqstr = from_ascii("equation");
776 CounterMap::const_iterator it = counter_map.find(eqstr);
777 if (it != counter_map.end()) {
778 int num = it->second;
780 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
781 '{' + convert<docstring>(num) + '}' + '\n';
783 for (size_t i = 0; i != numcnts; ++i) {
784 docstring cnt = from_ascii(counters_to_save[i]);
785 it = counter_map.find(cnt);
786 if (it == counter_map.end())
788 int num = it->second;
790 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
791 '{' + convert<docstring>(num) + '}';
794 docstring const snippet = macro_preamble + setfont + setcnt
795 + latexString(*this) + endfont;
796 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
797 preview_->addPreview(snippet, *buffer, forexport);
801 void InsetMathHull::reloadPreview(DocIterator const & pos) const
804 preview_->startLoading(*pos.buffer());
808 void InsetMathHull::loadPreview(DocIterator const & pos) const
810 bool const forexport = true;
811 preparePreview(pos, forexport);
812 preview_->startLoading(*pos.buffer(), forexport);
816 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
818 if (RenderPreview::previewMath()) {
820 cur.screenUpdateFlags(Update::Force);
826 docstring InsetMathHull::label(row_type row) const
828 LASSERT(row < nrows(), return docstring());
829 if (InsetLabel * il = label_[row])
830 return il->screenLabel();
835 void InsetMathHull::label(row_type row, docstring const & label)
837 //lyxerr << "setting label '" << label << "' for row " << row << endl;
841 label_[row] = dummy_pointer;
844 label_[row]->updateLabelAndRefs(label);
846 label_[row]->setParam("name", label);
850 InsetCommandParams p(LABEL_CODE);
852 label_[row] = new InsetLabel(buffer_, p);
854 label_[row]->setBuffer(buffer());
858 void InsetMathHull::numbered(row_type row, Numbered num)
860 numbered_[row] = num;
861 if (!numbered(row) && label_[row]) {
868 bool InsetMathHull::numbered(row_type row) const
870 return numbered_[row] == NUMBER;
874 bool InsetMathHull::ams() const
894 for (size_t row = 0; row < numbered_.size(); ++row)
895 if (numbered_[row] == NOTAG)
901 Inset::DisplayType InsetMathHull::display() const
924 bool InsetMathHull::numberedType() const
943 for (row_type row = 0; row < nrows(); ++row)
950 void InsetMathHull::validate(LaTeXFeatures & features) const
952 if (features.runparams().isLaTeX()) {
954 features.require("amsmath");
971 if (features.inDeletedInset() && !features.mustProvide("ct-dvipost"))
972 features.require("ct-tikz-math-sout");
976 features.require("color");
977 docstring frcol = from_utf8(lcolor.getLaTeXName(Color_regexpframe));
978 docstring bgcol = from_ascii("white");
979 features.addPreambleSnippet(
980 "\\newcommand{\\regexp}[1]{\\fcolorbox{"
982 + bgcol + "}{\\ensuremath{\\mathtt{#1}}}}");
983 features.addPreambleSnippet(
984 from_ascii("\\newcommand{\\endregexp}{}"));
988 // Validation is necessary only if not using AMS math.
989 // To be safe, we will always run mathedvalidate.
990 //if (features.amsstyle)
993 //features.binom = true;
994 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
995 // it would be better to do this elsewhere, but we can't validate in
996 // InsetMathMatrix and we have no way, outside MathExtern, to know if
997 // we even have any matrices.
998 features.addCSSSnippet(
999 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
1000 "table.matrix td{padding: 0.25px;}\n"
1001 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
1002 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
1004 InsetMathGrid::validate(features);
1008 void InsetMathHull::header_write(WriteStream & os) const
1010 bool n = numberedType();
1019 if (cell(0).empty())
1024 if (os.strikeoutMath())
1025 os << "\\lyxmathsout{\\parbox{\\columnwidth}{";
1029 os << "\\begin{equation" << star(n) << "}\n";
1039 if (os.strikeoutMath())
1040 os << "\\lyxmathsout{\\parbox{\\columnwidth}{";
1043 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1050 os << "\\begin{" << hullName(type_) << star(n) << '}'
1051 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1057 os << "\\begin{" << hullName(type_) << '}'
1058 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1068 os << "\\begin{unknown" << star(n) << "}\n";
1074 void InsetMathHull::footer_write(WriteStream & os) const
1076 bool n = numberedType();
1091 os << "\\end{equation" << star(n) << "}\n";
1094 if (os.strikeoutMath())
1105 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1106 if (os.strikeoutMath())
1114 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1120 os << "\\end{" << hullName(type_) << "}\n";
1124 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1125 os << "\\endregexp{}}";
1131 os << "\\end{unknown" << star(n) << "}\n";
1137 bool InsetMathHull::allowsTabularFeatures() const
1160 bool InsetMathHull::rowChangeOK() const
1163 type_ == hullEqnArray || type_ == hullAlign ||
1164 type_ == hullFlAlign || type_ == hullAlignAt ||
1165 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1166 type_ == hullGather || type_ == hullMultline;
1170 bool InsetMathHull::colChangeOK() const
1173 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1174 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1178 void InsetMathHull::addRow(row_type row)
1183 bool numbered = numberedType();
1184 // Move the number and raw pointer, do not call label() (bug 7511)
1185 InsetLabel * label = dummy_pointer;
1186 docstring number = empty_docstring();
1187 if (type_ == hullMultline) {
1188 if (row + 1 == nrows()) {
1189 numbered_[row] = NONUMBER;
1190 swap(label, label_[row]);
1191 swap(number, numbers_[row]);
1196 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1197 numbers_.insert(numbers_.begin() + row + 1, number);
1198 label_.insert(label_.begin() + row + 1, label);
1199 InsetMathGrid::addRow(row);
1203 void InsetMathHull::swapRow(row_type row)
1207 if (row + 1 == nrows())
1209 swap(numbered_[row], numbered_[row + 1]);
1210 swap(numbers_[row], numbers_[row + 1]);
1211 swap(label_[row], label_[row + 1]);
1212 InsetMathGrid::swapRow(row);
1216 void InsetMathHull::delRow(row_type row)
1218 if (nrows() <= 1 || !rowChangeOK())
1220 if (row + 1 == nrows() && type_ == hullMultline) {
1221 swap(numbered_[row - 1], numbered_[row]);
1222 swap(numbers_[row - 1], numbers_[row]);
1223 swap(label_[row - 1], label_[row]);
1224 InsetMathGrid::delRow(row);
1227 InsetMathGrid::delRow(row);
1228 // The last dummy row has no number info nor a label.
1229 // Test nrows() + 1 because we have already erased the row.
1230 if (row == nrows() + 1)
1232 numbered_.erase(numbered_.begin() + row);
1233 numbers_.erase(numbers_.begin() + row);
1235 label_.erase(label_.begin() + row);
1239 void InsetMathHull::addCol(col_type col)
1243 InsetMathGrid::addCol(col);
1247 void InsetMathHull::delCol(col_type col)
1249 if (ncols() <= 1 || !colChangeOK())
1251 InsetMathGrid::delCol(col);
1255 docstring InsetMathHull::nicelabel(row_type row) const
1259 docstring const & val = numbers_[row];
1261 return '(' + val + ')';
1262 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1266 void InsetMathHull::glueall(HullType type)
1269 for (idx_type i = 0; i < nargs(); ++i)
1271 InsetLabel * label = 0;
1272 if (type == hullEquation) {
1273 // preserve first non-empty label
1274 for (row_type row = 0; row < nrows(); ++row) {
1276 label = label_[row];
1282 *this = InsetMathHull(buffer_, hullSimple);
1289 void InsetMathHull::splitTo2Cols()
1291 LASSERT(ncols() == 1, return);
1292 InsetMathGrid::addCol(1);
1293 for (row_type row = 0; row < nrows(); ++row) {
1294 idx_type const i = 2 * row;
1295 pos_type pos = firstRelOp(cell(i));
1296 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1297 cell(i).erase(pos, cell(i).size());
1302 void InsetMathHull::splitTo3Cols()
1304 LASSERT(ncols() < 3, return);
1307 InsetMathGrid::addCol(2);
1308 for (row_type row = 0; row < nrows(); ++row) {
1309 idx_type const i = 3 * row + 1;
1310 if (!cell(i).empty()) {
1311 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1312 cell(i).erase(1, cell(i).size());
1318 void InsetMathHull::changeCols(col_type cols)
1320 if (ncols() == cols)
1322 else if (ncols() < cols) {
1328 while (ncols() < cols)
1329 InsetMathGrid::addCol(ncols());
1335 for (row_type row = 0; row < nrows(); ++row) {
1336 idx_type const i = row * ncols();
1337 for (col_type col = cols; col < ncols(); ++col) {
1338 cell(i + cols - 1).append(cell(i + col));
1342 while (ncols() > cols) {
1343 InsetMathGrid::delCol(ncols() - 1);
1348 HullType InsetMathHull::getType() const
1354 void InsetMathHull::setType(HullType type)
1361 bool InsetMathHull::isMutable(HullType type)
1385 void InsetMathHull::mutate(HullType newtype)
1387 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1389 if (newtype == type_)
1392 // This guards the algorithm below it, which is designed with certain types
1394 if (!isMutable(newtype) || !isMutable(type_)) {
1395 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1396 << "' to '" << to_utf8(hullName(newtype))
1397 << "' not implemented" << endl;
1401 // we try to move along the chain
1402 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1404 // +-------------------------------------+
1405 // we use eqnarray as intermediate type for mutations that are not
1406 // directly supported because it handles labels and numbering for
1411 setType(hullSimple);
1417 if (newtype == hullNone) {
1421 setType(hullEquation);
1422 numbered(0, label_[0] ? true : false);
1431 setType(hullSimple);
1436 // split it "nicely" on the first relop
1438 setType(hullEqnArray);
1446 // split it "nicely"
1481 setType(hullEqnArray);
1490 for (row_type row = 0; row < nrows(); ++row)
1491 numbered(row, false);
1501 for (row_type row = 0; row < nrows(); ++row)
1502 numbered(row, false);
1509 setType(hullEqnArray);
1539 for (row_type row = 0; row < nrows(); ++row)
1540 numbered(row, false);
1544 // first we mutate to EqnArray
1546 setType(hullEqnArray);
1553 // we passed the guard so we should not be here
1554 LASSERT("Mutation not implemented, but should have been.", return);
1560 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1561 bool last_eoln) const
1564 if (numberedType()) {
1565 if (label_[row] && numbered(row)) {
1566 docstring const name =
1567 latex ? escape(label_[row]->getParam("name"))
1568 : label_[row]->getParam("name");
1569 res += "\\label{" + name + '}';
1571 if (type_ != hullMultline) {
1572 if (numbered_[row] == NONUMBER)
1573 res += "\\nonumber ";
1574 else if (numbered_[row] == NOTAG)
1578 // Never add \\ on the last empty line of eqnarray and friends
1580 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1583 void InsetMathHull::write(WriteStream & os) const
1585 ModeSpecifier specifier(os, MATH_MODE);
1587 InsetMathGrid::write(os);
1592 void InsetMathHull::normalize(NormalStream & os) const
1594 os << "[formula " << hullName(type_) << ' ';
1595 InsetMathGrid::normalize(os);
1600 void InsetMathHull::infoize(odocstream & os) const
1602 os << bformat(_("Type: %1$s"), hullName(type_));
1606 void InsetMathHull::check() const
1608 LATTEST(numbered_.size() == nrows());
1609 LATTEST(numbers_.size() == nrows());
1610 LATTEST(label_.size() == nrows());
1614 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1618 idocstringstream iss(func.argument());
1619 iss >> dlang >> extra;
1621 extra = from_ascii("noextra");
1622 string const lang = to_ascii(dlang);
1624 // replace selection with result of computation
1625 if (reduceSelectionToOneCell(cur)) {
1627 asArray(grabAndEraseSelection(cur), ar);
1628 lyxerr << "use selection: " << ar << endl;
1629 cur.insert(pipeThroughExtern(lang, extra, ar));
1633 // only inline, display or eqnarray math is allowed
1634 switch (getType()) {
1640 frontend::Alert::warning(_("Bad math environment"),
1641 _("Computation cannot be performed for AMS "
1642 "math environments.\nChange the math "
1643 "formula type and try again."));
1648 eq.push_back(MathAtom(new InsetMathChar('=')));
1650 // go to first item in line
1651 cur.idx() -= cur.idx() % ncols();
1654 if (getType() == hullSimple) {
1655 size_type pos = cur.cell().find_last(eq);
1657 if (pos == cur.cell().size()) {
1659 lyxerr << "use whole cell: " << ar << endl;
1661 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1662 lyxerr << "use partial cell form pos: " << pos << endl;
1664 cur.cell().append(eq);
1665 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1666 cur.pos() = cur.lastpos();
1670 if (getType() == hullEquation) {
1671 lyxerr << "use equation inset" << endl;
1672 mutate(hullEqnArray);
1673 MathData & ar = cur.cell();
1674 lyxerr << "use cell: " << ar << endl;
1678 cur.cell() = pipeThroughExtern(lang, extra, ar);
1679 // move to end of line
1680 cur.pos() = cur.lastpos();
1685 lyxerr << "use eqnarray" << endl;
1686 cur.idx() += 2 - cur.idx() % ncols();
1688 MathData ar = cur.cell();
1689 lyxerr << "use cell: " << ar << endl;
1690 // FIXME: temporarily disabled
1696 cur.cell() = pipeThroughExtern(lang, extra, ar);
1697 cur.pos() = cur.lastpos();
1702 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1704 //lyxerr << "action: " << cmd.action() << endl;
1705 switch (cmd.action()) {
1707 case LFUN_FINISHED_BACKWARD:
1708 case LFUN_FINISHED_FORWARD:
1709 case LFUN_FINISHED_RIGHT:
1710 case LFUN_FINISHED_LEFT:
1711 //lyxerr << "action: " << cmd.action() << endl;
1712 InsetMathGrid::doDispatch(cur, cmd);
1715 case LFUN_PARAGRAPH_BREAK:
1716 // just swallow this
1719 case LFUN_NEWLINE_INSERT:
1720 // some magic for the common case
1721 if (type_ == hullSimple || type_ == hullEquation) {
1722 cur.recordUndoInset();
1724 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1725 mutate(align ? hullAlign : hullEqnArray);
1726 // mutate() may change labels and such.
1727 cur.forceBufferUpdate();
1728 cur.idx() = nrows() * ncols() - 1;
1729 cur.pos() = cur.lastpos();
1731 InsetMathGrid::doDispatch(cur, cmd);
1734 case LFUN_MATH_NUMBER_TOGGLE: {
1735 //lyxerr << "toggling all numbers" << endl;
1736 cur.recordUndoInset();
1737 bool old = numberedType();
1738 if (type_ == hullMultline)
1739 numbered(nrows() - 1, !old);
1741 for (row_type row = 0; row < nrows(); ++row)
1742 numbered(row, !old);
1744 cur.message(old ? _("No number") : _("Number"));
1745 cur.forceBufferUpdate();
1749 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1750 cur.recordUndoInset();
1751 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1752 bool old = numbered(r);
1753 cur.message(old ? _("No number") : _("Number"));
1755 cur.forceBufferUpdate();
1759 case LFUN_LABEL_INSERT: {
1760 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1761 docstring old_label = label(r);
1762 docstring const default_label = from_ascii("eq:");
1763 if (old_label.empty())
1764 old_label = default_label;
1766 InsetCommandParams p(LABEL_CODE);
1767 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1768 string const data = InsetCommand::params2string(p);
1770 if (cmd.argument().empty())
1771 cur.bv().showDialog("label", data);
1773 FuncRequest fr(LFUN_INSET_INSERT, data);
1779 case LFUN_LABEL_COPY_AS_REFERENCE: {
1781 if (cmd.argument().empty() && &cur.inset() == this)
1782 // if there is no argument and we're inside math, we retrieve
1783 // the row number from the cursor position.
1784 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1786 // if there is an argument, find the corresponding label, else
1787 // check whether there is at least one label.
1788 for (row = 0; row != nrows(); ++row)
1789 if (numbered(row) && label_[row]
1790 && (cmd.argument().empty() || label(row) == cmd.argument()))
1797 InsetCommandParams p(REF_CODE, "ref");
1798 p["reference"] = label(row);
1799 cap::clearSelection();
1800 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1804 case LFUN_WORD_DELETE_FORWARD:
1805 case LFUN_CHAR_DELETE_FORWARD:
1806 if (col(cur.idx()) + 1 == ncols()
1807 && cur.pos() == cur.lastpos()
1808 && !cur.selection()) {
1809 if (!label(row(cur.idx())).empty()) {
1810 cur.recordUndoInset();
1811 label(row(cur.idx()), docstring());
1812 } else if (numbered(row(cur.idx()))) {
1813 cur.recordUndoInset();
1814 numbered(row(cur.idx()), false);
1815 cur.forceBufferUpdate();
1817 InsetMathGrid::doDispatch(cur, cmd);
1821 InsetMathGrid::doDispatch(cur, cmd);
1826 case LFUN_INSET_INSERT: {
1827 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1828 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1829 string const name = cmd.getArg(0);
1830 if (name == "label") {
1831 InsetCommandParams p(LABEL_CODE);
1832 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1833 docstring str = p["name"];
1834 cur.recordUndoInset();
1835 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1839 docstring old = label(r);
1842 // The label will take care of the reference update.
1846 // Newly created inset so initialize it.
1847 label_[r]->initView();
1850 cur.forceBufferUpdate();
1853 InsetMathGrid::doDispatch(cur, cmd);
1857 case LFUN_MATH_EXTERN:
1858 cur.recordUndoInset();
1862 case LFUN_MATH_MUTATE: {
1863 cur.recordUndoInset();
1864 row_type row = cur.row();
1865 col_type col = cur.col();
1866 mutate(hullType(cmd.argument()));
1867 cur.idx() = row * ncols() + col;
1868 if (cur.idx() > cur.lastidx()) {
1869 cur.idx() = cur.lastidx();
1870 cur.pos() = cur.lastpos();
1872 if (cur.pos() > cur.lastpos())
1873 cur.pos() = cur.lastpos();
1875 cur.forceBufferUpdate();
1876 // FIXME: find some more clever handling of the selection,
1877 // i.e. preserve it.
1878 cur.clearSelection();
1879 //cur.dispatched(FINISHED);
1883 case LFUN_MATH_DISPLAY: {
1884 cur.recordUndoInset();
1885 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1886 // if the cursor is in a cell that got merged, move it to
1887 // start of the hull inset.
1888 if (cur.idx() > 0) {
1892 if (cur.pos() > cur.lastpos())
1893 cur.pos() = cur.lastpos();
1898 case LFUN_TABULAR_FEATURE:
1899 if (!allowsTabularFeatures())
1902 InsetMathGrid::doDispatch(cur, cmd);
1906 InsetMathGrid::doDispatch(cur, cmd);
1914 bool allowDisplayMath(Cursor const & cur)
1916 LATTEST(cur.depth() > 1);
1917 Cursor tmpcur = cur;
1920 FuncRequest cmd(LFUN_MATH_DISPLAY);
1921 return tmpcur.getStatus(cmd, status) && status.enabled();
1927 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1928 FuncStatus & status) const
1930 switch (cmd.action()) {
1931 case LFUN_FINISHED_BACKWARD:
1932 case LFUN_FINISHED_FORWARD:
1933 case LFUN_FINISHED_RIGHT:
1934 case LFUN_FINISHED_LEFT:
1937 case LFUN_NEWLINE_INSERT:
1938 case LFUN_MATH_EXTERN:
1940 status.setEnabled(true);
1943 // we never allow this in math, and we want to bind enter
1944 // to another actions in command-alternatives
1945 case LFUN_PARAGRAPH_BREAK:
1946 status.setEnabled(false);
1948 case LFUN_MATH_MUTATE: {
1949 HullType const ht = hullType(cmd.argument());
1950 status.setOnOff(type_ == ht);
1951 status.setEnabled(isMutable(ht) && isMutable(type_));
1953 if (ht != hullSimple && status.enabled())
1954 status.setEnabled(allowDisplayMath(cur));
1957 case LFUN_MATH_DISPLAY: {
1958 status.setEnabled(display() != Inline || allowDisplayMath(cur));
1959 status.setOnOff(display() != Inline);
1963 case LFUN_MATH_NUMBER_TOGGLE:
1964 // FIXME: what is the right test, this or the one of
1966 status.setEnabled(display() != Inline);
1967 status.setOnOff(numberedType());
1970 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1971 // FIXME: what is the right test, this or the one of
1973 bool const enable = (type_ == hullMultline)
1974 ? (nrows() - 1 == cur.row())
1975 : display() != Inline;
1976 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1977 status.setEnabled(enable);
1978 status.setOnOff(enable && numbered(r));
1982 case LFUN_LABEL_INSERT:
1983 status.setEnabled(type_ != hullSimple);
1986 case LFUN_LABEL_COPY_AS_REFERENCE: {
1987 bool enabled = false;
1989 if (cmd.argument().empty() && &cur.inset() == this) {
1990 // if there is no argument and we're inside math, we retrieve
1991 // the row number from the cursor position.
1992 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1993 enabled = numberedType() && label_[row] && numbered(row);
1995 // if there is an argument, find the corresponding label, else
1996 // check whether there is at least one label.
1997 for (row_type row = 0; row != nrows(); ++row) {
1998 if (numbered(row) && label_[row] &&
1999 (cmd.argument().empty() || label(row) == cmd.argument())) {
2005 status.setEnabled(enabled);
2009 case LFUN_INSET_INSERT:
2010 if (cmd.getArg(0) == "label") {
2011 status.setEnabled(type_ != hullSimple);
2014 return InsetMathGrid::getStatus(cur, cmd, status);
2016 case LFUN_TABULAR_FEATURE: {
2017 if (!allowsTabularFeatures())
2019 string s = cmd.getArg(0);
2021 && (s == "append-row"
2022 || s == "delete-row"
2023 || s == "copy-row")) {
2024 status.message(bformat(
2025 from_utf8(N_("Can't change number of rows in '%1$s'")),
2027 status.setEnabled(false);
2031 && (s == "append-column"
2032 || s == "delete-column"
2033 || s == "copy-column")) {
2034 status.message(bformat(
2035 from_utf8(N_("Can't change number of columns in '%1$s'")),
2037 status.setEnabled(false);
2040 if (s == "add-vline-left" || s == "add-vline-right") {
2041 status.message(bformat(
2042 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2044 status.setEnabled(false);
2047 if (s == "valign-top" || s == "valign-middle"
2048 || s == "valign-bottom" || s == "align-left"
2049 || s == "align-center" || s == "align-right") {
2050 status.setEnabled(false);
2053 return InsetMathGrid::getStatus(cur, cmd, status);
2057 return InsetMathGrid::getStatus(cur, cmd, status);
2060 // This cannot really happen, but inserted to shut-up gcc
2061 return InsetMathGrid::getStatus(cur, cmd, status);
2065 /////////////////////////////////////////////////////////////////////
2069 // simply scrap this function if you want
2070 void InsetMathHull::mutateToText()
2073 // translate to latex
2075 latex(os, false, false);
2076 string str = os.str();
2079 Text * lt = view_->cursor().innerText();
2080 string::const_iterator cit = str.begin();
2081 string::const_iterator end = str.end();
2082 for (; cit != end; ++cit)
2083 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2086 //dispatch(LFUN_ESCAPE);
2091 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2092 docstring const & font)
2094 // this whole function is a hack and won't work for incremental font
2097 if (cur.inset().asInsetMath()->name() == font)
2098 cur.handleFont(to_utf8(font));
2100 cur.handleNest(createInsetMath(font, cur.buffer()));
2106 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2111 font.fromString(to_utf8(arg), b);
2112 if (font.fontInfo().color() != Color_inherit) {
2113 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2114 cur.handleNest(at, 0);
2119 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2122 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
2123 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
2124 enter_front ? idxFirst(cur) : idxLast(cur);
2125 // The inset formula dimension is not necessarily the same as the
2126 // one of the instant preview image, so we have to indicate to the
2127 // BufferView that a metrics update is needed.
2128 cur.screenUpdateFlags(Update::Force);
2132 void InsetMathHull::revealCodes(Cursor & cur) const
2134 if (!cur.inMathed())
2136 odocstringstream os;
2138 cur.message(os.str());
2140 // write something to the minibuffer
2141 // translate to latex
2145 string str = os.str();
2147 string::size_type pos = 0;
2149 for (string::iterator it = str.begin(); it != str.end(); ++it) {
2152 else if (*it == '\0') {
2154 pos = it - str.begin();
2160 res = res.substr(pos - 30);
2161 if (res.size() > 60)
2162 res = res.substr(0, 60);
2168 /////////////////////////////////////////////////////////////////////
2172 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2175 // FIXME: completely broken
2176 static InsetMathHull * lastformula = 0;
2177 static CursorBase current = DocIterator(ibegin(nucleus()));
2179 static string laststr;
2181 if (lastformula != this || laststr != str) {
2182 //lyxerr << "reset lastformula to " << this << endl;
2185 current = ibegin(nucleus());
2187 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2191 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2193 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2194 CursorSlice & top = it.back();
2195 MathData const & a = top.asInsetMath()->cell(top.idx_);
2196 if (a.matchpart(ar, top.pos_)) {
2197 bv->cursor().setSelection(it, ar.size());
2199 top.pos_ += ar.size();
2205 //lyxerr << "not found!" << endl;
2212 void InsetMathHull::write(ostream & os) const
2214 odocstringstream oss;
2215 otexrowstream ots(oss);
2216 WriteStream wi(ots, false, false, WriteStream::wsDefault);
2219 os << to_utf8(oss.str());
2223 void InsetMathHull::read(Lexer & lex)
2226 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2227 operator=(*at->asHullInset());
2231 bool InsetMathHull::readQuiet(Lexer & lex)
2234 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2236 operator=(*at->asHullInset());
2241 int InsetMathHull::plaintext(odocstringstream & os,
2242 OutputParams const & op, size_t max_length) const
2244 // disables ASCII-art for export of equations. See #2275.
2245 if (0 && display()) {
2249 TextPainter tpain(dim.width(), dim.height());
2250 drawT(tpain, 0, dim.ascent());
2252 // reset metrics cache to "real" values
2254 return tpain.textheight();
2257 odocstringstream oss;
2258 otexrowstream ots(oss);
2259 Encoding const * const enc = encodings.fromLyXName("utf8");
2260 WriteStream wi(ots, false, true, WriteStream::wsDefault, enc);
2263 if (type_ == hullRegexp)
2266 for (row_type r = 0; r < nrows(); ++r) {
2267 for (col_type c = 0; c < ncols(); ++c)
2268 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2269 // if it's for the TOC, we write just the first line
2270 // and do not include the newline.
2271 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2273 if (r < nrows() - 1)
2277 docstring const str = oss.str();
2283 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
2288 if (getType() == hullSimple)
2289 name = from_ascii("inlineequation");
2291 name = from_ascii("informalequation");
2293 docstring bname = name;
2294 if (!label(0).empty())
2295 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
2297 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
2299 odocstringstream ls;
2301 if (runparams.flavor == OutputParams::XML) {
2302 ms << MTag("alt role='tex' ");
2303 // Workaround for db2latex: db2latex always includes equations with
2304 // \ensuremath{} or \begin{display}\end{display}
2305 // so we strip LyX' math environment
2306 WriteStream wi(ols, false, false, WriteStream::wsDefault, runparams.encoding);
2307 InsetMathGrid::write(wi);
2308 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2313 InsetMathGrid::mathmlize(ms);
2316 ms << MTag("alt role='tex'");
2317 latex(ols, runparams);
2318 res = ols.texrow().rows();
2319 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2323 ms << from_ascii("<graphic fileref=\"eqn/");
2324 if (!label(0).empty())
2325 ms << sgml::cleanID(buffer(), runparams, label(0));
2327 ms << sgml::uniqueID(from_ascii("anon"));
2329 if (runparams.flavor == OutputParams::XML)
2330 ms << from_ascii("\"/>");
2332 ms << from_ascii("\">");
2334 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2336 return ms.line() + res;
2340 bool InsetMathHull::haveNumbers() const
2342 bool havenumbers = false;
2343 // inline formulas are never numbered (bug 7351 part 3)
2344 if (getType() == hullSimple)
2346 for (size_t i = 0; i != numbered_.size(); ++i) {
2357 // We need to do something about alignment here.
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::htmlize(HtmlStream & os) const
2364 bool const havenumbers = haveNumbers();
2365 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2368 os << cell(index(0, 0));
2372 os << MTag("table", "class='mathtable'");
2373 for (row_type row = 0; row < nrows(); ++row) {
2375 for (col_type col = 0; col < ncols(); ++col) {
2377 os << cell(index(row, col));
2382 docstring const & num = numbers_[row];
2384 os << '(' << num << ')';
2389 os << ETag("table");
2393 // this duplicates code from InsetMathGrid, but
2394 // we need access here to number information,
2395 // and we simply do not have that in InsetMathGrid.
2396 void InsetMathHull::mathmlize(MathStream & os) const
2398 bool const havenumbers = haveNumbers();
2399 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2402 os << MTag("mtable");
2403 char const * const celltag = havetable ? "mtd" : "mrow";
2404 // FIXME There does not seem to be wide support at the moment
2405 // for mlabeledtr, so we have to use just mtr for now.
2406 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2407 char const * const rowtag = "mtr";
2408 for (row_type row = 0; row < nrows(); ++row) {
2411 for (col_type col = 0; col < ncols(); ++col) {
2413 << cell(index(row, col))
2419 docstring const & num = numbers_[row];
2421 os << '(' << num << ')';
2428 os << ETag("mtable");
2432 void InsetMathHull::mathAsLatex(WriteStream & os) const
2434 MathEnsurer ensurer(os, false);
2435 bool havenumbers = haveNumbers();
2436 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2439 os << cell(index(0, 0));
2443 os << "<table class='mathtable'>";
2444 for (row_type row = 0; row < nrows(); ++row) {
2446 for (col_type col = 0; col < ncols(); ++col) {
2447 os << "<td class='math'>";
2448 os << cell(index(row, col));
2453 docstring const & num = numbers_[row];
2455 os << '(' << num << ')';
2464 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2466 BufferParams::MathOutput const mathtype =
2467 buffer().masterBuffer()->params().html_math_output;
2469 bool success = false;
2471 // we output all the labels just at the beginning of the equation.
2472 // this should be fine.
2473 for (size_t i = 0; i != label_.size(); ++i) {
2474 InsetLabel const * const il = label_[i];
2480 // FIXME Eventually we would like to do this inset by inset.
2481 if (mathtype == BufferParams::MathML) {
2482 odocstringstream os;
2487 } catch (MathExportException const &) {}
2489 if (getType() == hullSimple)
2490 xs << html::StartTag("math",
2491 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2493 xs << html::StartTag("math",
2494 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2495 xs << XHTMLStream::ESCAPE_NONE
2497 << html::EndTag("math");
2499 } else if (mathtype == BufferParams::HTML) {
2500 odocstringstream os;
2505 } catch (MathExportException const &) {}
2507 string const tag = (getType() == hullSimple) ? "span" : "div";
2508 xs << html::StartTag(tag, "class='formula'", true)
2509 << XHTMLStream::ESCAPE_NONE
2511 << html::EndTag(tag);
2515 // what we actually want is this:
2517 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2519 // || mathtype == BufferParams::Images
2521 // but what follows is equivalent, since we'll enter only if either (a) we
2522 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2523 // aren't doing LaTeX.
2525 // so this is for Images.
2526 if (!success && mathtype != BufferParams::LaTeX) {
2527 graphics::PreviewImage const * pimage = 0;
2529 loadPreview(docit_);
2530 pimage = preview_->getPreviewImage(buffer());
2531 // FIXME Do we always have png?
2534 if (pimage || op.dryrun) {
2535 string const filename = pimage ? pimage->filename().onlyFileName()
2536 : "previewimage.png";
2538 // if we are not in the master buffer, then we need to see that the
2539 // generated image is copied there; otherwise, preview fails.
2540 Buffer const * mbuf = buffer().masterBuffer();
2541 if (mbuf != &buffer()) {
2542 string mbtmp = mbuf->temppath();
2543 FileName const mbufimg(support::addName(mbtmp, filename));
2544 pimage->filename().copyTo(mbufimg);
2546 // add the file to the list of files to be exported
2547 op.exportdata->addExternalFile("xhtml", pimage->filename());
2550 string const tag = (getType() == hullSimple) ? "span" : "div";
2552 << html::StartTag(tag, "style = \"text-align: center;\"")
2553 << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2554 << html::EndTag(tag)
2560 // so we'll pass this test if we've failed everything else, or
2561 // if mathtype was LaTeX, since we won't have entered any of the
2563 if (!success /* || mathtype != BufferParams::LaTeX */) {
2564 // Unfortunately, we cannot use latexString() because we do not want
2565 // $...$ or whatever.
2566 odocstringstream ls;
2567 otexrowstream ots(ls);
2568 WriteStream wi(ots, false, true, WriteStream::wsPreview);
2569 ModeSpecifier specifier(wi, MATH_MODE);
2571 docstring const latex = ls.str();
2573 // class='math' allows for use of jsMath
2574 // http://www.math.union.edu/~dpvc/jsMath/
2576 // probably should allow for some kind of customization here
2577 string const tag = (getType() == hullSimple) ? "span" : "div";
2578 xs << html::StartTag(tag, "class='math'")
2580 << html::EndTag(tag)
2587 void InsetMathHull::toString(odocstream & os) const
2589 odocstringstream ods;
2590 plaintext(ods, OutputParams(0));
2595 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2597 odocstringstream ods;
2600 // FIXME: this results in spilling TeX into the LyXHTML output since the
2601 // outliner is used to generate the LyXHTML list of figures/etc.
2607 string InsetMathHull::contextMenuName() const
2609 return "context-math";
2613 void InsetMathHull::recordLocation(DocIterator const & di)
2619 bool InsetMathHull::canPaintChange(BufferView const &) const
2621 // We let RowPainter do it seamlessly for inline insets
2622 return display() != Inline;