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 "InsetMathNest.h"
19 #include "InsetMathScript.h"
20 #include "MathExtern.h"
21 #include "MathFactory.h"
22 #include "MathStream.h"
23 #include "MathSupport.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
29 #include "CutAndPaste.h"
32 #include "FuncRequest.h"
33 #include "FuncStatus.h"
35 #include "LaTeXFeatures.h"
37 #include "MacroTable.h"
38 #include "MathMacro.h"
39 #include "MathMacroTemplate.h"
40 #include "MetricsInfo.h"
41 #include "output_xhtml.h"
42 #include "Paragraph.h"
43 #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)->mathClass() == MC_REL)
112 return it - ar.begin();
117 char const * star(bool numbered)
119 return numbered ? "" : "*";
123 // writes a preamble for underlined or struck out math display
124 void writeMathdisplayPreamble(WriteStream & os)
126 if (os.strikeoutMath()) {
127 if (os.ulemCmd() == WriteStream::UNDERLINE)
128 os << "\\raisebox{-\\belowdisplayshortskip}{"
129 "\\lyxmathsout{\\parbox[b]{\\columnwidth}{";
131 os << "\\lyxmathsout{\\parbox{\\columnwidth}{";
132 } else if (os.ulemCmd() == WriteStream::UNDERLINE)
133 os << "\\raisebox{-\\belowdisplayshortskip}{"
134 "\\parbox[b]{\\columnwidth}{";
135 else if (os.ulemCmd() == WriteStream::STRIKEOUT)
136 os << "\\parbox{\\columnwidth}{";
140 // writes a postamble for underlined or struck out math display
141 void writeMathdisplayPostamble(WriteStream & os)
143 if (os.strikeoutMath()) {
144 if (os.ulemCmd() == WriteStream::UNDERLINE)
147 } else if (os.ulemCmd() == WriteStream::UNDERLINE)
149 else if (os.ulemCmd() == WriteStream::STRIKEOUT)
154 } // end anon namespace
157 HullType hullType(docstring const & s)
159 if (s == "none") return hullNone;
160 if (s == "simple") return hullSimple;
161 if (s == "equation") return hullEquation;
162 if (s == "eqnarray") return hullEqnArray;
163 if (s == "align") return hullAlign;
164 if (s == "alignat") return hullAlignAt;
165 if (s == "xalignat") return hullXAlignAt;
166 if (s == "xxalignat") return hullXXAlignAt;
167 if (s == "multline") return hullMultline;
168 if (s == "gather") return hullGather;
169 if (s == "flalign") return hullFlAlign;
170 if (s == "regexp") return hullRegexp;
171 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
176 docstring hullName(HullType type)
179 case hullNone: return from_ascii("none");
180 case hullSimple: return from_ascii("simple");
181 case hullEquation: return from_ascii("equation");
182 case hullEqnArray: return from_ascii("eqnarray");
183 case hullAlign: return from_ascii("align");
184 case hullAlignAt: return from_ascii("alignat");
185 case hullXAlignAt: return from_ascii("xalignat");
186 case hullXXAlignAt: return from_ascii("xxalignat");
187 case hullMultline: return from_ascii("multline");
188 case hullGather: return from_ascii("gather");
189 case hullFlAlign: return from_ascii("flalign");
190 case hullRegexp: return from_ascii("regexp");
192 lyxerr << "unknown hull type" << endl;
195 return from_ascii("none");
198 static InsetLabel * dummy_pointer = 0;
200 InsetMathHull::InsetMathHull(Buffer * buf)
201 : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, NUMBER),
202 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
203 preview_(new RenderPreview(this))
205 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
206 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
207 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
208 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
215 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
216 : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, NUMBER),
217 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
218 preview_(new RenderPreview(this))
226 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
232 InsetMathHull::~InsetMathHull()
234 for (size_t i = 0; i < label_.size(); ++i)
239 Inset * InsetMathHull::clone() const
241 return new InsetMathHull(*this);
245 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
249 InsetMathGrid::operator=(other);
251 numbered_ = other.numbered_;
252 numbers_ = other.numbers_;
253 buffer_ = other.buffer_;
254 for (size_t i = 0; i < label_.size(); ++i)
256 label_ = other.label_;
257 for (size_t i = 0; i != label_.size(); ++i) {
259 label_[i] = new InsetLabel(*label_[i]);
261 preview_.reset(new RenderPreview(*other.preview_, this));
267 void InsetMathHull::setBuffer(Buffer & buffer)
269 InsetMathGrid::setBuffer(buffer);
271 for (size_t i = 0; i != label_.size(); ++i) {
273 label_[i]->setBuffer(buffer);
278 // FIXME This should really be controlled by the TOC level, or
279 // something of the sort.
281 const char * counters_to_save[] = {"section", "chapter"};
282 unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
286 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
289 //FIXME: buffer_ should be set at creation for this inset! Problem is
290 // This inset is created at too many places (see Parser::parse1() in
295 // if any of the equations are numbered, then we want to save the values
296 // of some of the counters.
298 BufferParams const & bp = buffer_->params();
299 string const & lang = it->getParLanguage(bp)->code();
301 buffer_->masterBuffer()->params().documentClass().counters();
303 // right now, we only need to do this at export time
304 if (utype == OutputUpdate) {
305 for (size_t i = 0; i < numcnts; ++i) {
306 docstring const cnt = from_ascii(counters_to_save[i]);
307 if (cnts.hasCounter(cnt))
308 counter_map[cnt] = cnts.value(cnt);
312 // this has to be done separately
313 docstring const eqstr = from_ascii("equation");
314 if (cnts.hasCounter(eqstr)) {
315 if (utype == OutputUpdate)
316 counter_map[eqstr] = cnts.value(eqstr);
317 for (size_t i = 0; i != label_.size(); ++i) {
319 cnts.step(eqstr, utype);
320 numbers_[i] = cnts.theCounter(eqstr, lang);
322 numbers_[i] = empty_docstring();
328 for (size_t i = 0; i != label_.size(); ++i) {
330 label_[i]->updateBuffer(it, utype);
333 InsetMathGrid::updateBuffer(it, utype);
337 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active,
338 UpdateType utype) const
341 //FIXME: buffer_ should be set at creation for this inset! Problem is
342 // This inset is created at too many places (see Parser::parse1() in
347 shared_ptr<Toc> toc = buffer().tocBackend().toc("equation");
349 for (row_type row = 0; row != nrows(); ++row) {
353 label_[row]->addToToc(pit, output_active, utype);
354 toc->push_back(TocItem(pit, 0, nicelabel(row), output_active));
359 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
361 if (previewState(&cur.bv())) {
365 return InsetMathNest::editXY(cur, x, y);
369 InsetMath::mode_type InsetMathHull::currentMode() const
373 return UNDECIDED_MODE;
375 // definitely math mode ...
395 bool InsetMathHull::idxFirst(Cursor & cur) const
403 bool InsetMathHull::idxLast(Cursor & cur) const
405 cur.idx() = nargs() - 1;
406 cur.pos() = cur.lastpos();
411 // FIXME: InsetMathGrid should be changed to let the real column alignment be
412 // given by a virtual method like displayColAlign, because the values produced
413 // by defaultColAlign can be invalidated by lfuns such as add-column. For the
414 // moment the values produced by defaultColAlign are not used, notably because
415 // alignment is not implemented in the LyXHTML output.
416 char InsetMathHull::defaultColAlign(col_type col)
418 return colAlign(type_, col);
422 char InsetMathHull::displayColAlign(idx_type idx) const
426 row_type const r = row(idx);
429 if (r == nrows() - 1)
440 return colAlign(type_, col(idx));
444 return InsetMathGrid::displayColAlign(idx);
448 int InsetMathHull::displayColSpace(col_type col) const
450 return colSpace(type_, col);
454 // FIXME: same comment as for defaultColAlign applies.
455 int InsetMathHull::defaultColSpace(col_type col)
457 return colSpace(type_, col);
461 string InsetMathHull::standardFont() const
467 return "lyxnochange";
474 ColorCode InsetMathHull::standardColor() const
479 return Color_foreground;
487 bool InsetMathHull::previewState(const BufferView *const bv) const
489 if (!editing(bv) && RenderPreview::previewMath()
490 && type_ != hullRegexp)
492 graphics::PreviewImage const * pimage =
493 preview_->getPreviewImage(bv->buffer());
494 return pimage && pimage->image();
501 static const int ERROR_FRAME_WIDTH = 2;
504 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
506 if (previewState(mi.base.bv)) {
507 preview_->metrics(mi, dim);
508 if (previewTooSmall(dim)) {
509 // preview image is too small
510 dim.wid += 2 * ERROR_FRAME_WIDTH;
511 dim.asc += 2 * ERROR_FRAME_WIDTH;
513 // insert a one pixel gap in front of the formula
516 dim.des += displayMargin();
521 Changer dummy1 = mi.base.changeFontSet(standardFont());
522 Changer dummy2 = mi.base.font.changeStyle(display() ? LM_ST_DISPLAY
525 // let the cells adjust themselves
526 InsetMathGrid::metrics(mi, dim);
529 dim.asc += displayMargin();
530 dim.des += displayMargin();
533 if (numberedType()) {
534 Changer dummy = mi.base.changeFontSet("mathbf");
536 for (row_type row = 0; row < nrows(); ++row)
537 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
543 if (type_ == hullRegexp)
545 // make it at least as high as the current font
548 math_font_max_dim(mi.base.font, asc, des);
549 dim.asc = max(dim.asc, asc);
550 dim.des = max(dim.des, des);
554 bool InsetMathHull::previewTooSmall(Dimension const & dim) const
556 return dim.width() <= 10 && dim.height() <= 10;
560 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
562 BufferView const * const bv = pi.base.bv;
563 if (previewState(bv)) {
564 Dimension const dim = dimension(*pi.base.bv);
565 if (previewTooSmall(dim))
567 return graphics::PreviewLoader::backgroundColor();
573 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
575 Dimension const dim = dimension(*pi.base.bv);
576 if (previewTooSmall(dim)) {
577 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
578 dim.wid, dim.asc + dim.des, backgroundColor(pi));
581 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
582 dim.asc + dim.des - 1, pi.backgroundColor(this));
586 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
588 BufferView const * const bv = pi.base.bv;
589 Dimension const dim = dimension(*bv);
591 if (type_ == hullRegexp)
592 pi.pain.rectangle(x + 2, y - dim.ascent() + 1,
593 dim.width() - 3, dim.height() - 2, Color_regexpframe);
595 if (previewState(bv)) {
596 // Do not draw change tracking cue if taken care of by RowPainter
598 Changer dummy = !canPaintChange(*bv) ? make_change(pi.change_, Change())
600 if (previewTooSmall(dim)) {
601 // we have an extra frame
602 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
604 // one pixel gap in front
605 preview_->draw(pi, x + 1, y);
610 ColorCode color = pi.selected && lyxrc.use_system_colors
611 ? Color_selectiontext : standardColor();
612 bool const really_change_color = pi.base.font.color() == Color_none;
613 Changer dummy0 = really_change_color ? pi.base.font.changeColor(color)
615 Changer dummy1 = pi.base.changeFontSet(standardFont());
616 Changer dummy2 = pi.base.font.changeStyle(display() ? LM_ST_DISPLAY
619 InsetMathGrid::draw(pi, x + 1, y);
621 if (numberedType()) {
622 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
623 for (row_type row = 0; row < nrows(); ++row) {
624 int const yy = y + rowinfo_[row].offset_;
625 Changer dummy = pi.base.changeFontSet("mathrm");
626 docstring const nl = nicelabel(row);
630 // drawing change line
631 if (canPaintChange(*bv))
632 pi.change_.paintCue(pi, x + 1, y + 1 - dim.asc,
633 x + dim.wid, y + dim.des);
637 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
640 InsetMathGrid::metricsT(mi, dim);
643 otexrowstream ots(os);
644 WriteStream wi(ots, false, true, WriteStream::wsDefault);
646 dim.wid = os.str().size();
653 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
656 InsetMathGrid::drawT(pain, x, y);
659 otexrowstream ots(os);
660 WriteStream wi(ots, false, true, WriteStream::wsDefault);
662 pain.draw(x, y, os.str().c_str());
667 static docstring latexString(InsetMathHull const & inset)
670 // This has to be static, because a preview snippet or a math
671 // macro containing math in text mode (such as $\text{$\phi$}$ or
672 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
673 // first time as a whole, and the second time only the inner math.
674 // In this last case inset.buffer() would be invalid.
675 static Encoding const * encoding = 0;
676 if (inset.isBufferValid())
677 encoding = &(inset.buffer().params().encoding());
678 otexrowstream ots(ls);
679 WriteStream wi(ots, false, true, WriteStream::wsPreview, encoding);
685 void InsetMathHull::initUnicodeMath() const
687 // Trigger classification of the unicode symbols in this inset
688 docstring const dummy = latexString(*this);
692 void InsetMathHull::addPreview(DocIterator const & inset_pos,
693 graphics::PreviewLoader & /*ploader*/) const
695 if (RenderPreview::previewMath()) {
696 preparePreview(inset_pos);
701 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
702 MacroNameSet & macros, MacroNameSet & defs) const
704 MacroNameSet::iterator const end = macros.end();
706 for (size_t i = 0; i < md.size(); ++i) {
707 MathMacro const * mi = md[i].nucleus()->asMacro();
708 MathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
709 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
710 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
711 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
712 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
714 // Look for macros in the arguments of this macro.
715 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
716 usedMacros(mi->cell(idx), pos, macros, defs);
717 // Make sure this is a macro defined in the document
718 // (as we also spot the macros in the symbols file)
719 // or that we have not already accounted for it.
720 docstring const name = mi->name();
721 if (macros.find(name) == end)
724 // Look for macros in the definition of this macro.
725 MathData ar(pos.buffer());
726 MacroData const * data =
727 pos.buffer()->getMacro(name, pos, true);
729 odocstringstream macro_def;
730 data->write(macro_def, true);
732 defs.insert(macro_def.str());
733 asArray(data->definition(), ar);
735 usedMacros(ar, pos, macros, defs);
737 MathData ar(pos.buffer());
738 asArray(mt->definition(), ar);
739 usedMacros(ar, pos, macros, defs);
741 if (!si->nuc().empty())
742 usedMacros(si->nuc(), pos, macros, defs);
744 usedMacros(si->down(), pos, macros, defs);
746 usedMacros(si->up(), pos, macros, defs);
747 } else if (fi || gi) {
748 idx_type nidx = fi ? fi->nargs() : gi->nargs();
749 for (idx_type idx = 0; idx < nidx; ++idx)
750 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
753 usedMacros(ni->cell(0), pos, macros, defs);
759 void InsetMathHull::preparePreview(DocIterator const & pos,
760 bool forexport) const
762 // there is no need to do all the macro stuff if we're not
763 // actually going to generate the preview.
764 if (!RenderPreview::previewMath() && !forexport)
767 Buffer const * buffer = pos.buffer();
769 // collect macros at this position
771 buffer->listMacroNames(macros);
773 // collect definitions only for the macros used in this inset
775 for (idx_type idx = 0; idx < nargs(); ++idx)
776 usedMacros(cell(idx), pos, macros, defs);
778 MacroNameSet::iterator it = defs.begin();
779 MacroNameSet::iterator end = defs.end();
780 docstring macro_preamble;
781 for (; it != end; ++it)
782 macro_preamble.append(*it);
784 // set the font series and size for this snippet
785 DocIterator dit = pos.getInnerText();
786 Paragraph const & par = dit.paragraph();
787 Font font = par.getFontSettings(buffer->params(), dit.pos());
788 font.fontInfo().realize(par.layout().font);
789 string const lsize = font.latexSize();
792 if (font.fontInfo().series() == BOLD_SERIES) {
793 setfont += from_ascii("\\textbf{");
796 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
797 setfont += from_ascii("\\" + lsize + '\n');
800 if (forexport && haveNumbers()) {
801 docstring eqstr = from_ascii("equation");
802 CounterMap::const_iterator it = counter_map.find(eqstr);
803 if (it != counter_map.end()) {
804 int num = it->second;
806 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
807 '{' + convert<docstring>(num) + '}' + '\n';
809 for (size_t i = 0; i != numcnts; ++i) {
810 docstring cnt = from_ascii(counters_to_save[i]);
811 it = counter_map.find(cnt);
812 if (it == counter_map.end())
814 int num = it->second;
816 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
817 '{' + convert<docstring>(num) + '}';
820 docstring const snippet = macro_preamble + setfont + setcnt
821 + latexString(*this) + endfont;
822 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
823 preview_->addPreview(snippet, *buffer, forexport);
827 void InsetMathHull::reloadPreview(DocIterator const & pos) const
830 preview_->startLoading(*pos.buffer());
834 void InsetMathHull::loadPreview(DocIterator const & pos) const
836 bool const forexport = true;
837 preparePreview(pos, forexport);
838 preview_->startLoading(*pos.buffer(), forexport);
842 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
844 if (RenderPreview::previewMath()) {
846 cur.screenUpdateFlags(Update::Force);
852 docstring InsetMathHull::label(row_type row) const
854 LASSERT(row < nrows(), return docstring());
855 if (InsetLabel * il = label_[row])
856 return il->screenLabel();
861 void InsetMathHull::label(row_type row, docstring const & label)
863 //lyxerr << "setting label '" << label << "' for row " << row << endl;
867 label_[row] = dummy_pointer;
870 label_[row]->updateLabelAndRefs(label);
872 label_[row]->setParam("name", label);
876 InsetCommandParams p(LABEL_CODE);
878 label_[row] = new InsetLabel(buffer_, p);
880 label_[row]->setBuffer(buffer());
884 void InsetMathHull::numbered(row_type row, Numbered num)
886 numbered_[row] = num;
887 if (!numbered(row) && label_[row]) {
894 bool InsetMathHull::numbered(row_type row) const
896 return numbered_[row] == NUMBER;
900 bool InsetMathHull::ams() const
920 for (size_t row = 0; row < numbered_.size(); ++row)
921 if (numbered_[row] == NOTAG)
927 bool InsetMathHull::outerDisplay() const
950 Inset::DisplayType InsetMathHull::display() const
973 bool InsetMathHull::numberedType() const
992 for (row_type row = 0; row < nrows(); ++row)
999 void InsetMathHull::validate(LaTeXFeatures & features) const
1001 if (features.runparams().isLaTeX()) {
1003 features.require("amsmath");
1005 if (type_ == hullRegexp) {
1006 features.require("color");
1007 docstring frcol = from_utf8(lcolor.getLaTeXName(Color_regexpframe));
1008 docstring bgcol = from_ascii("white");
1009 features.addPreambleSnippet(
1010 "\\newcommand{\\regexp}[1]{\\fcolorbox{"
1012 + bgcol + "}{\\ensuremath{\\mathtt{#1}}}}");
1013 features.addPreambleSnippet(
1014 from_ascii("\\newcommand{\\endregexp}{}"));
1015 } else if (outerDisplay() && features.inDeletedInset()
1016 && !features.mustProvide("ct-dvipost")) {
1017 features.require("ct-tikz-math-sout");
1020 // Validation is necessary only if not using AMS math.
1021 // To be safe, we will always run mathedvalidate.
1022 //if (features.amsstyle)
1025 //features.binom = true;
1026 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
1027 // it would be better to do this elsewhere, but we can't validate in
1028 // InsetMathMatrix and we have no way, outside MathExtern, to know if
1029 // we even have any matrices.
1030 features.addCSSSnippet(
1031 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
1032 "table.matrix td{padding: 0.25px;}\n"
1033 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
1034 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
1036 InsetMathGrid::validate(features);
1040 void InsetMathHull::header_write(WriteStream & os) const
1042 bool n = numberedType();
1053 if (cell(0).empty())
1058 writeMathdisplayPreamble(os);
1062 os << "\\begin{equation" << star(n) << "}\n";
1072 writeMathdisplayPreamble(os);
1075 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1082 os << "\\begin{" << hullName(type_) << star(n) << '}'
1083 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1089 os << "\\begin{" << hullName(type_) << '}'
1090 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1100 os << "\\begin{unknown" << star(n) << "}\n";
1106 void InsetMathHull::footer_write(WriteStream & os) const
1108 bool n = numberedType();
1125 os << "\\end{equation" << star(n) << "}\n";
1128 writeMathdisplayPostamble(os);
1138 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1139 writeMathdisplayPostamble(os);
1146 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1152 os << "\\end{" << hullName(type_) << "}\n";
1156 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1157 os << "\\endregexp{}}";
1163 os << "\\end{unknown" << star(n) << "}\n";
1169 bool InsetMathHull::allowsTabularFeatures() const
1192 bool InsetMathHull::rowChangeOK() const
1195 type_ == hullEqnArray || type_ == hullAlign ||
1196 type_ == hullFlAlign || type_ == hullAlignAt ||
1197 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1198 type_ == hullGather || type_ == hullMultline;
1202 bool InsetMathHull::colChangeOK() const
1205 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1206 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1210 void InsetMathHull::addRow(row_type row)
1215 bool numbered = numberedType();
1216 // Move the number and raw pointer, do not call label() (bug 7511)
1217 InsetLabel * label = dummy_pointer;
1218 docstring number = empty_docstring();
1219 if (type_ == hullMultline) {
1220 if (row + 1 == nrows()) {
1221 numbered_[row] = NONUMBER;
1222 swap(label, label_[row]);
1223 swap(number, numbers_[row]);
1228 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1229 numbers_.insert(numbers_.begin() + row + 1, number);
1230 label_.insert(label_.begin() + row + 1, label);
1231 InsetMathGrid::addRow(row);
1235 void InsetMathHull::swapRow(row_type row)
1239 if (row + 1 == nrows())
1241 swap(numbered_[row], numbered_[row + 1]);
1242 swap(numbers_[row], numbers_[row + 1]);
1243 swap(label_[row], label_[row + 1]);
1244 InsetMathGrid::swapRow(row);
1248 void InsetMathHull::delRow(row_type row)
1250 if (nrows() <= 1 || !rowChangeOK())
1252 if (row + 1 == nrows() && type_ == hullMultline) {
1253 swap(numbered_[row - 1], numbered_[row]);
1254 swap(numbers_[row - 1], numbers_[row]);
1255 swap(label_[row - 1], label_[row]);
1256 InsetMathGrid::delRow(row);
1259 InsetMathGrid::delRow(row);
1260 // The last dummy row has no number info nor a label.
1261 // Test nrows() + 1 because we have already erased the row.
1262 if (row == nrows() + 1)
1264 numbered_.erase(numbered_.begin() + row);
1265 numbers_.erase(numbers_.begin() + row);
1267 label_.erase(label_.begin() + row);
1271 void InsetMathHull::addCol(col_type col)
1275 InsetMathGrid::addCol(col);
1279 void InsetMathHull::delCol(col_type col)
1281 if (ncols() <= 1 || !colChangeOK())
1283 InsetMathGrid::delCol(col);
1287 docstring InsetMathHull::nicelabel(row_type row) const
1291 docstring const & val = numbers_[row];
1293 return '(' + val + ')';
1294 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1298 void InsetMathHull::glueall(HullType type)
1301 for (idx_type i = 0; i < nargs(); ++i)
1303 InsetLabel * label = 0;
1304 if (type == hullEquation) {
1305 // preserve first non-empty label
1306 for (row_type row = 0; row < nrows(); ++row) {
1308 label = label_[row];
1314 *this = InsetMathHull(buffer_, hullSimple);
1321 void InsetMathHull::splitTo2Cols()
1323 LASSERT(ncols() == 1, return);
1324 InsetMathGrid::addCol(1);
1325 for (row_type row = 0; row < nrows(); ++row) {
1326 idx_type const i = 2 * row;
1327 pos_type pos = firstRelOp(cell(i));
1328 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1329 cell(i).erase(pos, cell(i).size());
1334 void InsetMathHull::splitTo3Cols()
1336 LASSERT(ncols() < 3, return);
1339 InsetMathGrid::addCol(2);
1340 for (row_type row = 0; row < nrows(); ++row) {
1341 idx_type const i = 3 * row + 1;
1342 if (!cell(i).empty()) {
1343 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1344 cell(i).erase(1, cell(i).size());
1350 void InsetMathHull::changeCols(col_type cols)
1352 if (ncols() == cols)
1354 else if (ncols() < cols) {
1360 while (ncols() < cols)
1361 InsetMathGrid::addCol(ncols());
1367 for (row_type row = 0; row < nrows(); ++row) {
1368 idx_type const i = row * ncols();
1369 for (col_type col = cols; col < ncols(); ++col) {
1370 cell(i + cols - 1).append(cell(i + col));
1374 while (ncols() > cols) {
1375 InsetMathGrid::delCol(ncols() - 1);
1380 HullType InsetMathHull::getType() const
1386 void InsetMathHull::setType(HullType type)
1393 bool InsetMathHull::isMutable(HullType type)
1417 void InsetMathHull::mutate(HullType newtype)
1419 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1421 if (newtype == type_)
1424 // This guards the algorithm below it, which is designed with certain types
1426 if (!isMutable(newtype) || !isMutable(type_)) {
1427 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1428 << "' to '" << to_utf8(hullName(newtype))
1429 << "' not implemented" << endl;
1433 // we try to move along the chain
1434 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1436 // +-------------------------------------+
1437 // we use eqnarray as intermediate type for mutations that are not
1438 // directly supported because it handles labels and numbering for
1443 setType(hullSimple);
1449 if (newtype == hullNone) {
1453 setType(hullEquation);
1454 numbered(0, label_[0] ? true : false);
1463 setType(hullSimple);
1468 // split it "nicely" on the first relop
1470 setType(hullEqnArray);
1478 // split it "nicely"
1513 setType(hullEqnArray);
1522 for (row_type row = 0; row < nrows(); ++row)
1523 numbered(row, false);
1533 for (row_type row = 0; row < nrows(); ++row)
1534 numbered(row, false);
1541 setType(hullEqnArray);
1571 for (row_type row = 0; row < nrows(); ++row)
1572 numbered(row, false);
1576 // first we mutate to EqnArray
1578 setType(hullEqnArray);
1585 // we passed the guard so we should not be here
1586 LASSERT("Mutation not implemented, but should have been.", return);
1592 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1593 bool last_eoln) const
1596 if (numberedType()) {
1597 if (label_[row] && numbered(row)) {
1598 docstring const name =
1599 latex ? escape(label_[row]->getParam("name"))
1600 : label_[row]->getParam("name");
1601 res += "\\label{" + name + '}';
1603 if (type_ != hullMultline) {
1604 if (numbered_[row] == NONUMBER)
1605 res += "\\nonumber ";
1606 else if (numbered_[row] == NOTAG)
1610 // Never add \\ on the last empty line of eqnarray and friends
1612 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1615 void InsetMathHull::write(WriteStream & os) const
1617 ModeSpecifier specifier(os, MATH_MODE);
1619 InsetMathGrid::write(os);
1624 void InsetMathHull::normalize(NormalStream & os) const
1626 os << "[formula " << hullName(type_) << ' ';
1627 InsetMathGrid::normalize(os);
1632 void InsetMathHull::infoize(odocstream & os) const
1634 os << bformat(_("Type: %1$s"), hullName(type_));
1638 void InsetMathHull::check() const
1640 LATTEST(numbered_.size() == nrows());
1641 LATTEST(numbers_.size() == nrows());
1642 LATTEST(label_.size() == nrows());
1646 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1650 idocstringstream iss(func.argument());
1651 iss >> dlang >> extra;
1653 extra = from_ascii("noextra");
1654 string const lang = to_ascii(dlang);
1656 // replace selection with result of computation
1657 if (reduceSelectionToOneCell(cur)) {
1659 asArray(grabAndEraseSelection(cur), ar);
1660 lyxerr << "use selection: " << ar << endl;
1661 cur.insert(pipeThroughExtern(lang, extra, ar));
1665 // only inline, display or eqnarray math is allowed
1666 switch (getType()) {
1672 frontend::Alert::warning(_("Bad math environment"),
1673 _("Computation cannot be performed for AMS "
1674 "math environments.\nChange the math "
1675 "formula type and try again."));
1680 eq.push_back(MathAtom(new InsetMathChar('=')));
1682 // go to first item in line
1683 cur.idx() -= cur.idx() % ncols();
1686 if (getType() == hullSimple) {
1687 size_type pos = cur.cell().find_last(eq);
1689 if (pos == cur.cell().size()) {
1691 lyxerr << "use whole cell: " << ar << endl;
1693 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1694 lyxerr << "use partial cell form pos: " << pos << endl;
1696 cur.cell().append(eq);
1697 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1698 cur.pos() = cur.lastpos();
1702 if (getType() == hullEquation) {
1703 lyxerr << "use equation inset" << endl;
1704 mutate(hullEqnArray);
1705 MathData & ar = cur.cell();
1706 lyxerr << "use cell: " << ar << endl;
1710 cur.cell() = pipeThroughExtern(lang, extra, ar);
1711 // move to end of line
1712 cur.pos() = cur.lastpos();
1717 lyxerr << "use eqnarray" << endl;
1718 cur.idx() += 2 - cur.idx() % ncols();
1720 MathData ar = cur.cell();
1721 lyxerr << "use cell: " << ar << endl;
1722 // FIXME: temporarily disabled
1728 cur.cell() = pipeThroughExtern(lang, extra, ar);
1729 cur.pos() = cur.lastpos();
1734 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1736 //lyxerr << "action: " << cmd.action() << endl;
1737 switch (cmd.action()) {
1739 case LFUN_FINISHED_BACKWARD:
1740 case LFUN_FINISHED_FORWARD:
1741 case LFUN_FINISHED_RIGHT:
1742 case LFUN_FINISHED_LEFT:
1743 //lyxerr << "action: " << cmd.action() << endl;
1744 InsetMathGrid::doDispatch(cur, cmd);
1747 case LFUN_PARAGRAPH_BREAK:
1748 // just swallow this
1751 case LFUN_NEWLINE_INSERT:
1752 // some magic for the common case
1753 if (type_ == hullSimple || type_ == hullEquation) {
1754 cur.recordUndoInset();
1756 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1757 mutate(align ? hullAlign : hullEqnArray);
1758 // mutate() may change labels and such.
1759 cur.forceBufferUpdate();
1760 cur.idx() = nrows() * ncols() - 1;
1761 cur.pos() = cur.lastpos();
1763 InsetMathGrid::doDispatch(cur, cmd);
1766 case LFUN_MATH_NUMBER_TOGGLE: {
1767 //lyxerr << "toggling all numbers" << endl;
1768 cur.recordUndoInset();
1769 bool old = numberedType();
1770 if (type_ == hullMultline)
1771 numbered(nrows() - 1, !old);
1773 for (row_type row = 0; row < nrows(); ++row)
1774 numbered(row, !old);
1776 cur.message(old ? _("No number") : _("Number"));
1777 cur.forceBufferUpdate();
1781 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1782 cur.recordUndoInset();
1783 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1784 bool old = numbered(r);
1785 cur.message(old ? _("No number") : _("Number"));
1787 cur.forceBufferUpdate();
1791 case LFUN_LABEL_INSERT: {
1792 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1793 docstring old_label = label(r);
1794 docstring const default_label = from_ascii("eq:");
1795 if (old_label.empty())
1796 old_label = default_label;
1798 InsetCommandParams p(LABEL_CODE);
1799 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1800 string const data = InsetCommand::params2string(p);
1802 if (cmd.argument().empty())
1803 cur.bv().showDialog("label", data);
1805 FuncRequest fr(LFUN_INSET_INSERT, data);
1811 case LFUN_LABEL_COPY_AS_REFERENCE: {
1813 if (cmd.argument().empty() && &cur.inset() == this)
1814 // if there is no argument and we're inside math, we retrieve
1815 // the row number from the cursor position.
1816 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1818 // if there is an argument, find the corresponding label, else
1819 // check whether there is at least one label.
1820 for (row = 0; row != nrows(); ++row)
1821 if (numbered(row) && label_[row]
1822 && (cmd.argument().empty() || label(row) == cmd.argument()))
1829 InsetCommandParams p(REF_CODE, "ref");
1830 p["reference"] = label(row);
1831 cap::clearSelection();
1832 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1836 case LFUN_WORD_DELETE_FORWARD:
1837 case LFUN_CHAR_DELETE_FORWARD:
1838 if (col(cur.idx()) + 1 == ncols()
1839 && cur.pos() == cur.lastpos()
1840 && !cur.selection()) {
1841 if (!label(row(cur.idx())).empty()) {
1842 cur.recordUndoInset();
1843 label(row(cur.idx()), docstring());
1844 } else if (numbered(row(cur.idx()))) {
1845 cur.recordUndoInset();
1846 numbered(row(cur.idx()), false);
1847 cur.forceBufferUpdate();
1849 InsetMathGrid::doDispatch(cur, cmd);
1853 InsetMathGrid::doDispatch(cur, cmd);
1858 case LFUN_INSET_INSERT: {
1859 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1860 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1861 string const name = cmd.getArg(0);
1862 if (name == "label") {
1863 InsetCommandParams p(LABEL_CODE);
1864 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1865 docstring str = p["name"];
1866 cur.recordUndoInset();
1867 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1871 docstring old = label(r);
1874 // The label will take care of the reference update.
1878 // Newly created inset so initialize it.
1879 label_[r]->initView();
1882 cur.forceBufferUpdate();
1885 InsetMathGrid::doDispatch(cur, cmd);
1889 case LFUN_MATH_EXTERN:
1890 cur.recordUndoInset();
1894 case LFUN_MATH_MUTATE: {
1895 cur.recordUndoInset();
1896 row_type row = cur.row();
1897 col_type col = cur.col();
1898 mutate(hullType(cmd.argument()));
1899 cur.idx() = row * ncols() + col;
1900 if (cur.idx() > cur.lastidx()) {
1901 cur.idx() = cur.lastidx();
1902 cur.pos() = cur.lastpos();
1904 if (cur.pos() > cur.lastpos())
1905 cur.pos() = cur.lastpos();
1907 cur.forceBufferUpdate();
1908 // FIXME: find some more clever handling of the selection,
1909 // i.e. preserve it.
1910 cur.clearSelection();
1911 //cur.dispatched(FINISHED);
1915 case LFUN_MATH_DISPLAY: {
1916 cur.recordUndoInset();
1917 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1918 // if the cursor is in a cell that got merged, move it to
1919 // start of the hull inset.
1920 if (cur.idx() > 0) {
1924 if (cur.pos() > cur.lastpos())
1925 cur.pos() = cur.lastpos();
1930 case LFUN_TABULAR_FEATURE:
1931 if (!allowsTabularFeatures())
1934 InsetMathGrid::doDispatch(cur, cmd);
1938 InsetMathGrid::doDispatch(cur, cmd);
1946 bool allowDisplayMath(Cursor const & cur)
1948 LATTEST(cur.depth() > 1);
1949 Cursor tmpcur = cur;
1952 FuncRequest cmd(LFUN_MATH_DISPLAY);
1953 return tmpcur.getStatus(cmd, status) && status.enabled();
1959 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1960 FuncStatus & status) const
1962 switch (cmd.action()) {
1963 case LFUN_FINISHED_BACKWARD:
1964 case LFUN_FINISHED_FORWARD:
1965 case LFUN_FINISHED_RIGHT:
1966 case LFUN_FINISHED_LEFT:
1969 case LFUN_NEWLINE_INSERT:
1970 case LFUN_MATH_EXTERN:
1972 status.setEnabled(true);
1975 // we never allow this in math, and we want to bind enter
1976 // to another actions in command-alternatives
1977 case LFUN_PARAGRAPH_BREAK:
1978 status.setEnabled(false);
1980 case LFUN_MATH_MUTATE: {
1981 HullType const ht = hullType(cmd.argument());
1982 status.setOnOff(type_ == ht);
1983 status.setEnabled(isMutable(ht) && isMutable(type_));
1985 if (ht != hullSimple && status.enabled())
1986 status.setEnabled(allowDisplayMath(cur));
1989 case LFUN_MATH_DISPLAY: {
1990 status.setEnabled(display() != Inline || allowDisplayMath(cur));
1991 status.setOnOff(display() != Inline);
1995 case LFUN_MATH_NUMBER_TOGGLE:
1996 // FIXME: what is the right test, this or the one of
1998 status.setEnabled(display() != Inline);
1999 status.setOnOff(numberedType());
2002 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
2003 // FIXME: what is the right test, this or the one of
2005 bool const enable = (type_ == hullMultline)
2006 ? (nrows() - 1 == cur.row())
2007 : display() != Inline;
2008 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2009 status.setEnabled(enable);
2010 status.setOnOff(enable && numbered(r));
2014 case LFUN_LABEL_INSERT:
2015 status.setEnabled(type_ != hullSimple);
2018 case LFUN_LABEL_COPY_AS_REFERENCE: {
2019 bool enabled = false;
2021 if (cmd.argument().empty() && &cur.inset() == this) {
2022 // if there is no argument and we're inside math, we retrieve
2023 // the row number from the cursor position.
2024 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2025 enabled = numberedType() && label_[row] && numbered(row);
2027 // if there is an argument, find the corresponding label, else
2028 // check whether there is at least one label.
2029 for (row_type row = 0; row != nrows(); ++row) {
2030 if (numbered(row) && label_[row] &&
2031 (cmd.argument().empty() || label(row) == cmd.argument())) {
2037 status.setEnabled(enabled);
2041 case LFUN_INSET_INSERT:
2042 if (cmd.getArg(0) == "label") {
2043 status.setEnabled(type_ != hullSimple);
2046 return InsetMathGrid::getStatus(cur, cmd, status);
2048 case LFUN_TABULAR_FEATURE: {
2049 if (!allowsTabularFeatures())
2051 string s = cmd.getArg(0);
2053 && (s == "append-row"
2054 || s == "delete-row"
2055 || s == "copy-row")) {
2056 status.message(bformat(
2057 from_utf8(N_("Can't change number of rows in '%1$s'")),
2059 status.setEnabled(false);
2063 && (s == "append-column"
2064 || s == "delete-column"
2065 || s == "copy-column")) {
2066 status.message(bformat(
2067 from_utf8(N_("Can't change number of columns in '%1$s'")),
2069 status.setEnabled(false);
2072 if (s == "add-vline-left" || s == "add-vline-right") {
2073 status.message(bformat(
2074 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2076 status.setEnabled(false);
2079 if (s == "valign-top" || s == "valign-middle"
2080 || s == "valign-bottom" || s == "align-left"
2081 || s == "align-center" || s == "align-right") {
2082 status.setEnabled(false);
2085 return InsetMathGrid::getStatus(cur, cmd, status);
2089 return InsetMathGrid::getStatus(cur, cmd, status);
2092 // This cannot really happen, but inserted to shut-up gcc
2093 return InsetMathGrid::getStatus(cur, cmd, status);
2097 /////////////////////////////////////////////////////////////////////
2101 // simply scrap this function if you want
2102 void InsetMathHull::mutateToText()
2105 // translate to latex
2107 latex(os, false, false);
2108 string str = os.str();
2111 Text * lt = view_->cursor().innerText();
2112 string::const_iterator cit = str.begin();
2113 string::const_iterator end = str.end();
2114 for (; cit != end; ++cit)
2115 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2118 //dispatch(LFUN_ESCAPE);
2123 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2124 docstring const & font)
2126 // this whole function is a hack and won't work for incremental font
2129 if (cur.inset().asInsetMath()->name() == font)
2130 cur.handleFont(to_utf8(font));
2132 cur.handleNest(createInsetMath(font, cur.buffer()));
2138 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2143 font.fromString(to_utf8(arg), b);
2144 if (font.fontInfo().color() != Color_inherit) {
2145 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2146 cur.handleNest(at, 0);
2151 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2154 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
2155 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
2156 enter_front ? idxFirst(cur) : idxLast(cur);
2157 // The inset formula dimension is not necessarily the same as the
2158 // one of the instant preview image, so we have to indicate to the
2159 // BufferView that a metrics update is needed.
2160 cur.screenUpdateFlags(Update::Force);
2164 void InsetMathHull::revealCodes(Cursor & cur) const
2166 if (!cur.inMathed())
2168 odocstringstream os;
2170 cur.message(os.str());
2172 // write something to the minibuffer
2173 // translate to latex
2177 string str = os.str();
2179 string::size_type pos = 0;
2181 for (string::iterator it = str.begin(); it != str.end(); ++it) {
2184 else if (*it == '\0') {
2186 pos = it - str.begin();
2192 res = res.substr(pos - 30);
2193 if (res.size() > 60)
2194 res = res.substr(0, 60);
2200 /////////////////////////////////////////////////////////////////////
2204 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2207 // FIXME: completely broken
2208 static InsetMathHull * lastformula = 0;
2209 static CursorBase current = DocIterator(ibegin(nucleus()));
2211 static string laststr;
2213 if (lastformula != this || laststr != str) {
2214 //lyxerr << "reset lastformula to " << this << endl;
2217 current = ibegin(nucleus());
2219 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2223 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2225 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2226 CursorSlice & top = it.back();
2227 MathData const & a = top.asInsetMath()->cell(top.idx_);
2228 if (a.matchpart(ar, top.pos_)) {
2229 bv->cursor().setSelection(it, ar.size());
2231 top.pos_ += ar.size();
2237 //lyxerr << "not found!" << endl;
2244 void InsetMathHull::write(ostream & os) const
2246 odocstringstream oss;
2247 otexrowstream ots(oss);
2248 WriteStream wi(ots, false, false, WriteStream::wsDefault);
2251 os << to_utf8(oss.str());
2255 void InsetMathHull::read(Lexer & lex)
2258 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2259 operator=(*at->asHullInset());
2263 bool InsetMathHull::readQuiet(Lexer & lex)
2266 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2268 operator=(*at->asHullInset());
2273 int InsetMathHull::plaintext(odocstringstream & os,
2274 OutputParams const & op, size_t max_length) const
2276 // disables ASCII-art for export of equations. See #2275.
2277 if (0 && display()) {
2281 TextPainter tpain(dim.width(), dim.height());
2282 drawT(tpain, 0, dim.ascent());
2284 // reset metrics cache to "real" values
2286 return tpain.textheight();
2289 odocstringstream oss;
2290 otexrowstream ots(oss);
2291 Encoding const * const enc = encodings.fromLyXName("utf8");
2292 WriteStream wi(ots, false, true, WriteStream::wsDefault, enc);
2295 if (type_ == hullRegexp)
2298 for (row_type r = 0; r < nrows(); ++r) {
2299 for (col_type c = 0; c < ncols(); ++c)
2300 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2301 // if it's for the TOC, we write just the first line
2302 // and do not include the newline.
2303 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2305 if (r < nrows() - 1)
2309 docstring const str = oss.str();
2315 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
2320 if (getType() == hullSimple)
2321 name = from_ascii("inlineequation");
2323 name = from_ascii("informalequation");
2325 docstring bname = name;
2326 if (!label(0).empty())
2327 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
2329 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
2331 odocstringstream ls;
2333 if (runparams.flavor == OutputParams::XML) {
2334 ms << MTag("alt role='tex' ");
2335 // Workaround for db2latex: db2latex always includes equations with
2336 // \ensuremath{} or \begin{display}\end{display}
2337 // so we strip LyX' math environment
2338 WriteStream wi(ols, false, false, WriteStream::wsDefault, runparams.encoding);
2339 InsetMathGrid::write(wi);
2340 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2345 InsetMathGrid::mathmlize(ms);
2348 ms << MTag("alt role='tex'");
2349 latex(ols, runparams);
2350 res = ols.texrow().rows();
2351 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2355 ms << from_ascii("<graphic fileref=\"eqn/");
2356 if (!label(0).empty())
2357 ms << sgml::cleanID(buffer(), runparams, label(0));
2359 ms << sgml::uniqueID(from_ascii("anon"));
2361 if (runparams.flavor == OutputParams::XML)
2362 ms << from_ascii("\"/>");
2364 ms << from_ascii("\">");
2366 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2368 return ms.line() + res;
2372 bool InsetMathHull::haveNumbers() const
2374 bool havenumbers = false;
2375 // inline formulas are never numbered (bug 7351 part 3)
2376 if (getType() == hullSimple)
2378 for (size_t i = 0; i != numbered_.size(); ++i) {
2389 // We need to do something about alignment here.
2391 // This duplicates code from InsetMathGrid, but
2392 // we need access here to number information,
2393 // and we simply do not have that in InsetMathGrid.
2394 void InsetMathHull::htmlize(HtmlStream & os) const
2396 bool const havenumbers = haveNumbers();
2397 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2400 os << cell(index(0, 0));
2404 os << MTag("table", "class='mathtable'");
2405 for (row_type row = 0; row < nrows(); ++row) {
2407 for (col_type col = 0; col < ncols(); ++col) {
2409 os << cell(index(row, col));
2414 docstring const & num = numbers_[row];
2416 os << '(' << num << ')';
2421 os << ETag("table");
2425 // this duplicates code from InsetMathGrid, but
2426 // we need access here to number information,
2427 // and we simply do not have that in InsetMathGrid.
2428 void InsetMathHull::mathmlize(MathStream & os) const
2430 bool const havenumbers = haveNumbers();
2431 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2434 os << MTag("mtable");
2435 char const * const celltag = havetable ? "mtd" : "mrow";
2436 // FIXME There does not seem to be wide support at the moment
2437 // for mlabeledtr, so we have to use just mtr for now.
2438 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2439 char const * const rowtag = "mtr";
2440 for (row_type row = 0; row < nrows(); ++row) {
2443 for (col_type col = 0; col < ncols(); ++col) {
2445 << cell(index(row, col))
2451 docstring const & num = numbers_[row];
2453 os << '(' << num << ')';
2460 os << ETag("mtable");
2464 void InsetMathHull::mathAsLatex(WriteStream & os) const
2466 MathEnsurer ensurer(os, false);
2467 bool havenumbers = haveNumbers();
2468 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2471 os << cell(index(0, 0));
2475 os << "<table class='mathtable'>";
2476 for (row_type row = 0; row < nrows(); ++row) {
2478 for (col_type col = 0; col < ncols(); ++col) {
2479 os << "<td class='math'>";
2480 os << cell(index(row, col));
2485 docstring const & num = numbers_[row];
2487 os << '(' << num << ')';
2496 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2498 BufferParams::MathOutput const mathtype =
2499 buffer().masterBuffer()->params().html_math_output;
2501 bool success = false;
2503 // we output all the labels just at the beginning of the equation.
2504 // this should be fine.
2505 for (size_t i = 0; i != label_.size(); ++i) {
2506 InsetLabel const * const il = label_[i];
2512 // FIXME Eventually we would like to do this inset by inset.
2513 if (mathtype == BufferParams::MathML) {
2514 odocstringstream os;
2519 } catch (MathExportException const &) {}
2521 if (getType() == hullSimple)
2522 xs << html::StartTag("math",
2523 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2525 xs << html::StartTag("math",
2526 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2527 xs << XHTMLStream::ESCAPE_NONE
2529 << html::EndTag("math");
2531 } else if (mathtype == BufferParams::HTML) {
2532 odocstringstream os;
2537 } catch (MathExportException const &) {}
2539 string const tag = (getType() == hullSimple) ? "span" : "div";
2540 xs << html::StartTag(tag, "class='formula'", true)
2541 << XHTMLStream::ESCAPE_NONE
2543 << html::EndTag(tag);
2547 // what we actually want is this:
2549 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2551 // || mathtype == BufferParams::Images
2553 // but what follows is equivalent, since we'll enter only if either (a) we
2554 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2555 // aren't doing LaTeX.
2557 // so this is for Images.
2558 if (!success && mathtype != BufferParams::LaTeX) {
2559 graphics::PreviewImage const * pimage = 0;
2561 loadPreview(docit_);
2562 pimage = preview_->getPreviewImage(buffer());
2563 // FIXME Do we always have png?
2566 if (pimage || op.dryrun) {
2567 string const filename = pimage ? pimage->filename().onlyFileName()
2568 : "previewimage.png";
2570 // if we are not in the master buffer, then we need to see that the
2571 // generated image is copied there; otherwise, preview fails.
2572 Buffer const * mbuf = buffer().masterBuffer();
2573 if (mbuf != &buffer()) {
2574 string mbtmp = mbuf->temppath();
2575 FileName const mbufimg(support::addName(mbtmp, filename));
2576 pimage->filename().copyTo(mbufimg);
2578 // add the file to the list of files to be exported
2579 op.exportdata->addExternalFile("xhtml", pimage->filename());
2582 string const tag = (getType() == hullSimple) ? "span" : "div";
2584 << html::StartTag(tag, "style = \"text-align: center;\"")
2585 << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2586 << html::EndTag(tag)
2592 // so we'll pass this test if we've failed everything else, or
2593 // if mathtype was LaTeX, since we won't have entered any of the
2595 if (!success /* || mathtype != BufferParams::LaTeX */) {
2596 // Unfortunately, we cannot use latexString() because we do not want
2597 // $...$ or whatever.
2598 odocstringstream ls;
2599 otexrowstream ots(ls);
2600 WriteStream wi(ots, false, true, WriteStream::wsPreview);
2601 ModeSpecifier specifier(wi, MATH_MODE);
2603 docstring const latex = ls.str();
2605 // class='math' allows for use of jsMath
2606 // http://www.math.union.edu/~dpvc/jsMath/
2608 // probably should allow for some kind of customization here
2609 string const tag = (getType() == hullSimple) ? "span" : "div";
2610 xs << html::StartTag(tag, "class='math'")
2612 << html::EndTag(tag)
2619 void InsetMathHull::toString(odocstream & os) const
2621 odocstringstream ods;
2622 plaintext(ods, OutputParams(0));
2627 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2629 odocstringstream ods;
2632 // FIXME: this results in spilling TeX into the LyXHTML output since the
2633 // outliner is used to generate the LyXHTML list of figures/etc.
2639 string InsetMathHull::contextMenuName() const
2641 return "context-math";
2645 void InsetMathHull::recordLocation(DocIterator const & di)
2651 bool InsetMathHull::canPaintChange(BufferView const &) const
2653 // We let RowPainter do it seamlessly for inline insets
2654 return display() != Inline;