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, TocBackend & backend) 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 TocBuilder & b = backend.builder("equation");
348 // compute first and last item
349 row_type first = nrows();
350 for (row_type row = 0; row != nrows(); ++row)
355 if (first == nrows())
358 row_type last = nrows() - 1;
359 for (; last != 0; --last)
362 // add equation numbers
363 b.pushItem(pit, docstring(), output_active);
365 b.argumentItem(bformat(from_ascii("(%1$s-%2$s)"),
366 numbers_[first], numbers_[last]));
367 for (row_type row = 0; row != nrows(); ++row) {
371 label_[row]->addToToc(pit, output_active, utype, backend);
372 docstring label = nicelabel(row);
374 // this is the only equation
375 b.argumentItem(label);
377 // insert as sub-items
378 b.pushItem(pit, label, output_active);
386 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
388 if (previewState(&cur.bv())) {
392 return InsetMathNest::editXY(cur, x, y);
396 InsetMath::mode_type InsetMathHull::currentMode() const
400 return UNDECIDED_MODE;
402 // definitely math mode ...
422 bool InsetMathHull::idxFirst(Cursor & cur) const
430 bool InsetMathHull::idxLast(Cursor & cur) const
432 cur.idx() = nargs() - 1;
433 cur.pos() = cur.lastpos();
438 // FIXME: InsetMathGrid should be changed to let the real column alignment be
439 // given by a virtual method like displayColAlign, because the values produced
440 // by defaultColAlign can be invalidated by lfuns such as add-column. For the
441 // moment the values produced by defaultColAlign are not used, notably because
442 // alignment is not implemented in the LyXHTML output.
443 char InsetMathHull::defaultColAlign(col_type col)
445 return colAlign(type_, col);
449 char InsetMathHull::displayColAlign(idx_type idx) const
453 row_type const r = row(idx);
456 if (r == nrows() - 1)
467 return colAlign(type_, col(idx));
471 return InsetMathGrid::displayColAlign(idx);
475 int InsetMathHull::displayColSpace(col_type col) const
477 return colSpace(type_, col);
481 // FIXME: same comment as for defaultColAlign applies.
482 int InsetMathHull::defaultColSpace(col_type col)
484 return colSpace(type_, col);
488 string InsetMathHull::standardFont() const
494 return "lyxnochange";
501 ColorCode InsetMathHull::standardColor() const
506 return Color_foreground;
514 bool InsetMathHull::previewState(const BufferView *const bv) const
516 if (!editing(bv) && RenderPreview::previewMath()
517 && type_ != hullRegexp)
519 graphics::PreviewImage const * pimage =
520 preview_->getPreviewImage(bv->buffer());
521 return pimage && pimage->image();
528 static const int ERROR_FRAME_WIDTH = 2;
531 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
533 if (previewState(mi.base.bv)) {
534 preview_->metrics(mi, dim);
535 if (previewTooSmall(dim)) {
536 // preview image is too small
537 dim.wid += 2 * ERROR_FRAME_WIDTH;
538 dim.asc += 2 * ERROR_FRAME_WIDTH;
540 // insert a one pixel gap in front of the formula
543 dim.des += displayMargin();
548 Changer dummy1 = mi.base.changeFontSet(standardFont());
549 Changer dummy2 = mi.base.font.changeStyle(display() ? LM_ST_DISPLAY
552 // let the cells adjust themselves
553 InsetMathGrid::metrics(mi, dim);
556 dim.asc += displayMargin();
557 dim.des += displayMargin();
560 if (numberedType()) {
561 Changer dummy = mi.base.changeFontSet("mathbf");
563 for (row_type row = 0; row < nrows(); ++row)
564 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
570 // reserve some space for marker.
573 // make it at least as high as the current font
576 math_font_max_dim(mi.base.font, asc, des);
577 dim.asc = max(dim.asc, asc);
578 dim.des = max(dim.des, des);
582 bool InsetMathHull::previewTooSmall(Dimension const & dim) const
584 return dim.width() <= 10 && dim.height() <= 10;
588 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
590 BufferView const * const bv = pi.base.bv;
591 if (previewState(bv)) {
592 Dimension const dim = dimension(*pi.base.bv);
593 if (previewTooSmall(dim))
595 return graphics::PreviewLoader::backgroundColor();
601 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
603 Dimension const dim = dimension(*pi.base.bv);
604 if (previewTooSmall(dim)) {
605 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
606 dim.wid, dim.asc + dim.des, backgroundColor(pi));
609 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
610 dim.asc + dim.des - 1, pi.backgroundColor(this));
614 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
616 BufferView const * const bv = pi.base.bv;
617 Dimension const dim = dimension(*bv);
619 if (type_ == hullRegexp)
620 pi.pain.rectangle(x + 2, y - dim.ascent() + 1,
621 dim.width() - 3, dim.height() - 2, Color_regexpframe);
623 if (previewState(bv)) {
624 // Do not draw change tracking cue if taken care of by RowPainter
626 Changer dummy = !canPaintChange(*bv) ? make_change(pi.change_, Change())
628 if (previewTooSmall(dim)) {
629 // we have an extra frame
630 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
632 // one pixel gap in front
633 preview_->draw(pi, x + 1, y);
638 ColorCode color = pi.selected && lyxrc.use_system_colors
639 ? Color_selectiontext : standardColor();
640 bool const really_change_color = pi.base.font.color() == Color_none;
641 Changer dummy0 = really_change_color ? pi.base.font.changeColor(color)
643 Changer dummy1 = pi.base.changeFontSet(standardFont());
644 Changer dummy2 = pi.base.font.changeStyle(display() ? LM_ST_DISPLAY
647 InsetMathGrid::draw(pi, x + 1, y);
648 drawMarkers2(pi, x, y);
650 if (numberedType()) {
651 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
652 for (row_type row = 0; row < nrows(); ++row) {
653 int const yy = y + rowinfo_[row].offset_;
654 Changer dummy = pi.base.changeFontSet("mathrm");
655 docstring const nl = nicelabel(row);
659 // drawing change line
660 if (canPaintChange(*bv))
661 pi.change_.paintCue(pi, x + 1, y + 1 - dim.asc,
662 x + dim.wid, y + dim.des);
666 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
669 InsetMathGrid::metricsT(mi, dim);
672 otexrowstream ots(os);
673 WriteStream wi(ots, false, true, WriteStream::wsDefault);
675 dim.wid = os.str().size();
682 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
685 InsetMathGrid::drawT(pain, x, y);
688 otexrowstream ots(os);
689 WriteStream wi(ots, false, true, WriteStream::wsDefault);
691 pain.draw(x, y, os.str().c_str());
696 static docstring latexString(InsetMathHull const & inset)
699 // This has to be static, because a preview snippet or a math
700 // macro containing math in text mode (such as $\text{$\phi$}$ or
701 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
702 // first time as a whole, and the second time only the inner math.
703 // In this last case inset.buffer() would be invalid.
704 static Encoding const * encoding = 0;
705 if (inset.isBufferValid())
706 encoding = &(inset.buffer().params().encoding());
707 otexrowstream ots(ls);
708 WriteStream wi(ots, false, true, WriteStream::wsPreview, encoding);
714 void InsetMathHull::initUnicodeMath() const
716 // Trigger classification of the unicode symbols in this inset
717 docstring const dummy = latexString(*this);
721 void InsetMathHull::addPreview(DocIterator const & inset_pos,
722 graphics::PreviewLoader & /*ploader*/) const
724 if (RenderPreview::previewMath()) {
725 preparePreview(inset_pos);
730 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
731 MacroNameSet & macros, MacroNameSet & defs) const
733 MacroNameSet::iterator const end = macros.end();
735 for (size_t i = 0; i < md.size(); ++i) {
736 MathMacro const * mi = md[i].nucleus()->asMacro();
737 MathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
738 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
739 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
740 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
741 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
743 // Look for macros in the arguments of this macro.
744 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
745 usedMacros(mi->cell(idx), pos, macros, defs);
746 // Make sure this is a macro defined in the document
747 // (as we also spot the macros in the symbols file)
748 // or that we have not already accounted for it.
749 docstring const name = mi->name();
750 if (macros.find(name) == end)
753 // Look for macros in the definition of this macro.
754 MathData ar(pos.buffer());
755 MacroData const * data =
756 pos.buffer()->getMacro(name, pos, true);
758 odocstringstream macro_def;
759 data->write(macro_def, true);
761 defs.insert(macro_def.str());
762 asArray(data->definition(), ar);
764 usedMacros(ar, pos, macros, defs);
766 MathData ar(pos.buffer());
767 asArray(mt->definition(), ar);
768 usedMacros(ar, pos, macros, defs);
770 if (!si->nuc().empty())
771 usedMacros(si->nuc(), pos, macros, defs);
773 usedMacros(si->down(), pos, macros, defs);
775 usedMacros(si->up(), pos, macros, defs);
776 } else if (fi || gi) {
777 idx_type nidx = fi ? fi->nargs() : gi->nargs();
778 for (idx_type idx = 0; idx < nidx; ++idx)
779 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
782 usedMacros(ni->cell(0), pos, macros, defs);
788 void InsetMathHull::preparePreview(DocIterator const & pos,
789 bool forexport) const
791 // there is no need to do all the macro stuff if we're not
792 // actually going to generate the preview.
793 if (!RenderPreview::previewMath() && !forexport)
796 Buffer const * buffer = pos.buffer();
798 // collect macros at this position
800 buffer->listMacroNames(macros);
802 // collect definitions only for the macros used in this inset
804 for (idx_type idx = 0; idx < nargs(); ++idx)
805 usedMacros(cell(idx), pos, macros, defs);
807 MacroNameSet::iterator it = defs.begin();
808 MacroNameSet::iterator end = defs.end();
809 docstring macro_preamble;
810 for (; it != end; ++it)
811 macro_preamble.append(*it);
813 // set the font series and size for this snippet
814 DocIterator dit = pos.getInnerText();
815 Paragraph const & par = dit.paragraph();
816 Font font = par.getFontSettings(buffer->params(), dit.pos());
817 font.fontInfo().realize(par.layout().font);
818 string const lsize = font.latexSize();
821 if (font.fontInfo().series() == BOLD_SERIES) {
822 setfont += from_ascii("\\textbf{");
825 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
826 setfont += from_ascii("\\" + lsize + '\n');
829 if (forexport && haveNumbers()) {
830 docstring eqstr = from_ascii("equation");
831 CounterMap::const_iterator it = counter_map.find(eqstr);
832 if (it != counter_map.end()) {
833 int num = it->second;
835 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
836 '{' + convert<docstring>(num) + '}' + '\n';
838 for (size_t i = 0; i != numcnts; ++i) {
839 docstring cnt = from_ascii(counters_to_save[i]);
840 it = counter_map.find(cnt);
841 if (it == counter_map.end())
843 int num = it->second;
845 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
846 '{' + convert<docstring>(num) + '}';
849 docstring const snippet = macro_preamble + setfont + setcnt
850 + latexString(*this) + endfont;
851 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
852 preview_->addPreview(snippet, *buffer, forexport);
856 void InsetMathHull::reloadPreview(DocIterator const & pos) const
859 preview_->startLoading(*pos.buffer());
863 void InsetMathHull::loadPreview(DocIterator const & pos) const
865 bool const forexport = true;
866 preparePreview(pos, forexport);
867 preview_->startLoading(*pos.buffer(), forexport);
871 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
873 if (RenderPreview::previewMath()) {
875 cur.screenUpdateFlags(Update::Force);
881 docstring InsetMathHull::label(row_type row) const
883 LASSERT(row < nrows(), return docstring());
884 if (InsetLabel * il = label_[row])
885 return il->screenLabel();
890 void InsetMathHull::label(row_type row, docstring const & label)
892 //lyxerr << "setting label '" << label << "' for row " << row << endl;
896 label_[row] = dummy_pointer;
899 label_[row]->updateLabelAndRefs(label);
901 label_[row]->setParam("name", label);
905 InsetCommandParams p(LABEL_CODE);
907 label_[row] = new InsetLabel(buffer_, p);
909 label_[row]->setBuffer(buffer());
913 void InsetMathHull::numbered(row_type row, Numbered num)
915 numbered_[row] = num;
916 if (!numbered(row) && label_[row]) {
923 bool InsetMathHull::numbered(row_type row) const
925 return numbered_[row] == NUMBER;
929 bool InsetMathHull::ams() const
949 for (size_t row = 0; row < numbered_.size(); ++row)
950 if (numbered_[row] == NOTAG)
956 bool InsetMathHull::outerDisplay() const
979 Inset::DisplayType InsetMathHull::display() const
996 if (buffer().params().is_math_indent)
1006 int InsetMathHull::indent(BufferView const & bv) const
1008 // FIXME: set this in the textclass. This value is what the article class uses.
1009 static Length default_indent(2.5, Length::EM);
1010 if (buffer().params().is_math_indent) {
1011 Length const & len = buffer().params().getMathIndent();
1013 return bv.inPixels(default_indent);
1015 return bv.inPixels(len);
1017 return Inset::indent(bv);
1021 bool InsetMathHull::numberedType() const
1040 for (row_type row = 0; row < nrows(); ++row)
1047 void InsetMathHull::validate(LaTeXFeatures & features) const
1049 if (features.runparams().isLaTeX()) {
1051 features.require("amsmath");
1053 if (type_ == hullRegexp) {
1054 features.require("color");
1055 docstring frcol = from_utf8(lcolor.getLaTeXName(Color_regexpframe));
1056 docstring bgcol = from_ascii("white");
1057 features.addPreambleSnippet(
1058 "\\newcommand{\\regexp}[1]{\\fcolorbox{"
1060 + bgcol + "}{\\ensuremath{\\mathtt{#1}}}}");
1061 features.addPreambleSnippet(
1062 from_ascii("\\newcommand{\\endregexp}{}"));
1063 } else if (outerDisplay() && features.inDeletedInset()
1064 && !features.mustProvide("ct-dvipost")) {
1065 features.require("ct-tikz-math-sout");
1068 // Validation is necessary only if not using AMS math.
1069 // To be safe, we will always run mathedvalidate.
1070 //if (features.amsstyle)
1073 //features.binom = true;
1074 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
1075 // it would be better to do this elsewhere, but we can't validate in
1076 // InsetMathMatrix and we have no way, outside MathExtern, to know if
1077 // we even have any matrices.
1078 features.addCSSSnippet(
1079 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
1080 "table.matrix td{padding: 0.25px;}\n"
1081 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
1082 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
1084 InsetMathGrid::validate(features);
1088 void InsetMathHull::header_write(WriteStream & os) const
1090 bool n = numberedType();
1101 if (cell(0).empty())
1106 writeMathdisplayPreamble(os);
1110 os << "\\begin{equation" << star(n) << "}\n";
1120 writeMathdisplayPreamble(os);
1123 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1130 os << "\\begin{" << hullName(type_) << star(n) << '}'
1131 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1137 os << "\\begin{" << hullName(type_) << '}'
1138 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1148 os << "\\begin{unknown" << star(n) << "}\n";
1154 void InsetMathHull::footer_write(WriteStream & os) const
1156 bool n = numberedType();
1173 os << "\\end{equation" << star(n) << "}\n";
1176 writeMathdisplayPostamble(os);
1186 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1187 writeMathdisplayPostamble(os);
1194 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1200 os << "\\end{" << hullName(type_) << "}\n";
1204 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1205 os << "\\endregexp{}}";
1211 os << "\\end{unknown" << star(n) << "}\n";
1217 bool InsetMathHull::allowsTabularFeatures() const
1240 bool InsetMathHull::rowChangeOK() const
1243 type_ == hullEqnArray || type_ == hullAlign ||
1244 type_ == hullFlAlign || type_ == hullAlignAt ||
1245 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1246 type_ == hullGather || type_ == hullMultline;
1250 bool InsetMathHull::colChangeOK() const
1253 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1254 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1258 void InsetMathHull::addRow(row_type row)
1263 bool numbered = numberedType();
1264 // Move the number and raw pointer, do not call label() (bug 7511)
1265 InsetLabel * label = dummy_pointer;
1266 docstring number = empty_docstring();
1267 if (type_ == hullMultline) {
1268 if (row + 1 == nrows()) {
1269 numbered_[row] = NONUMBER;
1270 swap(label, label_[row]);
1271 swap(number, numbers_[row]);
1276 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1277 numbers_.insert(numbers_.begin() + row + 1, number);
1278 label_.insert(label_.begin() + row + 1, label);
1279 InsetMathGrid::addRow(row);
1283 void InsetMathHull::swapRow(row_type row)
1287 if (row + 1 == nrows())
1289 swap(numbered_[row], numbered_[row + 1]);
1290 swap(numbers_[row], numbers_[row + 1]);
1291 swap(label_[row], label_[row + 1]);
1292 InsetMathGrid::swapRow(row);
1296 void InsetMathHull::delRow(row_type row)
1298 if (nrows() <= 1 || !rowChangeOK())
1300 if (row + 1 == nrows() && type_ == hullMultline) {
1301 swap(numbered_[row - 1], numbered_[row]);
1302 swap(numbers_[row - 1], numbers_[row]);
1303 swap(label_[row - 1], label_[row]);
1304 InsetMathGrid::delRow(row);
1307 InsetMathGrid::delRow(row);
1308 // The last dummy row has no number info nor a label.
1309 // Test nrows() + 1 because we have already erased the row.
1310 if (row == nrows() + 1)
1312 numbered_.erase(numbered_.begin() + row);
1313 numbers_.erase(numbers_.begin() + row);
1315 label_.erase(label_.begin() + row);
1319 void InsetMathHull::addCol(col_type col)
1323 InsetMathGrid::addCol(col);
1327 void InsetMathHull::delCol(col_type col)
1329 if (ncols() <= 1 || !colChangeOK())
1331 InsetMathGrid::delCol(col);
1335 docstring InsetMathHull::nicelabel(row_type row) const
1339 docstring const & val = numbers_[row];
1341 return '(' + val + ')';
1342 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1346 void InsetMathHull::glueall(HullType type)
1349 for (idx_type i = 0; i < nargs(); ++i)
1351 InsetLabel * label = 0;
1352 if (type == hullEquation) {
1353 // preserve first non-empty label
1354 for (row_type row = 0; row < nrows(); ++row) {
1356 label = label_[row];
1362 *this = InsetMathHull(buffer_, hullSimple);
1369 void InsetMathHull::splitTo2Cols()
1371 LASSERT(ncols() == 1, return);
1372 InsetMathGrid::addCol(1);
1373 for (row_type row = 0; row < nrows(); ++row) {
1374 idx_type const i = 2 * row;
1375 pos_type pos = firstRelOp(cell(i));
1376 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1377 cell(i).erase(pos, cell(i).size());
1382 void InsetMathHull::splitTo3Cols()
1384 LASSERT(ncols() < 3, return);
1387 InsetMathGrid::addCol(2);
1388 for (row_type row = 0; row < nrows(); ++row) {
1389 idx_type const i = 3 * row + 1;
1390 if (!cell(i).empty()) {
1391 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1392 cell(i).erase(1, cell(i).size());
1398 void InsetMathHull::changeCols(col_type cols)
1400 if (ncols() == cols)
1402 else if (ncols() < cols) {
1408 while (ncols() < cols)
1409 InsetMathGrid::addCol(ncols());
1415 for (row_type row = 0; row < nrows(); ++row) {
1416 idx_type const i = row * ncols();
1417 for (col_type col = cols; col < ncols(); ++col) {
1418 cell(i + cols - 1).append(cell(i + col));
1422 while (ncols() > cols) {
1423 InsetMathGrid::delCol(ncols() - 1);
1428 HullType InsetMathHull::getType() const
1434 void InsetMathHull::setType(HullType type)
1441 bool InsetMathHull::isMutable(HullType type)
1465 void InsetMathHull::mutate(HullType newtype)
1467 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1469 if (newtype == type_)
1472 // This guards the algorithm below it, which is designed with certain types
1474 if (!isMutable(newtype) || !isMutable(type_)) {
1475 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1476 << "' to '" << to_utf8(hullName(newtype))
1477 << "' not implemented" << endl;
1481 // we try to move along the chain
1482 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1484 // +-------------------------------------+
1485 // we use eqnarray as intermediate type for mutations that are not
1486 // directly supported because it handles labels and numbering for
1491 setType(hullSimple);
1497 if (newtype == hullNone) {
1501 setType(hullEquation);
1502 numbered(0, label_[0] ? true : false);
1511 setType(hullSimple);
1516 // split it "nicely" on the first relop
1518 setType(hullEqnArray);
1526 // split it "nicely"
1561 setType(hullEqnArray);
1570 for (row_type row = 0; row < nrows(); ++row)
1571 numbered(row, false);
1581 for (row_type row = 0; row < nrows(); ++row)
1582 numbered(row, false);
1589 setType(hullEqnArray);
1619 for (row_type row = 0; row < nrows(); ++row)
1620 numbered(row, false);
1624 // first we mutate to EqnArray
1626 setType(hullEqnArray);
1633 // we passed the guard so we should not be here
1634 LASSERT("Mutation not implemented, but should have been.", return);
1640 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1641 bool last_eoln) const
1644 if (numberedType()) {
1645 if (label_[row] && numbered(row)) {
1646 docstring const name =
1647 latex ? escape(label_[row]->getParam("name"))
1648 : label_[row]->getParam("name");
1649 res += "\\label{" + name + '}';
1651 if (type_ != hullMultline) {
1652 if (numbered_[row] == NONUMBER)
1653 res += "\\nonumber ";
1654 else if (numbered_[row] == NOTAG)
1658 // Never add \\ on the last empty line of eqnarray and friends
1660 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1663 void InsetMathHull::write(WriteStream & os) const
1665 ModeSpecifier specifier(os, MATH_MODE);
1667 InsetMathGrid::write(os);
1672 void InsetMathHull::normalize(NormalStream & os) const
1674 os << "[formula " << hullName(type_) << ' ';
1675 InsetMathGrid::normalize(os);
1680 void InsetMathHull::infoize(odocstream & os) const
1682 os << bformat(_("Type: %1$s"), hullName(type_));
1686 void InsetMathHull::check() const
1688 LATTEST(numbered_.size() == nrows());
1689 LATTEST(numbers_.size() == nrows());
1690 LATTEST(label_.size() == nrows());
1694 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1698 idocstringstream iss(func.argument());
1699 iss >> dlang >> extra;
1701 extra = from_ascii("noextra");
1702 string const lang = to_ascii(dlang);
1704 // replace selection with result of computation
1705 if (reduceSelectionToOneCell(cur)) {
1707 asArray(grabAndEraseSelection(cur), ar);
1708 lyxerr << "use selection: " << ar << endl;
1709 cur.insert(pipeThroughExtern(lang, extra, ar));
1713 // only inline, display or eqnarray math is allowed
1714 switch (getType()) {
1720 frontend::Alert::warning(_("Bad math environment"),
1721 _("Computation cannot be performed for AMS "
1722 "math environments.\nChange the math "
1723 "formula type and try again."));
1728 eq.push_back(MathAtom(new InsetMathChar('=')));
1730 // go to first item in line
1731 cur.idx() -= cur.idx() % ncols();
1734 if (getType() == hullSimple) {
1735 size_type pos = cur.cell().find_last(eq);
1737 if (pos == cur.cell().size()) {
1739 lyxerr << "use whole cell: " << ar << endl;
1741 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1742 lyxerr << "use partial cell form pos: " << pos << endl;
1744 cur.cell().append(eq);
1745 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1746 cur.pos() = cur.lastpos();
1750 if (getType() == hullEquation) {
1751 lyxerr << "use equation inset" << endl;
1752 mutate(hullEqnArray);
1753 MathData & ar = cur.cell();
1754 lyxerr << "use cell: " << ar << endl;
1758 cur.cell() = pipeThroughExtern(lang, extra, ar);
1759 // move to end of line
1760 cur.pos() = cur.lastpos();
1765 lyxerr << "use eqnarray" << endl;
1766 cur.idx() += 2 - cur.idx() % ncols();
1768 MathData ar = cur.cell();
1769 lyxerr << "use cell: " << ar << endl;
1770 // FIXME: temporarily disabled
1776 cur.cell() = pipeThroughExtern(lang, extra, ar);
1777 cur.pos() = cur.lastpos();
1782 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1784 //lyxerr << "action: " << cmd.action() << endl;
1785 switch (cmd.action()) {
1787 case LFUN_FINISHED_BACKWARD:
1788 case LFUN_FINISHED_FORWARD:
1789 case LFUN_FINISHED_RIGHT:
1790 case LFUN_FINISHED_LEFT:
1791 //lyxerr << "action: " << cmd.action() << endl;
1792 InsetMathGrid::doDispatch(cur, cmd);
1795 case LFUN_PARAGRAPH_BREAK:
1796 // just swallow this
1799 case LFUN_NEWLINE_INSERT:
1800 // some magic for the common case
1801 if (type_ == hullSimple || type_ == hullEquation) {
1802 cur.recordUndoInset();
1804 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1805 mutate(align ? hullAlign : hullEqnArray);
1806 // mutate() may change labels and such.
1807 cur.forceBufferUpdate();
1808 cur.idx() = nrows() * ncols() - 1;
1809 cur.pos() = cur.lastpos();
1811 InsetMathGrid::doDispatch(cur, cmd);
1814 case LFUN_MATH_NUMBER_TOGGLE: {
1815 //lyxerr << "toggling all numbers" << endl;
1816 cur.recordUndoInset();
1817 bool old = numberedType();
1818 if (type_ == hullMultline)
1819 numbered(nrows() - 1, !old);
1821 for (row_type row = 0; row < nrows(); ++row)
1822 numbered(row, !old);
1824 cur.message(old ? _("No number") : _("Number"));
1825 cur.forceBufferUpdate();
1829 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1830 cur.recordUndoInset();
1831 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1832 bool old = numbered(r);
1833 cur.message(old ? _("No number") : _("Number"));
1835 cur.forceBufferUpdate();
1839 case LFUN_LABEL_INSERT: {
1840 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1841 docstring old_label = label(r);
1842 docstring const default_label = from_ascii("eq:");
1843 if (old_label.empty())
1844 old_label = default_label;
1846 InsetCommandParams p(LABEL_CODE);
1847 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1848 string const data = InsetCommand::params2string(p);
1850 if (cmd.argument().empty())
1851 cur.bv().showDialog("label", data);
1853 FuncRequest fr(LFUN_INSET_INSERT, data);
1859 case LFUN_LABEL_COPY_AS_REFERENCE: {
1861 if (cmd.argument().empty() && &cur.inset() == this)
1862 // if there is no argument and we're inside math, we retrieve
1863 // the row number from the cursor position.
1864 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1866 // if there is an argument, find the corresponding label, else
1867 // check whether there is at least one label.
1868 for (row = 0; row != nrows(); ++row)
1869 if (numbered(row) && label_[row]
1870 && (cmd.argument().empty() || label(row) == cmd.argument()))
1877 InsetCommandParams p(REF_CODE, "ref");
1878 p["reference"] = label(row);
1879 cap::clearSelection();
1880 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1884 case LFUN_WORD_DELETE_FORWARD:
1885 case LFUN_CHAR_DELETE_FORWARD:
1886 if (col(cur.idx()) + 1 == ncols()
1887 && cur.pos() == cur.lastpos()
1888 && !cur.selection()) {
1889 if (!label(row(cur.idx())).empty()) {
1890 cur.recordUndoInset();
1891 label(row(cur.idx()), docstring());
1892 } else if (numbered(row(cur.idx()))) {
1893 cur.recordUndoInset();
1894 numbered(row(cur.idx()), false);
1895 cur.forceBufferUpdate();
1897 InsetMathGrid::doDispatch(cur, cmd);
1901 InsetMathGrid::doDispatch(cur, cmd);
1906 case LFUN_INSET_INSERT: {
1907 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1908 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1909 string const name = cmd.getArg(0);
1910 if (name == "label") {
1911 InsetCommandParams p(LABEL_CODE);
1912 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1913 docstring str = p["name"];
1914 cur.recordUndoInset();
1915 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1919 docstring old = label(r);
1922 // The label will take care of the reference update.
1926 // Newly created inset so initialize it.
1927 label_[r]->initView();
1930 cur.forceBufferUpdate();
1933 InsetMathGrid::doDispatch(cur, cmd);
1937 case LFUN_MATH_EXTERN:
1938 cur.recordUndoInset();
1942 case LFUN_MATH_MUTATE: {
1943 cur.recordUndoInset();
1944 row_type row = cur.row();
1945 col_type col = cur.col();
1946 mutate(hullType(cmd.argument()));
1947 cur.idx() = row * ncols() + col;
1948 if (cur.idx() > cur.lastidx()) {
1949 cur.idx() = cur.lastidx();
1950 cur.pos() = cur.lastpos();
1952 if (cur.pos() > cur.lastpos())
1953 cur.pos() = cur.lastpos();
1955 cur.forceBufferUpdate();
1956 // FIXME: find some more clever handling of the selection,
1957 // i.e. preserve it.
1958 cur.clearSelection();
1959 //cur.dispatched(FINISHED);
1963 case LFUN_MATH_DISPLAY: {
1964 cur.recordUndoInset();
1965 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1966 // if the cursor is in a cell that got merged, move it to
1967 // start of the hull inset.
1968 if (cur.idx() > 0) {
1972 if (cur.pos() > cur.lastpos())
1973 cur.pos() = cur.lastpos();
1978 case LFUN_TABULAR_FEATURE:
1979 if (!allowsTabularFeatures())
1982 InsetMathGrid::doDispatch(cur, cmd);
1986 InsetMathGrid::doDispatch(cur, cmd);
1994 bool allowDisplayMath(Cursor const & cur)
1996 LATTEST(cur.depth() > 1);
1997 Cursor tmpcur = cur;
2000 FuncRequest cmd(LFUN_MATH_DISPLAY);
2001 return tmpcur.getStatus(cmd, status) && status.enabled();
2007 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
2008 FuncStatus & status) const
2010 switch (cmd.action()) {
2011 case LFUN_FINISHED_BACKWARD:
2012 case LFUN_FINISHED_FORWARD:
2013 case LFUN_FINISHED_RIGHT:
2014 case LFUN_FINISHED_LEFT:
2017 case LFUN_NEWLINE_INSERT:
2018 case LFUN_MATH_EXTERN:
2020 status.setEnabled(true);
2023 // we never allow this in math, and we want to bind enter
2024 // to another actions in command-alternatives
2025 case LFUN_PARAGRAPH_BREAK:
2026 status.setEnabled(false);
2028 case LFUN_MATH_MUTATE: {
2029 HullType const ht = hullType(cmd.argument());
2030 status.setOnOff(type_ == ht);
2031 status.setEnabled(isMutable(ht) && isMutable(type_));
2033 if (ht != hullSimple && status.enabled())
2034 status.setEnabled(allowDisplayMath(cur));
2037 case LFUN_MATH_DISPLAY: {
2038 status.setEnabled(display() != Inline || allowDisplayMath(cur));
2039 status.setOnOff(display() != Inline);
2043 case LFUN_MATH_NUMBER_TOGGLE:
2044 // FIXME: what is the right test, this or the one of
2046 status.setEnabled(display() != Inline);
2047 status.setOnOff(numberedType());
2050 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
2051 // FIXME: what is the right test, this or the one of
2053 bool const enable = (type_ == hullMultline)
2054 ? (nrows() - 1 == cur.row())
2055 : display() != Inline;
2056 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2057 status.setEnabled(enable);
2058 status.setOnOff(enable && numbered(r));
2062 case LFUN_LABEL_INSERT:
2063 status.setEnabled(type_ != hullSimple);
2066 case LFUN_LABEL_COPY_AS_REFERENCE: {
2067 bool enabled = false;
2069 if (cmd.argument().empty() && &cur.inset() == this) {
2070 // if there is no argument and we're inside math, we retrieve
2071 // the row number from the cursor position.
2072 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2073 enabled = numberedType() && label_[row] && numbered(row);
2075 // if there is an argument, find the corresponding label, else
2076 // check whether there is at least one label.
2077 for (row_type row = 0; row != nrows(); ++row) {
2078 if (numbered(row) && label_[row] &&
2079 (cmd.argument().empty() || label(row) == cmd.argument())) {
2085 status.setEnabled(enabled);
2089 case LFUN_INSET_INSERT:
2090 if (cmd.getArg(0) == "label") {
2091 status.setEnabled(type_ != hullSimple);
2094 return InsetMathGrid::getStatus(cur, cmd, status);
2096 case LFUN_TABULAR_FEATURE: {
2097 if (!allowsTabularFeatures())
2099 string s = cmd.getArg(0);
2101 && (s == "append-row"
2102 || s == "delete-row"
2103 || s == "copy-row")) {
2104 status.message(bformat(
2105 from_utf8(N_("Can't change number of rows in '%1$s'")),
2107 status.setEnabled(false);
2111 && (s == "append-column"
2112 || s == "delete-column"
2113 || s == "copy-column")) {
2114 status.message(bformat(
2115 from_utf8(N_("Can't change number of columns in '%1$s'")),
2117 status.setEnabled(false);
2120 if (s == "add-vline-left" || s == "add-vline-right") {
2121 status.message(bformat(
2122 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2124 status.setEnabled(false);
2127 if (s == "valign-top" || s == "valign-middle"
2128 || s == "valign-bottom" || s == "align-left"
2129 || s == "align-center" || s == "align-right") {
2130 status.setEnabled(false);
2133 return InsetMathGrid::getStatus(cur, cmd, status);
2137 return InsetMathGrid::getStatus(cur, cmd, status);
2142 int InsetMathHull::leftMargin() const
2144 return (getType() == hullSimple) ? 0 : InsetMathGrid::leftMargin();
2148 int InsetMathHull::rightMargin() const
2150 return (getType() == hullSimple) ? 0 : InsetMathGrid::rightMargin();
2154 int InsetMathHull::border() const
2156 return (getType() == hullSimple) ? 0 : InsetMathGrid::border();
2160 /////////////////////////////////////////////////////////////////////
2164 // simply scrap this function if you want
2165 void InsetMathHull::mutateToText()
2168 // translate to latex
2170 latex(os, false, false);
2171 string str = os.str();
2174 Text * lt = view_->cursor().innerText();
2175 string::const_iterator cit = str.begin();
2176 string::const_iterator end = str.end();
2177 for (; cit != end; ++cit)
2178 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2181 //dispatch(LFUN_ESCAPE);
2186 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2187 docstring const & font)
2189 // this whole function is a hack and won't work for incremental font
2192 if (cur.inset().asInsetMath()->name() == font)
2193 cur.handleFont(to_utf8(font));
2195 cur.handleNest(createInsetMath(font, cur.buffer()));
2201 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2206 font.fromString(to_utf8(arg), b);
2207 if (font.fontInfo().color() != Color_inherit) {
2208 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2209 cur.handleNest(at, 0);
2214 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2217 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
2218 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
2219 enter_front ? idxFirst(cur) : idxLast(cur);
2220 // The inset formula dimension is not necessarily the same as the
2221 // one of the instant preview image, so we have to indicate to the
2222 // BufferView that a metrics update is needed.
2223 cur.screenUpdateFlags(Update::Force);
2227 void InsetMathHull::revealCodes(Cursor & cur) const
2229 if (!cur.inMathed())
2231 odocstringstream os;
2233 cur.message(os.str());
2235 // write something to the minibuffer
2236 // translate to latex
2240 string str = os.str();
2242 string::size_type pos = 0;
2244 for (string::iterator it = str.begin(); it != str.end(); ++it) {
2247 else if (*it == '\0') {
2249 pos = it - str.begin();
2255 res = res.substr(pos - 30);
2256 if (res.size() > 60)
2257 res = res.substr(0, 60);
2263 /////////////////////////////////////////////////////////////////////
2267 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2270 // FIXME: completely broken
2271 static InsetMathHull * lastformula = 0;
2272 static CursorBase current = DocIterator(ibegin(nucleus()));
2274 static string laststr;
2276 if (lastformula != this || laststr != str) {
2277 //lyxerr << "reset lastformula to " << this << endl;
2280 current = ibegin(nucleus());
2282 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2286 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2288 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2289 CursorSlice & top = it.back();
2290 MathData const & a = top.asInsetMath()->cell(top.idx_);
2291 if (a.matchpart(ar, top.pos_)) {
2292 bv->cursor().setSelection(it, ar.size());
2294 top.pos_ += ar.size();
2300 //lyxerr << "not found!" << endl;
2307 void InsetMathHull::write(ostream & os) const
2309 odocstringstream oss;
2310 otexrowstream ots(oss);
2311 WriteStream wi(ots, false, false, WriteStream::wsDefault);
2314 os << to_utf8(oss.str());
2318 void InsetMathHull::read(Lexer & lex)
2321 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2322 operator=(*at->asHullInset());
2326 bool InsetMathHull::readQuiet(Lexer & lex)
2329 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2331 operator=(*at->asHullInset());
2336 int InsetMathHull::plaintext(odocstringstream & os,
2337 OutputParams const & op, size_t max_length) const
2339 // disables ASCII-art for export of equations. See #2275.
2340 if (0 && display()) {
2344 TextPainter tpain(dim.width(), dim.height());
2345 drawT(tpain, 0, dim.ascent());
2347 // reset metrics cache to "real" values
2349 return tpain.textheight();
2352 odocstringstream oss;
2353 otexrowstream ots(oss);
2354 Encoding const * const enc = encodings.fromLyXName("utf8");
2355 WriteStream wi(ots, false, true, WriteStream::wsDefault, enc);
2358 if (type_ == hullRegexp)
2361 for (row_type r = 0; r < nrows(); ++r) {
2362 for (col_type c = 0; c < ncols(); ++c)
2363 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2364 // if it's for the TOC, we write just the first line
2365 // and do not include the newline.
2366 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2368 if (r < nrows() - 1)
2372 docstring const str = oss.str();
2378 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
2383 if (getType() == hullSimple)
2384 name = from_ascii("inlineequation");
2386 name = from_ascii("informalequation");
2388 docstring bname = name;
2389 if (!label(0).empty())
2390 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
2392 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
2394 odocstringstream ls;
2396 if (runparams.flavor == OutputParams::XML) {
2397 ms << MTag("alt role='tex' ");
2398 // Workaround for db2latex: db2latex always includes equations with
2399 // \ensuremath{} or \begin{display}\end{display}
2400 // so we strip LyX' math environment
2401 WriteStream wi(ols, false, false, WriteStream::wsDefault, runparams.encoding);
2402 InsetMathGrid::write(wi);
2403 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2408 InsetMathGrid::mathmlize(ms);
2411 ms << MTag("alt role='tex'");
2412 latex(ols, runparams);
2413 res = ols.texrow().rows();
2414 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2418 ms << from_ascii("<graphic fileref=\"eqn/");
2419 if (!label(0).empty())
2420 ms << sgml::cleanID(buffer(), runparams, label(0));
2422 ms << sgml::uniqueID(from_ascii("anon"));
2424 if (runparams.flavor == OutputParams::XML)
2425 ms << from_ascii("\"/>");
2427 ms << from_ascii("\">");
2429 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2431 return ms.line() + res;
2435 bool InsetMathHull::haveNumbers() const
2437 bool havenumbers = false;
2438 // inline formulas are never numbered (bug 7351 part 3)
2439 if (getType() == hullSimple)
2441 for (size_t i = 0; i != numbered_.size(); ++i) {
2452 // We need to do something about alignment here.
2454 // This duplicates code from InsetMathGrid, but
2455 // we need access here to number information,
2456 // and we simply do not have that in InsetMathGrid.
2457 void InsetMathHull::htmlize(HtmlStream & os) const
2459 bool const havenumbers = haveNumbers();
2460 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2463 os << cell(index(0, 0));
2467 os << MTag("table", "class='mathtable'");
2468 for (row_type row = 0; row < nrows(); ++row) {
2470 for (col_type col = 0; col < ncols(); ++col) {
2472 os << cell(index(row, col));
2477 docstring const & num = numbers_[row];
2479 os << '(' << num << ')';
2484 os << ETag("table");
2488 // this duplicates code from InsetMathGrid, but
2489 // we need access here to number information,
2490 // and we simply do not have that in InsetMathGrid.
2491 void InsetMathHull::mathmlize(MathStream & os) const
2493 bool const havenumbers = haveNumbers();
2494 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2497 os << MTag("mtable");
2498 char const * const celltag = havetable ? "mtd" : "mrow";
2499 // FIXME There does not seem to be wide support at the moment
2500 // for mlabeledtr, so we have to use just mtr for now.
2501 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2502 char const * const rowtag = "mtr";
2503 for (row_type row = 0; row < nrows(); ++row) {
2506 for (col_type col = 0; col < ncols(); ++col) {
2508 << cell(index(row, col))
2514 docstring const & num = numbers_[row];
2516 os << '(' << num << ')';
2523 os << ETag("mtable");
2527 void InsetMathHull::mathAsLatex(WriteStream & os) const
2529 MathEnsurer ensurer(os, false);
2530 bool havenumbers = haveNumbers();
2531 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2534 os << cell(index(0, 0));
2538 os << "<table class='mathtable'>";
2539 for (row_type row = 0; row < nrows(); ++row) {
2541 for (col_type col = 0; col < ncols(); ++col) {
2542 os << "<td class='math'>";
2543 os << cell(index(row, col));
2548 docstring const & num = numbers_[row];
2550 os << '(' << num << ')';
2559 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2561 BufferParams::MathOutput const mathtype =
2562 buffer().masterBuffer()->params().html_math_output;
2564 bool success = false;
2566 // we output all the labels just at the beginning of the equation.
2567 // this should be fine.
2568 for (size_t i = 0; i != label_.size(); ++i) {
2569 InsetLabel const * const il = label_[i];
2575 // FIXME Eventually we would like to do this inset by inset.
2576 if (mathtype == BufferParams::MathML) {
2577 odocstringstream os;
2582 } catch (MathExportException const &) {}
2584 if (getType() == hullSimple)
2585 xs << html::StartTag("math",
2586 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2588 xs << html::StartTag("math",
2589 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2590 xs << XHTMLStream::ESCAPE_NONE
2592 << html::EndTag("math");
2594 } else if (mathtype == BufferParams::HTML) {
2595 odocstringstream os;
2600 } catch (MathExportException const &) {}
2602 string const tag = (getType() == hullSimple) ? "span" : "div";
2603 xs << html::StartTag(tag, "class='formula'", true)
2604 << XHTMLStream::ESCAPE_NONE
2606 << html::EndTag(tag);
2610 // what we actually want is this:
2612 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2614 // || mathtype == BufferParams::Images
2616 // but what follows is equivalent, since we'll enter only if either (a) we
2617 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2618 // aren't doing LaTeX.
2620 // so this is for Images.
2621 if (!success && mathtype != BufferParams::LaTeX) {
2622 graphics::PreviewImage const * pimage = 0;
2624 loadPreview(docit_);
2625 pimage = preview_->getPreviewImage(buffer());
2626 // FIXME Do we always have png?
2629 if (pimage || op.dryrun) {
2630 string const filename = pimage ? pimage->filename().onlyFileName()
2631 : "previewimage.png";
2633 // if we are not in the master buffer, then we need to see that the
2634 // generated image is copied there; otherwise, preview fails.
2635 Buffer const * mbuf = buffer().masterBuffer();
2636 if (mbuf != &buffer()) {
2637 string mbtmp = mbuf->temppath();
2638 FileName const mbufimg(support::addName(mbtmp, filename));
2639 pimage->filename().copyTo(mbufimg);
2641 // add the file to the list of files to be exported
2642 op.exportdata->addExternalFile("xhtml", pimage->filename());
2645 string const tag = (getType() == hullSimple) ? "span" : "div";
2647 << html::StartTag(tag, "style = \"text-align: center;\"")
2648 << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2649 << html::EndTag(tag)
2655 // so we'll pass this test if we've failed everything else, or
2656 // if mathtype was LaTeX, since we won't have entered any of the
2658 if (!success /* || mathtype != BufferParams::LaTeX */) {
2659 // Unfortunately, we cannot use latexString() because we do not want
2660 // $...$ or whatever.
2661 odocstringstream ls;
2662 otexrowstream ots(ls);
2663 WriteStream wi(ots, false, true, WriteStream::wsPreview);
2664 ModeSpecifier specifier(wi, MATH_MODE);
2666 docstring const latex = ls.str();
2668 // class='math' allows for use of jsMath
2669 // http://www.math.union.edu/~dpvc/jsMath/
2671 // probably should allow for some kind of customization here
2672 string const tag = (getType() == hullSimple) ? "span" : "div";
2673 xs << html::StartTag(tag, "class='math'")
2675 << html::EndTag(tag)
2682 void InsetMathHull::toString(odocstream & os) const
2684 odocstringstream ods;
2685 plaintext(ods, OutputParams(0));
2690 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2692 odocstringstream ods;
2695 // FIXME: this results in spilling TeX into the LyXHTML output since the
2696 // outliner is used to generate the LyXHTML list of figures/etc.
2702 string InsetMathHull::contextMenuName() const
2704 return "context-math";
2708 void InsetMathHull::recordLocation(DocIterator const & di)
2714 bool InsetMathHull::canPaintChange(BufferView const &) const
2716 // We let RowPainter do it seamlessly for inline insets
2717 return display() != Inline;