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 // writes a preamble for underlined or struck out math display
125 void writeMathdisplayPreamble(WriteStream & os)
127 if (os.strikeoutMath()) {
128 if (os.ulemCmd() == WriteStream::UNDERLINE)
129 os << "\\raisebox{-\\belowdisplayshortskip}{"
130 "\\lyxmathsout{\\parbox[b]{\\columnwidth}{";
132 os << "\\lyxmathsout{\\parbox{\\columnwidth}{";
133 } else if (os.ulemCmd() == WriteStream::UNDERLINE)
134 os << "\\raisebox{-\\belowdisplayshortskip}{"
135 "\\parbox[b]{\\columnwidth}{";
136 else if (os.ulemCmd() == WriteStream::STRIKEOUT)
137 os << "\\parbox{\\columnwidth}{";
141 // writes a postamble for underlined or struck out math display
142 void writeMathdisplayPostamble(WriteStream & os)
144 if (os.strikeoutMath()) {
145 if (os.ulemCmd() == WriteStream::UNDERLINE)
148 } else if (os.ulemCmd() == WriteStream::UNDERLINE)
150 else if (os.ulemCmd() == WriteStream::STRIKEOUT)
155 } // end anon namespace
158 HullType hullType(docstring const & s)
160 if (s == "none") return hullNone;
161 if (s == "simple") return hullSimple;
162 if (s == "equation") return hullEquation;
163 if (s == "eqnarray") return hullEqnArray;
164 if (s == "align") return hullAlign;
165 if (s == "alignat") return hullAlignAt;
166 if (s == "xalignat") return hullXAlignAt;
167 if (s == "xxalignat") return hullXXAlignAt;
168 if (s == "multline") return hullMultline;
169 if (s == "gather") return hullGather;
170 if (s == "flalign") return hullFlAlign;
171 if (s == "regexp") return hullRegexp;
172 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
177 docstring hullName(HullType type)
180 case hullNone: return from_ascii("none");
181 case hullSimple: return from_ascii("simple");
182 case hullEquation: return from_ascii("equation");
183 case hullEqnArray: return from_ascii("eqnarray");
184 case hullAlign: return from_ascii("align");
185 case hullAlignAt: return from_ascii("alignat");
186 case hullXAlignAt: return from_ascii("xalignat");
187 case hullXXAlignAt: return from_ascii("xxalignat");
188 case hullMultline: return from_ascii("multline");
189 case hullGather: return from_ascii("gather");
190 case hullFlAlign: return from_ascii("flalign");
191 case hullRegexp: return from_ascii("regexp");
193 lyxerr << "unknown hull type" << endl;
196 return from_ascii("none");
199 static InsetLabel * dummy_pointer = 0;
201 InsetMathHull::InsetMathHull(Buffer * buf)
202 : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, NUMBER),
203 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
204 preview_(new RenderPreview(this))
206 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
207 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
208 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
209 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
216 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
217 : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, NUMBER),
218 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
219 preview_(new RenderPreview(this))
227 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
233 InsetMathHull::~InsetMathHull()
235 for (size_t i = 0; i < label_.size(); ++i)
240 Inset * InsetMathHull::clone() const
242 return new InsetMathHull(*this);
246 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
250 InsetMathGrid::operator=(other);
252 numbered_ = other.numbered_;
253 numbers_ = other.numbers_;
254 buffer_ = other.buffer_;
255 for (size_t i = 0; i < label_.size(); ++i)
257 label_ = other.label_;
258 for (size_t i = 0; i != label_.size(); ++i) {
260 label_[i] = new InsetLabel(*label_[i]);
262 preview_.reset(new RenderPreview(*other.preview_, this));
268 void InsetMathHull::setBuffer(Buffer & buffer)
270 InsetMathGrid::setBuffer(buffer);
272 for (size_t i = 0; i != label_.size(); ++i) {
274 label_[i]->setBuffer(buffer);
279 // FIXME This should really be controlled by the TOC level, or
280 // something of the sort.
282 const char * counters_to_save[] = {"section", "chapter"};
283 unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
287 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
290 //FIXME: buffer_ should be set at creation for this inset! Problem is
291 // This inset is created at too many places (see Parser::parse1() in
296 // if any of the equations are numbered, then we want to save the values
297 // of some of the counters.
299 BufferParams const & bp = buffer_->params();
300 string const & lang = it->getParLanguage(bp)->code();
302 buffer_->masterBuffer()->params().documentClass().counters();
304 // right now, we only need to do this at export time
305 if (utype == OutputUpdate) {
306 for (size_t i = 0; i < numcnts; ++i) {
307 docstring const cnt = from_ascii(counters_to_save[i]);
308 if (cnts.hasCounter(cnt))
309 counter_map[cnt] = cnts.value(cnt);
313 // this has to be done separately
314 docstring const eqstr = from_ascii("equation");
315 if (cnts.hasCounter(eqstr)) {
316 if (utype == OutputUpdate)
317 counter_map[eqstr] = cnts.value(eqstr);
318 for (size_t i = 0; i != label_.size(); ++i) {
320 cnts.step(eqstr, utype);
321 numbers_[i] = cnts.theCounter(eqstr, lang);
323 numbers_[i] = empty_docstring();
329 for (size_t i = 0; i != label_.size(); ++i) {
331 label_[i]->updateBuffer(it, utype);
334 InsetMathGrid::updateBuffer(it, utype);
338 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active,
339 UpdateType utype) const
342 //FIXME: buffer_ should be set at creation for this inset! Problem is
343 // This inset is created at too many places (see Parser::parse1() in
348 shared_ptr<Toc> toc = buffer().tocBackend().toc("equation");
350 for (row_type row = 0; row != nrows(); ++row) {
354 label_[row]->addToToc(pit, output_active, utype);
355 toc->push_back(TocItem(pit, 0, nicelabel(row), output_active));
360 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
362 if (previewState(&cur.bv())) {
366 return InsetMathNest::editXY(cur, x, y);
370 InsetMath::mode_type InsetMathHull::currentMode() const
374 return UNDECIDED_MODE;
376 // definitely math mode ...
396 bool InsetMathHull::idxFirst(Cursor & cur) const
404 bool InsetMathHull::idxLast(Cursor & cur) const
406 cur.idx() = nargs() - 1;
407 cur.pos() = cur.lastpos();
412 // FIXME: InsetMathGrid should be changed to let the real column alignment be
413 // given by a virtual method like displayColAlign, because the values produced
414 // by defaultColAlign can be invalidated by lfuns such as add-column. For the
415 // moment the values produced by defaultColAlign are not used, notably because
416 // alignment is not implemented in the LyXHTML output.
417 char InsetMathHull::defaultColAlign(col_type col)
419 return colAlign(type_, col);
423 char InsetMathHull::displayColAlign(idx_type idx) const
427 row_type const r = row(idx);
430 if (r == nrows() - 1)
441 return colAlign(type_, col(idx));
445 return InsetMathGrid::displayColAlign(idx);
449 int InsetMathHull::displayColSpace(col_type col) const
451 return colSpace(type_, col);
455 // FIXME: same comment as for defaultColAlign applies.
456 int InsetMathHull::defaultColSpace(col_type col)
458 return colSpace(type_, col);
462 string InsetMathHull::standardFont() const
468 return "lyxnochange";
475 ColorCode InsetMathHull::standardColor() const
480 return Color_foreground;
488 bool InsetMathHull::previewState(const BufferView *const bv) const
490 if (!editing(bv) && RenderPreview::previewMath()
491 && type_ != hullRegexp)
493 graphics::PreviewImage const * pimage =
494 preview_->getPreviewImage(bv->buffer());
495 return pimage && pimage->image();
502 static const int ERROR_FRAME_WIDTH = 2;
505 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
507 if (previewState(mi.base.bv)) {
508 preview_->metrics(mi, dim);
509 if (previewTooSmall(dim)) {
510 // preview image is too small
511 dim.wid += 2 * ERROR_FRAME_WIDTH;
512 dim.asc += 2 * ERROR_FRAME_WIDTH;
514 // insert a one pixel gap in front of the formula
517 dim.des += displayMargin();
519 // Cache the inset dimension.
520 setDimCache(mi, dim);
524 // FIXME: Changing the same object repeatedly is inefficient.
525 Changer dummy1 = mi.base.changeFontSet(standardFont());
526 Changer dummy2 = mi.base.changeStyle(display() ? LM_ST_DISPLAY : LM_ST_TEXT);
528 // let the cells adjust themselves
529 InsetMathGrid::metrics(mi, dim);
532 dim.asc += displayMargin();
533 dim.des += displayMargin();
536 if (numberedType()) {
537 Changer dummy = mi.base.changeFontSet("mathbf");
539 for (row_type row = 0; row < nrows(); ++row)
540 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
546 if (type_ == hullRegexp)
548 // make it at least as high as the current font
551 math_font_max_dim(mi.base.font, asc, des);
552 dim.asc = max(dim.asc, asc);
553 dim.des = max(dim.des, des);
554 // Cache the inset dimension.
555 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
556 setDimCache(mi, dim);
560 bool InsetMathHull::previewTooSmall(Dimension const & dim) const
562 return dim.width() <= 10 && dim.height() <= 10;
566 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
568 BufferView const * const bv = pi.base.bv;
569 if (previewState(bv)) {
570 Dimension const dim = dimension(*pi.base.bv);
571 if (previewTooSmall(dim))
573 return graphics::PreviewLoader::backgroundColor();
579 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
581 Dimension const dim = dimension(*pi.base.bv);
582 if (previewTooSmall(dim)) {
583 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
584 dim.wid, dim.asc + dim.des, backgroundColor(pi));
587 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
588 dim.asc + dim.des - 1, pi.backgroundColor(this));
592 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
594 BufferView const * const bv = pi.base.bv;
595 Dimension const dim = dimension(*bv);
597 if (type_ == hullRegexp)
598 pi.pain.rectangle(x + 2, y - dim.ascent() + 1,
599 dim.width() - 3, dim.height() - 2, Color_regexpframe);
601 if (previewState(bv)) {
602 // Do not draw change tracking cue if taken care of by RowPainter
604 Changer dummy = make_change(pi.change_, Change(), !canPaintChange(*bv));
605 if (previewTooSmall(dim)) {
606 // we have an extra frame
607 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
609 // one pixel gap in front
610 preview_->draw(pi, x + 1, y);
612 setPosCache(pi, x, y);
616 ColorCode color = pi.selected && lyxrc.use_system_colors
617 ? Color_selectiontext : standardColor();
618 bool const really_change_color = pi.base.font.color() == Color_none;
619 Changer dummy0 = pi.base.font.changeColor(color, really_change_color);
620 Changer dummy1 = pi.base.changeFontSet(standardFont());
621 Changer dummy2 = pi.base.changeStyle(display() ? LM_ST_DISPLAY : LM_ST_TEXT);
623 InsetMathGrid::draw(pi, x + 1, y);
625 if (numberedType()) {
626 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
627 for (row_type row = 0; row < nrows(); ++row) {
628 int const yy = y + rowinfo_[row].offset_;
629 Changer dummy = pi.base.changeFontSet("mathrm");
630 docstring const nl = nicelabel(row);
634 // drawing change line
635 if (canPaintChange(*bv))
636 pi.change_.paintCue(pi, x + 1, y + 1 - dim.asc,
637 x + dim.wid, y + dim.des);
638 setPosCache(pi, x, y);
642 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
645 InsetMathGrid::metricsT(mi, dim);
648 otexrowstream ots(os);
649 WriteStream wi(ots, false, true, WriteStream::wsDefault);
651 dim.wid = os.str().size();
658 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
661 InsetMathGrid::drawT(pain, x, y);
664 otexrowstream ots(os);
665 WriteStream wi(ots, false, true, WriteStream::wsDefault);
667 pain.draw(x, y, os.str().c_str());
672 static docstring latexString(InsetMathHull const & inset)
675 // This has to be static, because a preview snippet or a math
676 // macro containing math in text mode (such as $\text{$\phi$}$ or
677 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
678 // first time as a whole, and the second time only the inner math.
679 // In this last case inset.buffer() would be invalid.
680 static Encoding const * encoding = 0;
681 if (inset.isBufferValid())
682 encoding = &(inset.buffer().params().encoding());
683 otexrowstream ots(ls);
684 WriteStream wi(ots, false, true, WriteStream::wsPreview, encoding);
690 void InsetMathHull::initUnicodeMath() const
692 // Trigger classification of the unicode symbols in this inset
693 docstring const dummy = latexString(*this);
697 void InsetMathHull::addPreview(DocIterator const & inset_pos,
698 graphics::PreviewLoader & /*ploader*/) const
700 if (RenderPreview::previewMath()) {
701 preparePreview(inset_pos);
706 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
707 MacroNameSet & macros, MacroNameSet & defs) const
709 MacroNameSet::iterator const end = macros.end();
711 for (size_t i = 0; i < md.size(); ++i) {
712 MathMacro const * mi = md[i].nucleus()->asMacro();
713 MathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
714 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
715 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
716 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
717 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
719 // Look for macros in the arguments of this macro.
720 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
721 usedMacros(mi->cell(idx), pos, macros, defs);
722 // Make sure this is a macro defined in the document
723 // (as we also spot the macros in the symbols file)
724 // or that we have not already accounted for it.
725 docstring const name = mi->name();
726 if (macros.find(name) == end)
729 // Look for macros in the definition of this macro.
730 MathData ar(pos.buffer());
731 MacroData const * data =
732 pos.buffer()->getMacro(name, pos, true);
734 odocstringstream macro_def;
735 data->write(macro_def, true);
737 defs.insert(macro_def.str());
738 asArray(data->definition(), ar);
740 usedMacros(ar, pos, macros, defs);
742 MathData ar(pos.buffer());
743 asArray(mt->definition(), ar);
744 usedMacros(ar, pos, macros, defs);
746 if (!si->nuc().empty())
747 usedMacros(si->nuc(), pos, macros, defs);
749 usedMacros(si->down(), pos, macros, defs);
751 usedMacros(si->up(), pos, macros, defs);
752 } else if (fi || gi) {
753 idx_type nidx = fi ? fi->nargs() : gi->nargs();
754 for (idx_type idx = 0; idx < nidx; ++idx)
755 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
758 usedMacros(ni->cell(0), pos, macros, defs);
764 void InsetMathHull::preparePreview(DocIterator const & pos,
765 bool forexport) const
767 // there is no need to do all the macro stuff if we're not
768 // actually going to generate the preview.
769 if (!RenderPreview::previewMath() && !forexport)
772 Buffer const * buffer = pos.buffer();
774 // collect macros at this position
776 buffer->listMacroNames(macros);
778 // collect definitions only for the macros used in this inset
780 for (idx_type idx = 0; idx < nargs(); ++idx)
781 usedMacros(cell(idx), pos, macros, defs);
783 MacroNameSet::iterator it = defs.begin();
784 MacroNameSet::iterator end = defs.end();
785 docstring macro_preamble;
786 for (; it != end; ++it)
787 macro_preamble.append(*it);
789 // set the font series and size for this snippet
790 DocIterator dit = pos.getInnerText();
791 Paragraph const & par = dit.paragraph();
792 Font font = par.getFontSettings(buffer->params(), dit.pos());
793 font.fontInfo().realize(par.layout().font);
794 string const lsize = font.latexSize();
797 if (font.fontInfo().series() == BOLD_SERIES) {
798 setfont += from_ascii("\\textbf{");
801 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
802 setfont += from_ascii("\\" + lsize + '\n');
805 if (forexport && haveNumbers()) {
806 docstring eqstr = from_ascii("equation");
807 CounterMap::const_iterator it = counter_map.find(eqstr);
808 if (it != counter_map.end()) {
809 int num = it->second;
811 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
812 '{' + convert<docstring>(num) + '}' + '\n';
814 for (size_t i = 0; i != numcnts; ++i) {
815 docstring cnt = from_ascii(counters_to_save[i]);
816 it = counter_map.find(cnt);
817 if (it == counter_map.end())
819 int num = it->second;
821 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
822 '{' + convert<docstring>(num) + '}';
825 docstring const snippet = macro_preamble + setfont + setcnt
826 + latexString(*this) + endfont;
827 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
828 preview_->addPreview(snippet, *buffer, forexport);
832 void InsetMathHull::reloadPreview(DocIterator const & pos) const
835 preview_->startLoading(*pos.buffer());
839 void InsetMathHull::loadPreview(DocIterator const & pos) const
841 bool const forexport = true;
842 preparePreview(pos, forexport);
843 preview_->startLoading(*pos.buffer(), forexport);
847 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
849 if (RenderPreview::previewMath()) {
851 cur.screenUpdateFlags(Update::Force);
857 docstring InsetMathHull::label(row_type row) const
859 LASSERT(row < nrows(), return docstring());
860 if (InsetLabel * il = label_[row])
861 return il->screenLabel();
866 void InsetMathHull::label(row_type row, docstring const & label)
868 //lyxerr << "setting label '" << label << "' for row " << row << endl;
872 label_[row] = dummy_pointer;
875 label_[row]->updateLabelAndRefs(label);
877 label_[row]->setParam("name", label);
881 InsetCommandParams p(LABEL_CODE);
883 label_[row] = new InsetLabel(buffer_, p);
885 label_[row]->setBuffer(buffer());
889 void InsetMathHull::numbered(row_type row, Numbered num)
891 numbered_[row] = num;
892 if (!numbered(row) && label_[row]) {
899 bool InsetMathHull::numbered(row_type row) const
901 return numbered_[row] == NUMBER;
905 bool InsetMathHull::ams() const
925 for (size_t row = 0; row < numbered_.size(); ++row)
926 if (numbered_[row] == NOTAG)
932 bool InsetMathHull::outerDisplay() const
955 Inset::DisplayType InsetMathHull::display() const
978 bool InsetMathHull::numberedType() const
997 for (row_type row = 0; row < nrows(); ++row)
1004 void InsetMathHull::validate(LaTeXFeatures & features) const
1006 if (features.runparams().isLaTeX()) {
1008 features.require("amsmath");
1010 if (type_ == hullRegexp) {
1011 features.require("color");
1012 docstring frcol = from_utf8(lcolor.getLaTeXName(Color_regexpframe));
1013 docstring bgcol = from_ascii("white");
1014 features.addPreambleSnippet(
1015 "\\newcommand{\\regexp}[1]{\\fcolorbox{"
1017 + bgcol + "}{\\ensuremath{\\mathtt{#1}}}}");
1018 features.addPreambleSnippet(
1019 from_ascii("\\newcommand{\\endregexp}{}"));
1020 } else if (outerDisplay() && features.inDeletedInset()
1021 && !features.mustProvide("ct-dvipost")) {
1022 features.require("ct-tikz-math-sout");
1025 // Validation is necessary only if not using AMS math.
1026 // To be safe, we will always run mathedvalidate.
1027 //if (features.amsstyle)
1030 //features.binom = true;
1031 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
1032 // it would be better to do this elsewhere, but we can't validate in
1033 // InsetMathMatrix and we have no way, outside MathExtern, to know if
1034 // we even have any matrices.
1035 features.addCSSSnippet(
1036 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
1037 "table.matrix td{padding: 0.25px;}\n"
1038 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
1039 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
1041 InsetMathGrid::validate(features);
1045 void InsetMathHull::header_write(WriteStream & os) const
1047 bool n = numberedType();
1058 if (cell(0).empty())
1063 writeMathdisplayPreamble(os);
1067 os << "\\begin{equation" << star(n) << "}\n";
1077 writeMathdisplayPreamble(os);
1080 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1087 os << "\\begin{" << hullName(type_) << star(n) << '}'
1088 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1094 os << "\\begin{" << hullName(type_) << '}'
1095 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1105 os << "\\begin{unknown" << star(n) << "}\n";
1111 void InsetMathHull::footer_write(WriteStream & os) const
1113 bool n = numberedType();
1130 os << "\\end{equation" << star(n) << "}\n";
1133 writeMathdisplayPostamble(os);
1143 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1144 writeMathdisplayPostamble(os);
1151 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1157 os << "\\end{" << hullName(type_) << "}\n";
1161 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1162 os << "\\endregexp{}}";
1168 os << "\\end{unknown" << star(n) << "}\n";
1174 bool InsetMathHull::allowsTabularFeatures() const
1197 bool InsetMathHull::rowChangeOK() const
1200 type_ == hullEqnArray || type_ == hullAlign ||
1201 type_ == hullFlAlign || type_ == hullAlignAt ||
1202 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1203 type_ == hullGather || type_ == hullMultline;
1207 bool InsetMathHull::colChangeOK() const
1210 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1211 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1215 void InsetMathHull::addRow(row_type row)
1220 bool numbered = numberedType();
1221 // Move the number and raw pointer, do not call label() (bug 7511)
1222 InsetLabel * label = dummy_pointer;
1223 docstring number = empty_docstring();
1224 if (type_ == hullMultline) {
1225 if (row + 1 == nrows()) {
1226 numbered_[row] = NONUMBER;
1227 swap(label, label_[row]);
1228 swap(number, numbers_[row]);
1233 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1234 numbers_.insert(numbers_.begin() + row + 1, number);
1235 label_.insert(label_.begin() + row + 1, label);
1236 InsetMathGrid::addRow(row);
1240 void InsetMathHull::swapRow(row_type row)
1244 if (row + 1 == nrows())
1246 swap(numbered_[row], numbered_[row + 1]);
1247 swap(numbers_[row], numbers_[row + 1]);
1248 swap(label_[row], label_[row + 1]);
1249 InsetMathGrid::swapRow(row);
1253 void InsetMathHull::delRow(row_type row)
1255 if (nrows() <= 1 || !rowChangeOK())
1257 if (row + 1 == nrows() && type_ == hullMultline) {
1258 swap(numbered_[row - 1], numbered_[row]);
1259 swap(numbers_[row - 1], numbers_[row]);
1260 swap(label_[row - 1], label_[row]);
1261 InsetMathGrid::delRow(row);
1264 InsetMathGrid::delRow(row);
1265 // The last dummy row has no number info nor a label.
1266 // Test nrows() + 1 because we have already erased the row.
1267 if (row == nrows() + 1)
1269 numbered_.erase(numbered_.begin() + row);
1270 numbers_.erase(numbers_.begin() + row);
1272 label_.erase(label_.begin() + row);
1276 void InsetMathHull::addCol(col_type col)
1280 InsetMathGrid::addCol(col);
1284 void InsetMathHull::delCol(col_type col)
1286 if (ncols() <= 1 || !colChangeOK())
1288 InsetMathGrid::delCol(col);
1292 docstring InsetMathHull::nicelabel(row_type row) const
1296 docstring const & val = numbers_[row];
1298 return '(' + val + ')';
1299 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1303 void InsetMathHull::glueall(HullType type)
1306 for (idx_type i = 0; i < nargs(); ++i)
1308 InsetLabel * label = 0;
1309 if (type == hullEquation) {
1310 // preserve first non-empty label
1311 for (row_type row = 0; row < nrows(); ++row) {
1313 label = label_[row];
1319 *this = InsetMathHull(buffer_, hullSimple);
1326 void InsetMathHull::splitTo2Cols()
1328 LASSERT(ncols() == 1, return);
1329 InsetMathGrid::addCol(1);
1330 for (row_type row = 0; row < nrows(); ++row) {
1331 idx_type const i = 2 * row;
1332 pos_type pos = firstRelOp(cell(i));
1333 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1334 cell(i).erase(pos, cell(i).size());
1339 void InsetMathHull::splitTo3Cols()
1341 LASSERT(ncols() < 3, return);
1344 InsetMathGrid::addCol(2);
1345 for (row_type row = 0; row < nrows(); ++row) {
1346 idx_type const i = 3 * row + 1;
1347 if (!cell(i).empty()) {
1348 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1349 cell(i).erase(1, cell(i).size());
1355 void InsetMathHull::changeCols(col_type cols)
1357 if (ncols() == cols)
1359 else if (ncols() < cols) {
1365 while (ncols() < cols)
1366 InsetMathGrid::addCol(ncols());
1372 for (row_type row = 0; row < nrows(); ++row) {
1373 idx_type const i = row * ncols();
1374 for (col_type col = cols; col < ncols(); ++col) {
1375 cell(i + cols - 1).append(cell(i + col));
1379 while (ncols() > cols) {
1380 InsetMathGrid::delCol(ncols() - 1);
1385 HullType InsetMathHull::getType() const
1391 void InsetMathHull::setType(HullType type)
1398 bool InsetMathHull::isMutable(HullType type)
1422 void InsetMathHull::mutate(HullType newtype)
1424 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1426 if (newtype == type_)
1429 // This guards the algorithm below it, which is designed with certain types
1431 if (!isMutable(newtype) || !isMutable(type_)) {
1432 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1433 << "' to '" << to_utf8(hullName(newtype))
1434 << "' not implemented" << endl;
1438 // we try to move along the chain
1439 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1441 // +-------------------------------------+
1442 // we use eqnarray as intermediate type for mutations that are not
1443 // directly supported because it handles labels and numbering for
1448 setType(hullSimple);
1454 if (newtype == hullNone) {
1458 setType(hullEquation);
1459 numbered(0, label_[0] ? true : false);
1468 setType(hullSimple);
1473 // split it "nicely" on the first relop
1475 setType(hullEqnArray);
1483 // split it "nicely"
1518 setType(hullEqnArray);
1527 for (row_type row = 0; row < nrows(); ++row)
1528 numbered(row, false);
1538 for (row_type row = 0; row < nrows(); ++row)
1539 numbered(row, false);
1546 setType(hullEqnArray);
1576 for (row_type row = 0; row < nrows(); ++row)
1577 numbered(row, false);
1581 // first we mutate to EqnArray
1583 setType(hullEqnArray);
1590 // we passed the guard so we should not be here
1591 LASSERT("Mutation not implemented, but should have been.", return);
1597 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1598 bool last_eoln) const
1601 if (numberedType()) {
1602 if (label_[row] && numbered(row)) {
1603 docstring const name =
1604 latex ? escape(label_[row]->getParam("name"))
1605 : label_[row]->getParam("name");
1606 res += "\\label{" + name + '}';
1608 if (type_ != hullMultline) {
1609 if (numbered_[row] == NONUMBER)
1610 res += "\\nonumber ";
1611 else if (numbered_[row] == NOTAG)
1615 // Never add \\ on the last empty line of eqnarray and friends
1617 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1620 void InsetMathHull::write(WriteStream & os) const
1622 ModeSpecifier specifier(os, MATH_MODE);
1624 InsetMathGrid::write(os);
1629 void InsetMathHull::normalize(NormalStream & os) const
1631 os << "[formula " << hullName(type_) << ' ';
1632 InsetMathGrid::normalize(os);
1637 void InsetMathHull::infoize(odocstream & os) const
1639 os << bformat(_("Type: %1$s"), hullName(type_));
1643 void InsetMathHull::check() const
1645 LATTEST(numbered_.size() == nrows());
1646 LATTEST(numbers_.size() == nrows());
1647 LATTEST(label_.size() == nrows());
1651 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1655 idocstringstream iss(func.argument());
1656 iss >> dlang >> extra;
1658 extra = from_ascii("noextra");
1659 string const lang = to_ascii(dlang);
1661 // replace selection with result of computation
1662 if (reduceSelectionToOneCell(cur)) {
1664 asArray(grabAndEraseSelection(cur), ar);
1665 lyxerr << "use selection: " << ar << endl;
1666 cur.insert(pipeThroughExtern(lang, extra, ar));
1670 // only inline, display or eqnarray math is allowed
1671 switch (getType()) {
1677 frontend::Alert::warning(_("Bad math environment"),
1678 _("Computation cannot be performed for AMS "
1679 "math environments.\nChange the math "
1680 "formula type and try again."));
1685 eq.push_back(MathAtom(new InsetMathChar('=')));
1687 // go to first item in line
1688 cur.idx() -= cur.idx() % ncols();
1691 if (getType() == hullSimple) {
1692 size_type pos = cur.cell().find_last(eq);
1694 if (pos == cur.cell().size()) {
1696 lyxerr << "use whole cell: " << ar << endl;
1698 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1699 lyxerr << "use partial cell form pos: " << pos << endl;
1701 cur.cell().append(eq);
1702 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1703 cur.pos() = cur.lastpos();
1707 if (getType() == hullEquation) {
1708 lyxerr << "use equation inset" << endl;
1709 mutate(hullEqnArray);
1710 MathData & ar = cur.cell();
1711 lyxerr << "use cell: " << ar << endl;
1715 cur.cell() = pipeThroughExtern(lang, extra, ar);
1716 // move to end of line
1717 cur.pos() = cur.lastpos();
1722 lyxerr << "use eqnarray" << endl;
1723 cur.idx() += 2 - cur.idx() % ncols();
1725 MathData ar = cur.cell();
1726 lyxerr << "use cell: " << ar << endl;
1727 // FIXME: temporarily disabled
1733 cur.cell() = pipeThroughExtern(lang, extra, ar);
1734 cur.pos() = cur.lastpos();
1739 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1741 //lyxerr << "action: " << cmd.action() << endl;
1742 switch (cmd.action()) {
1744 case LFUN_FINISHED_BACKWARD:
1745 case LFUN_FINISHED_FORWARD:
1746 case LFUN_FINISHED_RIGHT:
1747 case LFUN_FINISHED_LEFT:
1748 //lyxerr << "action: " << cmd.action() << endl;
1749 InsetMathGrid::doDispatch(cur, cmd);
1752 case LFUN_PARAGRAPH_BREAK:
1753 // just swallow this
1756 case LFUN_NEWLINE_INSERT:
1757 // some magic for the common case
1758 if (type_ == hullSimple || type_ == hullEquation) {
1759 cur.recordUndoInset();
1761 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1762 mutate(align ? hullAlign : hullEqnArray);
1763 // mutate() may change labels and such.
1764 cur.forceBufferUpdate();
1765 cur.idx() = nrows() * ncols() - 1;
1766 cur.pos() = cur.lastpos();
1768 InsetMathGrid::doDispatch(cur, cmd);
1771 case LFUN_MATH_NUMBER_TOGGLE: {
1772 //lyxerr << "toggling all numbers" << endl;
1773 cur.recordUndoInset();
1774 bool old = numberedType();
1775 if (type_ == hullMultline)
1776 numbered(nrows() - 1, !old);
1778 for (row_type row = 0; row < nrows(); ++row)
1779 numbered(row, !old);
1781 cur.message(old ? _("No number") : _("Number"));
1782 cur.forceBufferUpdate();
1786 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1787 cur.recordUndoInset();
1788 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1789 bool old = numbered(r);
1790 cur.message(old ? _("No number") : _("Number"));
1792 cur.forceBufferUpdate();
1796 case LFUN_LABEL_INSERT: {
1797 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1798 docstring old_label = label(r);
1799 docstring const default_label = from_ascii("eq:");
1800 if (old_label.empty())
1801 old_label = default_label;
1803 InsetCommandParams p(LABEL_CODE);
1804 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1805 string const data = InsetCommand::params2string(p);
1807 if (cmd.argument().empty())
1808 cur.bv().showDialog("label", data);
1810 FuncRequest fr(LFUN_INSET_INSERT, data);
1816 case LFUN_LABEL_COPY_AS_REFERENCE: {
1818 if (cmd.argument().empty() && &cur.inset() == this)
1819 // if there is no argument and we're inside math, we retrieve
1820 // the row number from the cursor position.
1821 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1823 // if there is an argument, find the corresponding label, else
1824 // check whether there is at least one label.
1825 for (row = 0; row != nrows(); ++row)
1826 if (numbered(row) && label_[row]
1827 && (cmd.argument().empty() || label(row) == cmd.argument()))
1834 InsetCommandParams p(REF_CODE, "ref");
1835 p["reference"] = label(row);
1836 cap::clearSelection();
1837 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1841 case LFUN_WORD_DELETE_FORWARD:
1842 case LFUN_CHAR_DELETE_FORWARD:
1843 if (col(cur.idx()) + 1 == ncols()
1844 && cur.pos() == cur.lastpos()
1845 && !cur.selection()) {
1846 if (!label(row(cur.idx())).empty()) {
1847 cur.recordUndoInset();
1848 label(row(cur.idx()), docstring());
1849 } else if (numbered(row(cur.idx()))) {
1850 cur.recordUndoInset();
1851 numbered(row(cur.idx()), false);
1852 cur.forceBufferUpdate();
1854 InsetMathGrid::doDispatch(cur, cmd);
1858 InsetMathGrid::doDispatch(cur, cmd);
1863 case LFUN_INSET_INSERT: {
1864 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1865 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1866 string const name = cmd.getArg(0);
1867 if (name == "label") {
1868 InsetCommandParams p(LABEL_CODE);
1869 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1870 docstring str = p["name"];
1871 cur.recordUndoInset();
1872 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1876 docstring old = label(r);
1879 // The label will take care of the reference update.
1883 // Newly created inset so initialize it.
1884 label_[r]->initView();
1887 cur.forceBufferUpdate();
1890 InsetMathGrid::doDispatch(cur, cmd);
1894 case LFUN_MATH_EXTERN:
1895 cur.recordUndoInset();
1899 case LFUN_MATH_MUTATE: {
1900 cur.recordUndoInset();
1901 row_type row = cur.row();
1902 col_type col = cur.col();
1903 mutate(hullType(cmd.argument()));
1904 cur.idx() = row * ncols() + col;
1905 if (cur.idx() > cur.lastidx()) {
1906 cur.idx() = cur.lastidx();
1907 cur.pos() = cur.lastpos();
1909 if (cur.pos() > cur.lastpos())
1910 cur.pos() = cur.lastpos();
1912 cur.forceBufferUpdate();
1913 // FIXME: find some more clever handling of the selection,
1914 // i.e. preserve it.
1915 cur.clearSelection();
1916 //cur.dispatched(FINISHED);
1920 case LFUN_MATH_DISPLAY: {
1921 cur.recordUndoInset();
1922 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1923 // if the cursor is in a cell that got merged, move it to
1924 // start of the hull inset.
1925 if (cur.idx() > 0) {
1929 if (cur.pos() > cur.lastpos())
1930 cur.pos() = cur.lastpos();
1935 case LFUN_TABULAR_FEATURE:
1936 if (!allowsTabularFeatures())
1939 InsetMathGrid::doDispatch(cur, cmd);
1943 InsetMathGrid::doDispatch(cur, cmd);
1951 bool allowDisplayMath(Cursor const & cur)
1953 LATTEST(cur.depth() > 1);
1954 Cursor tmpcur = cur;
1957 FuncRequest cmd(LFUN_MATH_DISPLAY);
1958 return tmpcur.getStatus(cmd, status) && status.enabled();
1964 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1965 FuncStatus & status) const
1967 switch (cmd.action()) {
1968 case LFUN_FINISHED_BACKWARD:
1969 case LFUN_FINISHED_FORWARD:
1970 case LFUN_FINISHED_RIGHT:
1971 case LFUN_FINISHED_LEFT:
1974 case LFUN_NEWLINE_INSERT:
1975 case LFUN_MATH_EXTERN:
1977 status.setEnabled(true);
1980 // we never allow this in math, and we want to bind enter
1981 // to another actions in command-alternatives
1982 case LFUN_PARAGRAPH_BREAK:
1983 status.setEnabled(false);
1985 case LFUN_MATH_MUTATE: {
1986 HullType const ht = hullType(cmd.argument());
1987 status.setOnOff(type_ == ht);
1988 status.setEnabled(isMutable(ht) && isMutable(type_));
1990 if (ht != hullSimple && status.enabled())
1991 status.setEnabled(allowDisplayMath(cur));
1994 case LFUN_MATH_DISPLAY: {
1995 status.setEnabled(display() != Inline || allowDisplayMath(cur));
1996 status.setOnOff(display() != Inline);
2000 case LFUN_MATH_NUMBER_TOGGLE:
2001 // FIXME: what is the right test, this or the one of
2003 status.setEnabled(display() != Inline);
2004 status.setOnOff(numberedType());
2007 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
2008 // FIXME: what is the right test, this or the one of
2010 bool const enable = (type_ == hullMultline)
2011 ? (nrows() - 1 == cur.row())
2012 : display() != Inline;
2013 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2014 status.setEnabled(enable);
2015 status.setOnOff(enable && numbered(r));
2019 case LFUN_LABEL_INSERT:
2020 status.setEnabled(type_ != hullSimple);
2023 case LFUN_LABEL_COPY_AS_REFERENCE: {
2024 bool enabled = false;
2026 if (cmd.argument().empty() && &cur.inset() == this) {
2027 // if there is no argument and we're inside math, we retrieve
2028 // the row number from the cursor position.
2029 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2030 enabled = numberedType() && label_[row] && numbered(row);
2032 // if there is an argument, find the corresponding label, else
2033 // check whether there is at least one label.
2034 for (row_type row = 0; row != nrows(); ++row) {
2035 if (numbered(row) && label_[row] &&
2036 (cmd.argument().empty() || label(row) == cmd.argument())) {
2042 status.setEnabled(enabled);
2046 case LFUN_INSET_INSERT:
2047 if (cmd.getArg(0) == "label") {
2048 status.setEnabled(type_ != hullSimple);
2051 return InsetMathGrid::getStatus(cur, cmd, status);
2053 case LFUN_TABULAR_FEATURE: {
2054 if (!allowsTabularFeatures())
2056 string s = cmd.getArg(0);
2058 && (s == "append-row"
2059 || s == "delete-row"
2060 || s == "copy-row")) {
2061 status.message(bformat(
2062 from_utf8(N_("Can't change number of rows in '%1$s'")),
2064 status.setEnabled(false);
2068 && (s == "append-column"
2069 || s == "delete-column"
2070 || s == "copy-column")) {
2071 status.message(bformat(
2072 from_utf8(N_("Can't change number of columns in '%1$s'")),
2074 status.setEnabled(false);
2077 if (s == "add-vline-left" || s == "add-vline-right") {
2078 status.message(bformat(
2079 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2081 status.setEnabled(false);
2084 if (s == "valign-top" || s == "valign-middle"
2085 || s == "valign-bottom" || s == "align-left"
2086 || s == "align-center" || s == "align-right") {
2087 status.setEnabled(false);
2090 return InsetMathGrid::getStatus(cur, cmd, status);
2094 return InsetMathGrid::getStatus(cur, cmd, status);
2097 // This cannot really happen, but inserted to shut-up gcc
2098 return InsetMathGrid::getStatus(cur, cmd, status);
2102 /////////////////////////////////////////////////////////////////////
2106 // simply scrap this function if you want
2107 void InsetMathHull::mutateToText()
2110 // translate to latex
2112 latex(os, false, false);
2113 string str = os.str();
2116 Text * lt = view_->cursor().innerText();
2117 string::const_iterator cit = str.begin();
2118 string::const_iterator end = str.end();
2119 for (; cit != end; ++cit)
2120 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2123 //dispatch(LFUN_ESCAPE);
2128 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2129 docstring const & font)
2131 // this whole function is a hack and won't work for incremental font
2134 if (cur.inset().asInsetMath()->name() == font)
2135 cur.handleFont(to_utf8(font));
2137 cur.handleNest(createInsetMath(font, cur.buffer()));
2143 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2148 font.fromString(to_utf8(arg), b);
2149 if (font.fontInfo().color() != Color_inherit) {
2150 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2151 cur.handleNest(at, 0);
2156 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2159 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
2160 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
2161 enter_front ? idxFirst(cur) : idxLast(cur);
2162 // The inset formula dimension is not necessarily the same as the
2163 // one of the instant preview image, so we have to indicate to the
2164 // BufferView that a metrics update is needed.
2165 cur.screenUpdateFlags(Update::Force);
2169 void InsetMathHull::revealCodes(Cursor & cur) const
2171 if (!cur.inMathed())
2173 odocstringstream os;
2175 cur.message(os.str());
2177 // write something to the minibuffer
2178 // translate to latex
2182 string str = os.str();
2184 string::size_type pos = 0;
2186 for (string::iterator it = str.begin(); it != str.end(); ++it) {
2189 else if (*it == '\0') {
2191 pos = it - str.begin();
2197 res = res.substr(pos - 30);
2198 if (res.size() > 60)
2199 res = res.substr(0, 60);
2205 /////////////////////////////////////////////////////////////////////
2209 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2212 // FIXME: completely broken
2213 static InsetMathHull * lastformula = 0;
2214 static CursorBase current = DocIterator(ibegin(nucleus()));
2216 static string laststr;
2218 if (lastformula != this || laststr != str) {
2219 //lyxerr << "reset lastformula to " << this << endl;
2222 current = ibegin(nucleus());
2224 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2228 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2230 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2231 CursorSlice & top = it.back();
2232 MathData const & a = top.asInsetMath()->cell(top.idx_);
2233 if (a.matchpart(ar, top.pos_)) {
2234 bv->cursor().setSelection(it, ar.size());
2236 top.pos_ += ar.size();
2242 //lyxerr << "not found!" << endl;
2249 void InsetMathHull::write(ostream & os) const
2251 odocstringstream oss;
2252 otexrowstream ots(oss);
2253 WriteStream wi(ots, false, false, WriteStream::wsDefault);
2256 os << to_utf8(oss.str());
2260 void InsetMathHull::read(Lexer & lex)
2263 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2264 operator=(*at->asHullInset());
2268 bool InsetMathHull::readQuiet(Lexer & lex)
2271 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2273 operator=(*at->asHullInset());
2278 int InsetMathHull::plaintext(odocstringstream & os,
2279 OutputParams const & op, size_t max_length) const
2281 // disables ASCII-art for export of equations. See #2275.
2282 if (0 && display()) {
2286 TextPainter tpain(dim.width(), dim.height());
2287 drawT(tpain, 0, dim.ascent());
2289 // reset metrics cache to "real" values
2291 return tpain.textheight();
2294 odocstringstream oss;
2295 otexrowstream ots(oss);
2296 Encoding const * const enc = encodings.fromLyXName("utf8");
2297 WriteStream wi(ots, false, true, WriteStream::wsDefault, enc);
2300 if (type_ == hullRegexp)
2303 for (row_type r = 0; r < nrows(); ++r) {
2304 for (col_type c = 0; c < ncols(); ++c)
2305 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2306 // if it's for the TOC, we write just the first line
2307 // and do not include the newline.
2308 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2310 if (r < nrows() - 1)
2314 docstring const str = oss.str();
2320 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
2325 if (getType() == hullSimple)
2326 name = from_ascii("inlineequation");
2328 name = from_ascii("informalequation");
2330 docstring bname = name;
2331 if (!label(0).empty())
2332 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
2334 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
2336 odocstringstream ls;
2338 if (runparams.flavor == OutputParams::XML) {
2339 ms << MTag("alt role='tex' ");
2340 // Workaround for db2latex: db2latex always includes equations with
2341 // \ensuremath{} or \begin{display}\end{display}
2342 // so we strip LyX' math environment
2343 WriteStream wi(ols, false, false, WriteStream::wsDefault, runparams.encoding);
2344 InsetMathGrid::write(wi);
2345 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2350 InsetMathGrid::mathmlize(ms);
2353 ms << MTag("alt role='tex'");
2354 latex(ols, runparams);
2355 res = ols.texrow().rows();
2356 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2360 ms << from_ascii("<graphic fileref=\"eqn/");
2361 if (!label(0).empty())
2362 ms << sgml::cleanID(buffer(), runparams, label(0));
2364 ms << sgml::uniqueID(from_ascii("anon"));
2366 if (runparams.flavor == OutputParams::XML)
2367 ms << from_ascii("\"/>");
2369 ms << from_ascii("\">");
2371 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2373 return ms.line() + res;
2377 bool InsetMathHull::haveNumbers() const
2379 bool havenumbers = false;
2380 // inline formulas are never numbered (bug 7351 part 3)
2381 if (getType() == hullSimple)
2383 for (size_t i = 0; i != numbered_.size(); ++i) {
2394 // We need to do something about alignment here.
2396 // This duplicates code from InsetMathGrid, but
2397 // we need access here to number information,
2398 // and we simply do not have that in InsetMathGrid.
2399 void InsetMathHull::htmlize(HtmlStream & os) const
2401 bool const havenumbers = haveNumbers();
2402 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2405 os << cell(index(0, 0));
2409 os << MTag("table", "class='mathtable'");
2410 for (row_type row = 0; row < nrows(); ++row) {
2412 for (col_type col = 0; col < ncols(); ++col) {
2414 os << cell(index(row, col));
2419 docstring const & num = numbers_[row];
2421 os << '(' << num << ')';
2426 os << ETag("table");
2430 // this duplicates code from InsetMathGrid, but
2431 // we need access here to number information,
2432 // and we simply do not have that in InsetMathGrid.
2433 void InsetMathHull::mathmlize(MathStream & os) const
2435 bool const havenumbers = haveNumbers();
2436 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2439 os << MTag("mtable");
2440 char const * const celltag = havetable ? "mtd" : "mrow";
2441 // FIXME There does not seem to be wide support at the moment
2442 // for mlabeledtr, so we have to use just mtr for now.
2443 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2444 char const * const rowtag = "mtr";
2445 for (row_type row = 0; row < nrows(); ++row) {
2448 for (col_type col = 0; col < ncols(); ++col) {
2450 << cell(index(row, col))
2456 docstring const & num = numbers_[row];
2458 os << '(' << num << ')';
2465 os << ETag("mtable");
2469 void InsetMathHull::mathAsLatex(WriteStream & os) const
2471 MathEnsurer ensurer(os, false);
2472 bool havenumbers = haveNumbers();
2473 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2476 os << cell(index(0, 0));
2480 os << "<table class='mathtable'>";
2481 for (row_type row = 0; row < nrows(); ++row) {
2483 for (col_type col = 0; col < ncols(); ++col) {
2484 os << "<td class='math'>";
2485 os << cell(index(row, col));
2490 docstring const & num = numbers_[row];
2492 os << '(' << num << ')';
2501 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2503 BufferParams::MathOutput const mathtype =
2504 buffer().masterBuffer()->params().html_math_output;
2506 bool success = false;
2508 // we output all the labels just at the beginning of the equation.
2509 // this should be fine.
2510 for (size_t i = 0; i != label_.size(); ++i) {
2511 InsetLabel const * const il = label_[i];
2517 // FIXME Eventually we would like to do this inset by inset.
2518 if (mathtype == BufferParams::MathML) {
2519 odocstringstream os;
2524 } catch (MathExportException const &) {}
2526 if (getType() == hullSimple)
2527 xs << html::StartTag("math",
2528 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2530 xs << html::StartTag("math",
2531 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2532 xs << XHTMLStream::ESCAPE_NONE
2534 << html::EndTag("math");
2536 } else if (mathtype == BufferParams::HTML) {
2537 odocstringstream os;
2542 } catch (MathExportException const &) {}
2544 string const tag = (getType() == hullSimple) ? "span" : "div";
2545 xs << html::StartTag(tag, "class='formula'", true)
2546 << XHTMLStream::ESCAPE_NONE
2548 << html::EndTag(tag);
2552 // what we actually want is this:
2554 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2556 // || mathtype == BufferParams::Images
2558 // but what follows is equivalent, since we'll enter only if either (a) we
2559 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2560 // aren't doing LaTeX.
2562 // so this is for Images.
2563 if (!success && mathtype != BufferParams::LaTeX) {
2564 graphics::PreviewImage const * pimage = 0;
2566 loadPreview(docit_);
2567 pimage = preview_->getPreviewImage(buffer());
2568 // FIXME Do we always have png?
2571 if (pimage || op.dryrun) {
2572 string const filename = pimage ? pimage->filename().onlyFileName()
2573 : "previewimage.png";
2575 // if we are not in the master buffer, then we need to see that the
2576 // generated image is copied there; otherwise, preview fails.
2577 Buffer const * mbuf = buffer().masterBuffer();
2578 if (mbuf != &buffer()) {
2579 string mbtmp = mbuf->temppath();
2580 FileName const mbufimg(support::addName(mbtmp, filename));
2581 pimage->filename().copyTo(mbufimg);
2583 // add the file to the list of files to be exported
2584 op.exportdata->addExternalFile("xhtml", pimage->filename());
2587 string const tag = (getType() == hullSimple) ? "span" : "div";
2589 << html::StartTag(tag, "style = \"text-align: center;\"")
2590 << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2591 << html::EndTag(tag)
2597 // so we'll pass this test if we've failed everything else, or
2598 // if mathtype was LaTeX, since we won't have entered any of the
2600 if (!success /* || mathtype != BufferParams::LaTeX */) {
2601 // Unfortunately, we cannot use latexString() because we do not want
2602 // $...$ or whatever.
2603 odocstringstream ls;
2604 otexrowstream ots(ls);
2605 WriteStream wi(ots, false, true, WriteStream::wsPreview);
2606 ModeSpecifier specifier(wi, MATH_MODE);
2608 docstring const latex = ls.str();
2610 // class='math' allows for use of jsMath
2611 // http://www.math.union.edu/~dpvc/jsMath/
2613 // probably should allow for some kind of customization here
2614 string const tag = (getType() == hullSimple) ? "span" : "div";
2615 xs << html::StartTag(tag, "class='math'")
2617 << html::EndTag(tag)
2624 void InsetMathHull::toString(odocstream & os) const
2626 odocstringstream ods;
2627 plaintext(ods, OutputParams(0));
2632 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2634 odocstringstream ods;
2637 // FIXME: this results in spilling TeX into the LyXHTML output since the
2638 // outliner is used to generate the LyXHTML list of figures/etc.
2644 string InsetMathHull::contextMenuName() const
2646 return "context-math";
2650 void InsetMathHull::recordLocation(DocIterator const & di)
2656 bool InsetMathHull::canPaintChange(BufferView const &) const
2658 // We let RowPainter do it seamlessly for inline insets
2659 return display() != Inline;