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"
14 #include "InsetMathChar.h"
15 #include "InsetMathColor.h"
16 #include "InsetMathFrac.h"
17 #include "InsetMathNest.h"
18 #include "InsetMathScript.h"
19 #include "MathExtern.h"
20 #include "MathFactory.h"
21 #include "MathStream.h"
22 #include "MathSupport.h"
25 #include "BufferParams.h"
26 #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 "InsetMathMacro.h"
39 #include "InsetMathMacroTemplate.h"
40 #include "MetricsInfo.h"
41 #include "Paragraph.h"
42 #include "ParIterator.h"
45 #include "TextClass.h"
46 #include "TextPainter.h"
47 #include "TocBackend.h"
49 #include "insets/InsetLabel.h"
50 #include "insets/InsetRef.h"
51 #include "insets/RenderPreview.h"
53 #include "graphics/PreviewImage.h"
54 #include "graphics/PreviewLoader.h"
56 #include "frontends/alert.h"
57 #include "frontends/FontMetrics.h"
58 #include "frontends/Painter.h"
60 #include "support/convert.h"
61 #include "support/debug.h"
62 #include "support/gettext.h"
63 #include "support/filetools.h"
64 #include "support/lassert.h"
65 #include "support/lstrings.h"
66 #include "support/Changer.h"
71 using namespace lyx::support;
75 using cap::grabAndEraseSelection;
76 using cap::reduceSelectionToOneCell;
80 int getCols(HullType type)
105 // returns position of first relation operator in the array
106 // used for "intelligent splitting"
107 size_t firstRelOp(MathData const & ar)
109 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
110 if ((*it)->mathClass() == MC_REL)
111 return it - ar.begin();
116 char const * star(bool numbered)
118 return numbered ? "" : "*";
122 // writes a preamble for underlined or struck out math display
123 void writeMathdisplayPreamble(TeXMathStream & os)
125 if (os.strikeoutMath())
128 if (os.ulemCmd() == TeXMathStream::UNDERLINE)
129 os << "\\raisebox{-\\belowdisplayshortskip}{"
130 "\\parbox[b]{\\linewidth}{";
131 else if (os.ulemCmd() == TeXMathStream::STRIKEOUT)
132 os << "\\parbox{\\linewidth}{";
136 // writes a postamble for underlined or struck out math display
137 void writeMathdisplayPostamble(TeXMathStream & os)
139 if (os.strikeoutMath())
142 if (os.ulemCmd() == TeXMathStream::UNDERLINE)
144 else if (os.ulemCmd() == TeXMathStream::STRIKEOUT)
151 static InsetLabel * dummy_pointer = 0;
153 InsetMathHull::InsetMathHull(Buffer * buf)
154 : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, NONUMBER),
155 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
156 preview_(new RenderPreview(this))
158 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
159 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
160 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
161 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
168 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
169 : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, NONUMBER),
170 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
171 preview_(new RenderPreview(this))
179 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
185 InsetMathHull::~InsetMathHull()
187 for (auto & i : label_)
192 Inset * InsetMathHull::clone() const
194 return new InsetMathHull(*this);
198 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
202 InsetMathGrid::operator=(other);
204 numbered_ = other.numbered_;
205 numbers_ = other.numbers_;
206 buffer_ = other.buffer_;
207 for (auto & i : label_)
209 label_ = other.label_;
210 for (size_t i = 0; i != label_.size(); ++i) {
212 label_[i] = new InsetLabel(*label_[i]);
214 preview_.reset(new RenderPreview(*other.preview_, this));
220 void InsetMathHull::setBuffer(Buffer & buffer)
222 InsetMathGrid::setBuffer(buffer);
224 for (size_t i = 0; i != label_.size(); ++i) {
226 label_[i]->setBuffer(buffer);
231 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
234 //FIXME: buffer_ should be set at creation for this inset! Problem is
235 // This inset is created at too many places (see Parser::parse1() in
240 // if any of the equations are numbered, then we want to save the values
241 // of some of the counters.
243 BufferParams const & bp = buffer_->params();
244 string const & lang = it->getParLanguage(bp)->code();
246 buffer_->masterBuffer()->params().documentClass().counters();
248 // this has to be done separately
249 docstring const eqstr = from_ascii("equation");
250 if (cnts.hasCounter(eqstr)) {
251 for (size_t i = 0; i != label_.size(); ++i) {
252 docstring const oldnumber = numbers_[i];
254 Paragraph const & par = it.paragraph();
255 if (!par.isDeleted(it.pos())) {
256 cnts.step(eqstr, utype);
257 numbers_[i] = cnts.theCounter(eqstr, lang);
259 numbers_[i] = from_ascii("#");
261 numbers_[i] = empty_docstring();
262 // If the numbering has changed, trigger a new preview
263 if (oldnumber != numbers_[i] && RenderPreview::previewMath()) {
264 // Do we need to remove it first?
265 //preview_->removePreview(*buffer_);
273 for (size_t i = 0; i != label_.size(); ++i) {
275 label_[i]->updateBuffer(it, utype, deleted);
278 InsetMathGrid::updateBuffer(it, utype, deleted);
282 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active,
283 UpdateType utype, TocBackend & backend) const
286 //FIXME: buffer_ should be set at creation for this inset! Problem is
287 // This inset is created at too many places (see Parser::parse1() in
292 TocBuilder & b = backend.builder("equation");
293 // compute first and last item
294 row_type first = nrows();
295 for (row_type row = 0; row != nrows(); ++row)
300 if (first == nrows())
303 row_type last = nrows() - 1;
304 for (; last != 0; --last)
307 // add equation numbers
308 b.pushItem(pit, docstring(), output_active);
310 b.argumentItem(bformat(from_ascii("(%1$s-%2$s)"),
311 numbers_[first], numbers_[last]));
312 for (row_type row = 0; row != nrows(); ++row) {
316 label_[row]->addToToc(pit, output_active, utype, backend);
317 docstring label = nicelabel(row);
319 // this is the only equation
320 b.argumentItem(label);
322 // insert as sub-items
323 b.pushItem(pit, label, output_active);
331 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
333 if (previewState(&cur.bv())) {
337 return InsetMathNest::editXY(cur, x, y);
341 InsetMath::mode_type InsetMathHull::currentMode() const
345 return UNDECIDED_MODE;
347 // definitely math mode ...
367 // FIXME: InsetMathGrid should be changed to let the real column alignment be
368 // given by a virtual method like displayColAlign, because the values produced
369 // by defaultColAlign can be invalidated by lfuns such as add-column. For the
370 // moment the values produced by defaultColAlign are not used, notably because
371 // alignment is not implemented in the LyXHTML output.
372 char InsetMathHull::defaultColAlign(col_type col)
374 return colAlign(type_, col);
378 char InsetMathHull::displayColAlign(idx_type idx) const
382 row_type const r = row(idx);
385 if (r == nrows() - 1)
396 return colAlign(type_, col(idx));
400 return InsetMathGrid::displayColAlign(idx);
404 int InsetMathHull::displayColSpace(col_type col) const
406 return colSpace(type_, col);
410 // FIXME: same comment as for defaultColAlign applies.
411 int InsetMathHull::defaultColSpace(col_type col)
413 return colSpace(type_, col);
417 string InsetMathHull::standardFont() const
423 return "lyxnochange";
430 ColorCode InsetMathHull::standardColor() const
435 return Color_foreground;
443 bool InsetMathHull::previewState(const BufferView *const bv) const
445 if (!editing(bv) && RenderPreview::previewMath()
446 && type_ != hullRegexp)
448 graphics::PreviewImage const * pimage =
449 preview_->getPreviewImage(bv->buffer());
450 return pimage && pimage->image();
457 const int ERROR_FRAME_WIDTH = 2;
459 bool previewTooSmall(Dimension const & dim)
461 return dim.width() <= 10 && dim.height() <= 10;
466 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
468 /* Compute \(above|below)displayskip
469 true value in LaTeX is 10pt plus 2pt minus 5pt (in normal size at 10pt)
470 But we use a fixed number of pixels and scale them with zoom.
472 int const bottom_display_margin = mi.base.bv->zoomedPixels(6);
473 int top_display_margin = bottom_display_margin;
474 // at start of paragraph, add an empty line
476 top_display_margin += theFontMetrics(mi.base.font).maxHeight() + 2;
478 if (previewState(mi.base.bv)) {
479 preview_->metrics(mi, dim);
480 if (previewTooSmall(dim)) {
481 // preview image is too small
482 dim.wid += 2 * ERROR_FRAME_WIDTH;
483 dim.asc += 2 * ERROR_FRAME_WIDTH;
485 // insert a gap in front of the formula
486 // value was hardcoded to 1 pixel
487 dim.wid += mi.base.bv->zoomedPixels(1) ;
489 dim.asc += top_display_margin;
490 dim.des += bottom_display_margin;
497 Changer dummy1 = mi.base.changeFontSet(standardFont());
498 Changer dummy2 = mi.base.font.changeStyle(display() ? DISPLAY_STYLE
501 // let the cells adjust themselves
502 InsetMathGrid::metrics(mi, dim);
505 // Check whether the numbering interferes with the equations
506 if (numberedType()) {
507 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
508 int extra_offset = 0;
509 for (row_type row = 0; row < nrows(); ++row) {
510 rowinfo(row).offset[mi.base.bv] += extra_offset;
511 docstring const nl = nicelabel(row);
515 mathed_string_dim(mi.base.font, nl, dimnl);
516 int const ind = indent(*mi.base.bv);
517 int const x = ind ? ind : (mi.base.textwidth - dim.wid) / 2;
518 // for some reason metrics does not trigger at the
519 // same point as draw, and therefore we use >= instead of >
520 if ((math_number == BufferParams::LEFT && dimnl.wid >= x)
521 || (math_number == BufferParams::RIGHT
522 && dimnl.wid >= mi.base.textwidth - x - dim.wid)) {
523 extra_offset += dimnl.height();
526 dim.des += extra_offset;
531 dim.asc += top_display_margin;
532 dim.des += bottom_display_margin;
535 // reserve some space for marker.
540 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
542 BufferView const * const bv = pi.base.bv;
543 if (previewState(bv)) {
544 Dimension const dim = dimension(*pi.base.bv);
545 if (previewTooSmall(dim))
547 return graphics::PreviewLoader::backgroundColor();
553 void InsetMathHull::drawMarkers(PainterInfo & pi, int x, int y) const
555 ColorCode pen_color = mouseHovered(pi.base.bv) || editing(pi.base.bv)?
556 Color_mathframe : Color_mathcorners;
557 // If the corners have the same color as the background, do not paint them.
558 if (lcolor.getX11HexName(Color_mathbg) == lcolor.getX11HexName(pen_color))
561 Inset::drawMarkers(pi, x, y);
562 Dimension const dim = dimension(*pi.base.bv);
563 int const t = x + dim.width() - 1;
564 int const a = y - dim.ascent();
565 pi.pain.line(x, a + 3, x, a, pen_color);
566 pi.pain.line(t, a + 3, t, a, pen_color);
567 pi.pain.line(x, a, x + 3, a, pen_color);
568 pi.pain.line(t - 3, a, t, a, pen_color);
572 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
574 Dimension const dim = dimension(*pi.base.bv);
575 if (previewTooSmall(dim)) {
576 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
577 dim.wid, dim.asc + dim.des, backgroundColor(pi));
581 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
582 dim.height() - 1, pi.backgroundColor(this));
586 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
588 BufferView const * const bv = pi.base.bv;
589 Dimension const dim = dimension(*bv);
591 if (type_ == hullRegexp)
592 pi.pain.rectangle(x + 2, y - dim.ascent() + 1,
593 dim.width() - 3, dim.height() - 2, Color_regexpframe);
595 if (previewState(bv)) {
596 // Do not draw change tracking cue if taken care of by RowPainter
598 Changer dummy = !canPaintChange(*bv) ? changeVar(pi.change, Change())
600 if (previewTooSmall(dim)) {
601 // we have an extra frame
602 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
604 // one pixel gap in front
605 // value was hardcoded to 1 pixel
606 int const gap = pi.base.bv->zoomedPixels(1) ;
607 preview_->draw(pi, x + gap, y);
612 // First draw the numbers
613 if (numberedType()) {
614 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
615 for (row_type row = 0; row < nrows(); ++row) {
616 int yy = y + rowinfo(row).offset[bv];
617 docstring const nl = nicelabel(row);
619 mathed_string_dim(pi.base.font, nl, dimnl);
620 if (math_number == BufferParams::LEFT) {
621 ColorCode const col = pi.selected_left
622 ? Color_selectiontext
623 : pi.base.font.color();
624 Changer dummy0 = pi.base.font.changeColor(col);
625 if (dimnl.wid > x - pi.leftx)
626 yy += rowinfo(row).descent + dimnl.asc;
627 pi.pain.fillRectangle(pi.leftx, yy - dimnl.asc,
628 dimnl.width(), dimnl.height(),
629 pi.selected_left ? Color_selection : pi.background_color);
630 pi.draw(pi.leftx, yy, nl);
632 ColorCode const col = pi.selected_right
633 ? Color_selectiontext
634 : pi.base.font.color();
635 Changer dummy0 = pi.base.font.changeColor(col);
636 if (dimnl.wid > pi.rightx - x - dim.wid)
637 yy += rowinfo(row).descent + dimnl.asc;
638 pi.pain.fillRectangle(pi.rightx - dimnl.wid, yy - dimnl.asc,
639 dimnl.width(), dimnl.height(),
640 pi.selected_right ? Color_selection : pi.background_color);
641 pi.draw(pi.rightx - dimnl.wid, yy, nl);
646 // Then the equations
647 ColorCode color = pi.selected && lyxrc.use_system_colors
648 ? Color_selectiontext : standardColor();
649 bool const really_change_color = pi.base.font.color() == Color_none;
650 Changer dummy0 = really_change_color ? pi.base.font.changeColor(color)
652 Changer dummy1 = pi.base.changeFontSet(standardFont());
653 Changer dummy2 = pi.base.font.changeStyle(display() ? DISPLAY_STYLE
655 InsetMathGrid::draw(pi, x + 1, y);
656 drawMarkers(pi, x, y);
658 // drawing change line
659 if (canPaintChange(*bv)) {
661 int const display_margin = display() ? pi.base.inPixels(Length(12, Length::PT)) : 0;
662 pi.change.paintCue(pi, x + 1, y + 1 - dim.asc + display_margin,
663 x + dim.wid, y + dim.des - display_margin);
668 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
671 InsetMathGrid::metricsT(mi, dim);
674 otexrowstream ots(os);
675 TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault);
677 dim.wid = os.str().size();
684 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
687 InsetMathGrid::drawT(pain, x, y);
690 otexrowstream ots(os);
691 TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault);
693 pain.draw(x, y, os.str().c_str());
698 static docstring latexString(InsetMathHull const & inset)
701 // This has to be static, because a preview snippet or a math
702 // macro containing math in text mode (such as $\text{$\phi$}$ or
703 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
704 // first time as a whole, and the second time only the inner math.
705 // In this last case inset.buffer() would be invalid.
706 static Encoding const * encoding = 0;
707 if (inset.isBufferValid())
708 encoding = &(inset.buffer().params().encoding());
709 otexrowstream ots(ls);
710 TeXMathStream wi(ots, false, true, TeXMathStream::wsPreview, encoding);
716 void InsetMathHull::initUnicodeMath() const
718 // Trigger classification of the unicode symbols in this inset
719 docstring const dummy = latexString(*this);
723 void InsetMathHull::addPreview(DocIterator const & inset_pos,
724 graphics::PreviewLoader & /*ploader*/) const
726 if (RenderPreview::previewMath()) {
727 preparePreview(inset_pos);
732 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
733 MacroNameSet & macros, MacroNameSet & defs) const
735 MacroNameSet::iterator const end = macros.end();
737 for (size_t i = 0; i < md.size(); ++i) {
738 InsetMathMacro const * mi = md[i].nucleus()->asMacro();
739 InsetMathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
740 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
741 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
742 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
743 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
745 // Look for macros in the arguments of this macro.
746 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
747 usedMacros(mi->cell(idx), pos, macros, defs);
748 // Make sure this is a macro defined in the document
749 // (as we also spot the macros in the symbols file)
750 // or that we have not already accounted for it.
751 docstring const name = mi->name();
752 if (macros.find(name) == end)
755 // Look for macros in the definition of this macro.
756 MathData ar(pos.buffer());
757 MacroData const * data =
758 pos.buffer()->getMacro(name, pos, true);
760 odocstringstream macro_def;
761 data->write(macro_def, true);
763 defs.insert(macro_def.str());
764 asArray(data->definition(), ar);
766 usedMacros(ar, pos, macros, defs);
768 MathData ar(pos.buffer());
769 asArray(mt->definition(), ar);
770 usedMacros(ar, pos, macros, defs);
772 if (!si->nuc().empty())
773 usedMacros(si->nuc(), pos, macros, defs);
775 usedMacros(si->down(), pos, macros, defs);
777 usedMacros(si->up(), pos, macros, defs);
778 } else if (fi || gi) {
779 idx_type nidx = fi ? fi->nargs() : gi->nargs();
780 for (idx_type idx = 0; idx < nidx; ++idx)
781 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
784 usedMacros(ni->cell(0), pos, macros, defs);
790 void InsetMathHull::preparePreview(DocIterator const & pos,
791 bool forexport) const
793 // there is no need to do all the macro stuff if we're not
794 // actually going to generate the preview.
795 if (!RenderPreview::previewMath() && !forexport)
798 Buffer const * buffer = pos.buffer();
800 // collect macros at this position
802 buffer->listMacroNames(macros);
804 // collect definitions only for the macros used in this inset
806 for (idx_type idx = 0; idx < nargs(); ++idx)
807 usedMacros(cell(idx), pos, macros, defs);
809 docstring macro_preamble;
810 for (auto const & defvar : defs)
811 macro_preamble.append(defvar);
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');
828 docstring const snippet = macro_preamble + setfont + latexString(*this) + endfont;
829 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
830 preview_->addPreview(snippet, *buffer, forexport);
834 void InsetMathHull::reloadPreview(DocIterator const & pos) const
837 preview_->startLoading(*pos.buffer());
841 void InsetMathHull::loadPreview(DocIterator const & pos) const
843 bool const forexport = true;
844 preparePreview(pos, forexport);
845 preview_->startLoading(*pos.buffer(), forexport);
849 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
851 if (RenderPreview::previewMath()) {
853 cur.screenUpdateFlags(Update::Force);
859 docstring InsetMathHull::label(row_type row) const
861 LASSERT(row < nrows(), return docstring());
862 if (InsetLabel * il = label_[row])
863 return il->screenLabel();
868 void InsetMathHull::label(row_type row, docstring const & label)
870 //lyxerr << "setting label '" << label << "' for row " << row << endl;
874 label_[row] = dummy_pointer;
877 label_[row]->updateLabelAndRefs(label);
879 label_[row]->setParam("name", label);
883 InsetCommandParams p(LABEL_CODE);
885 label_[row] = new InsetLabel(buffer_, p);
887 label_[row]->setBuffer(buffer());
891 void InsetMathHull::numbered(row_type row, Numbered num)
893 numbered_[row] = num;
897 bool InsetMathHull::numbered(row_type row) const
899 return numbered_[row] == NUMBER;
903 bool InsetMathHull::ams() const
923 for (auto const & row : numbered_)
930 bool InsetMathHull::outerDisplay() const
953 int InsetMathHull::rowFlags() const
970 if (buffer().params().is_math_indent)
971 return Display | AlignLeft;
980 int InsetMathHull::indent(BufferView const & bv) const
982 // FIXME: set this in the textclass. This value is what the article class uses.
983 static Length default_indent(2.5, Length::EM);
984 if (display() && buffer().params().is_math_indent) {
985 Length const & len = buffer().params().getMathIndent();
987 return bv.inPixels(default_indent);
989 return bv.inPixels(len);
991 return Inset::indent(bv);
995 bool InsetMathHull::numberedType() const
1014 for (row_type row = 0; row < nrows(); ++row)
1021 void InsetMathHull::validate(LaTeXFeatures & features) const
1023 if (features.runparams().isLaTeX()) {
1025 features.require("amsmath");
1027 if (type_ == hullRegexp) {
1028 features.require("color");
1029 docstring frcol = from_utf8(lcolor.getLaTeXName(Color_regexpframe));
1030 docstring bgcol = from_ascii("white");
1031 features.addPreambleSnippet(
1032 "\\newcommand{\\regexp}[1]{\\fcolorbox{"
1034 + bgcol + "}{\\ensuremath{\\mathtt{#1}}}}");
1035 features.addPreambleSnippet(
1036 from_ascii("\\newcommand{\\endregexp}{}"));
1037 } else if (outerDisplay() && features.inDeletedInset()) {
1038 features.require("tikz");
1039 features.require("ct-tikz-object-sout");
1042 // Validation is necessary only if not using AMS math.
1043 // To be safe, we will always run mathedvalidate.
1044 //if (features.amsstyle)
1047 //features.binom = true;
1048 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
1049 // it would be better to do this elsewhere, but we can't validate in
1050 // InsetMathMatrix and we have no way, outside MathExtern, to know if
1051 // we even have any matrices.
1052 features.addCSSSnippet(
1053 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
1054 "table.matrix td{padding: 0.25px;}\n"
1055 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
1056 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
1058 InsetMathGrid::validate(features);
1062 CtObject InsetMathHull::getCtObject(OutputParams const & runparams) const
1064 CtObject res = CtObject::Normal;
1080 case hullMultline: {
1081 if (runparams.inulemcmd
1082 && (!runparams.local_font || runparams.local_font->fontInfo().strikeout() != FONT_ON))
1083 res = CtObject::UDisplayObject;
1085 res = CtObject::DisplayObject;
1093 void InsetMathHull::header_write(TeXMathStream & os) const
1095 bool n = numberedType();
1106 if (cell(0).empty())
1111 writeMathdisplayPreamble(os);
1115 os << "\\begin{equation" << star(n) << "}\n";
1125 writeMathdisplayPreamble(os);
1128 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1135 os << "\\begin{" << hullName(type_) << star(n) << '}'
1136 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1142 os << "\\begin{" << hullName(type_) << '}'
1143 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1153 os << "\\begin{unknown" << star(n) << "}\n";
1159 void InsetMathHull::footer_write(TeXMathStream & os) const
1161 bool n = numberedType();
1178 os << "\\end{equation" << star(n) << "}\n";
1181 writeMathdisplayPostamble(os);
1191 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1192 writeMathdisplayPostamble(os);
1199 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1205 os << "\\end{" << hullName(type_) << "}\n";
1209 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1210 os << "\\endregexp{}}";
1216 os << "\\end{unknown" << star(n) << "}\n";
1222 bool InsetMathHull::allowsTabularFeatures() const
1245 bool InsetMathHull::rowChangeOK() const
1248 type_ == hullEqnArray || type_ == hullAlign ||
1249 type_ == hullFlAlign || type_ == hullAlignAt ||
1250 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1251 type_ == hullGather || type_ == hullMultline;
1255 bool InsetMathHull::colChangeOK() const
1258 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1259 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1263 void InsetMathHull::addRow(row_type row)
1268 bool numbered = numberedType();
1269 // Move the number and raw pointer, do not call label() (bug 7511)
1270 InsetLabel * label = dummy_pointer;
1271 docstring number = empty_docstring();
1272 if (type_ == hullMultline) {
1273 if (row + 1 == nrows()) {
1274 numbered_[row] = NONUMBER;
1275 swap(label, label_[row]);
1276 swap(number, numbers_[row]);
1281 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1282 numbers_.insert(numbers_.begin() + row + 1, number);
1283 label_.insert(label_.begin() + row + 1, label);
1284 InsetMathGrid::addRow(row);
1288 void InsetMathHull::swapRow(row_type row)
1292 if (row + 1 == nrows())
1294 swap(numbered_[row], numbered_[row + 1]);
1295 swap(numbers_[row], numbers_[row + 1]);
1296 swap(label_[row], label_[row + 1]);
1297 InsetMathGrid::swapRow(row);
1301 void InsetMathHull::delRow(row_type row)
1303 if (nrows() <= 1 || !rowChangeOK())
1305 if (row + 1 == nrows() && type_ == hullMultline) {
1306 swap(numbered_[row - 1], numbered_[row]);
1307 swap(numbers_[row - 1], numbers_[row]);
1308 swap(label_[row - 1], label_[row]);
1309 InsetMathGrid::delRow(row);
1312 InsetMathGrid::delRow(row);
1313 // The last dummy row has no number info nor a label.
1314 // Test nrows() + 1 because we have already erased the row.
1315 if (row == nrows() + 1)
1317 numbered_.erase(numbered_.begin() + row);
1318 numbers_.erase(numbers_.begin() + row);
1320 label_.erase(label_.begin() + row);
1324 void InsetMathHull::addCol(col_type col)
1328 InsetMathGrid::addCol(col);
1332 void InsetMathHull::delCol(col_type col)
1334 if (ncols() <= 1 || !colChangeOK())
1336 InsetMathGrid::delCol(col);
1340 docstring InsetMathHull::nicelabel(row_type row) const
1342 if (!numbered(row)) {
1345 return '[' + label_[row]->screenLabel() + ']';
1347 docstring const & val = numbers_[row];
1349 return '(' + val + ')';
1350 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1354 void InsetMathHull::glueall(HullType type)
1357 for (idx_type i = 0; i < nargs(); ++i)
1359 InsetLabel * label = 0;
1360 if (type == hullEquation) {
1361 // preserve first non-empty label
1362 for (row_type row = 0; row < nrows(); ++row) {
1364 label = label_[row];
1370 *this = InsetMathHull(buffer_, hullSimple);
1377 void InsetMathHull::splitTo2Cols()
1379 LASSERT(ncols() == 1, return);
1380 InsetMathGrid::addCol(1);
1381 for (row_type row = 0; row < nrows(); ++row) {
1382 idx_type const i = 2 * row;
1383 pos_type pos = firstRelOp(cell(i));
1384 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1385 cell(i).erase(pos, cell(i).size());
1390 void InsetMathHull::splitTo3Cols()
1392 LASSERT(ncols() < 3, return);
1395 InsetMathGrid::addCol(2);
1396 for (row_type row = 0; row < nrows(); ++row) {
1397 idx_type const i = 3 * row + 1;
1398 if (!cell(i).empty()) {
1399 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1400 cell(i).erase(1, cell(i).size());
1406 void InsetMathHull::changeCols(col_type cols)
1408 if (ncols() == cols)
1410 else if (ncols() < cols) {
1416 while (ncols() < cols)
1417 InsetMathGrid::addCol(ncols());
1423 for (row_type row = 0; row < nrows(); ++row) {
1424 idx_type const i = row * ncols();
1425 for (col_type col = cols; col < ncols(); ++col) {
1426 cell(i + cols - 1).append(cell(i + col));
1430 while (ncols() > cols) {
1431 InsetMathGrid::delCol(ncols() - 1);
1436 HullType InsetMathHull::getType() const
1442 void InsetMathHull::setType(HullType type)
1449 bool InsetMathHull::isMutable(HullType type)
1473 void InsetMathHull::mutate(HullType newtype)
1475 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1477 if (newtype == type_)
1480 // This guards the algorithm below it, which is designed with certain types
1482 if (!isMutable(newtype) || !isMutable(type_)) {
1483 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1484 << "' to '" << to_utf8(hullName(newtype))
1485 << "' not implemented" << endl;
1489 // we try to move along the chain
1490 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1492 // +-------------------------------------+
1493 // we use eqnarray as intermediate type for mutations that are not
1494 // directly supported because it handles labels and numbering for
1499 setType(hullSimple);
1505 if (newtype == hullNone) {
1509 setType(hullEquation);
1510 numbered(0, label_[0] != nullptr);
1519 setType(hullSimple);
1524 // split it "nicely" on the first relop
1526 setType(hullEqnArray);
1534 // split it "nicely"
1569 setType(hullEqnArray);
1578 for (row_type row = 0; row < nrows(); ++row)
1579 numbered(row, false);
1589 for (row_type row = 0; row < nrows(); ++row)
1590 numbered(row, false);
1597 setType(hullEqnArray);
1627 for (row_type row = 0; row < nrows(); ++row)
1628 numbered(row, false);
1632 // first we mutate to EqnArray
1634 setType(hullEqnArray);
1641 // we passed the guard so we should not be here
1642 LYXERR0("Mutation not implemented, but should have been.");
1643 LASSERT(false, return);
1649 void InsetMathHull::eol(TeXMathStream & os, row_type row, bool fragile, bool latex,
1650 bool last_eoln) const
1652 if (numberedType()) {
1654 docstring const name =
1655 latex ? escape(label_[row]->getParam("name"))
1656 : label_[row]->getParam("name");
1657 os << "\\label{" + name + '}';
1659 if (type_ != hullMultline) {
1660 if (numbered_[row] == NONUMBER)
1661 os << "\\nonumber ";
1662 else if (numbered_[row] == NOTAG)
1665 if (os.output() == TeXMathStream::wsPreview && !numbers_[row].empty()) {
1666 os << "\\global\\def\\theequation{" << numbers_[row] << "}\n";
1670 // Never add \\ on the last empty line of eqnarray and friends
1672 InsetMathGrid::eol(os, row, fragile, latex, last_eoln);
1675 void InsetMathHull::write(TeXMathStream & os) const
1677 ModeSpecifier specifier(os, MATH_MODE);
1679 InsetMathGrid::write(os);
1684 void InsetMathHull::normalize(NormalStream & os) const
1686 os << "[formula " << hullName(type_) << ' ';
1687 InsetMathGrid::normalize(os);
1692 void InsetMathHull::infoize(odocstream & os) const
1694 os << bformat(_("Type: %1$s"), hullName(type_));
1698 void InsetMathHull::check() const
1700 LATTEST(numbered_.size() == nrows());
1701 LATTEST(numbers_.size() == nrows());
1702 LATTEST(label_.size() == nrows());
1706 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1708 //FIXME: sort out whether we want std::string or docstring for those
1709 string const lang = func.getArg(0);
1710 docstring extra = from_utf8(func.getArg(1));
1712 extra = from_ascii("noextra");
1714 // replace selection with result of computation
1715 if (reduceSelectionToOneCell(cur)) {
1717 asArray(grabAndEraseSelection(cur), ar);
1718 lyxerr << "use selection: " << ar << endl;
1719 cur.insert(pipeThroughExtern(lang, extra, ar));
1723 // only inline, display or eqnarray math is allowed
1724 switch (getType()) {
1730 frontend::Alert::warning(_("Bad math environment"),
1731 _("Computation cannot be performed for AMS "
1732 "math environments.\nChange the math "
1733 "formula type and try again."));
1738 eq.push_back(MathAtom(new InsetMathChar('=')));
1740 // go to first item in line
1741 cur.idx() -= cur.idx() % ncols();
1744 if (getType() == hullSimple) {
1745 size_type pos = cur.cell().find_last(eq);
1747 if (pos == cur.cell().size()) {
1749 lyxerr << "use whole cell: " << ar << endl;
1751 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1752 lyxerr << "use partial cell form pos: " << pos << endl;
1754 cur.cell().append(eq);
1755 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1756 cur.pos() = cur.lastpos();
1760 if (getType() == hullEquation) {
1761 lyxerr << "use equation inset" << endl;
1762 mutate(hullEqnArray);
1763 MathData & ar = cur.cell();
1764 lyxerr << "use cell: " << ar << endl;
1768 cur.cell() = pipeThroughExtern(lang, extra, ar);
1769 // move to end of line
1770 cur.pos() = cur.lastpos();
1775 lyxerr << "use eqnarray" << endl;
1776 cur.idx() += 2 - cur.idx() % ncols();
1778 MathData ar = cur.cell();
1779 lyxerr << "use cell: " << ar << endl;
1780 // FIXME: temporarily disabled
1786 cur.cell() = pipeThroughExtern(lang, extra, ar);
1787 cur.pos() = cur.lastpos();
1792 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1794 //lyxerr << "action: " << cmd.action() << endl;
1795 switch (cmd.action()) {
1797 case LFUN_FINISHED_BACKWARD:
1798 case LFUN_FINISHED_FORWARD:
1799 case LFUN_FINISHED_RIGHT:
1800 case LFUN_FINISHED_LEFT:
1801 //lyxerr << "action: " << cmd.action() << endl;
1802 InsetMathGrid::doDispatch(cur, cmd);
1805 case LFUN_PARAGRAPH_BREAK:
1806 // just swallow this
1809 case LFUN_NEWLINE_INSERT:
1810 // some magic for the common case
1811 if (type_ == hullSimple || type_ == hullEquation) {
1812 cur.recordUndoInset();
1814 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1815 mutate(align ? hullAlign : hullEqnArray);
1816 // mutate() may change labels and such.
1817 cur.forceBufferUpdate();
1818 cur.idx() = nrows() * ncols() - 1;
1819 cur.pos() = cur.lastpos();
1821 InsetMathGrid::doDispatch(cur, cmd);
1824 case LFUN_MATH_NUMBER_TOGGLE: {
1825 //lyxerr << "toggling all numbers" << endl;
1826 cur.recordUndoInset();
1827 bool old = numberedType();
1828 if (type_ == hullMultline) {
1829 row_type row = nrows() - 1;
1830 numbered(row, !old);
1831 if (old && label_[row]) {
1836 for (row_type row = 0; row < nrows(); ++row) {
1837 numbered(row, !old);
1838 if (old && label_[row]) {
1845 cur.message(old ? _("No number") : _("Number"));
1846 cur.forceBufferUpdate();
1850 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1851 cur.recordUndoInset();
1852 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1853 bool old = numbered(r);
1854 cur.message(old ? _("No number") : _("Number"));
1856 if (old && label_[r]) {
1860 cur.forceBufferUpdate();
1864 case LFUN_LABEL_INSERT: {
1865 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1866 docstring old_label = label(r);
1867 docstring const default_label = from_ascii("eq:");
1868 if (old_label.empty())
1869 old_label = default_label;
1871 InsetCommandParams p(LABEL_CODE);
1872 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1873 string const data = InsetCommand::params2string(p);
1875 if (cmd.argument().empty())
1876 cur.bv().showDialog("label", data);
1878 FuncRequest fr(LFUN_INSET_INSERT, data);
1884 case LFUN_LABEL_COPY_AS_REFERENCE: {
1886 if (cmd.argument().empty() && &cur.inset() == this)
1887 // if there is no argument and we're inside math, we retrieve
1888 // the row number from the cursor position.
1889 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1891 // if there is an argument, find the corresponding label, else
1892 // check whether there is at least one label.
1893 for (row = 0; row != nrows(); ++row)
1895 && (cmd.argument().empty() || label(row) == cmd.argument()))
1902 InsetCommandParams p(REF_CODE, "ref");
1903 p["reference"] = label(row);
1904 cap::clearSelection();
1905 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1909 case LFUN_WORD_DELETE_FORWARD:
1910 case LFUN_CHAR_DELETE_FORWARD:
1911 if (col(cur.idx()) + 1 == ncols()
1912 && cur.pos() == cur.lastpos()
1913 && !cur.selection()) {
1914 if (!label(row(cur.idx())).empty()) {
1915 cur.recordUndoInset();
1916 label(row(cur.idx()), docstring());
1917 } else if (numbered(row(cur.idx()))) {
1918 cur.recordUndoInset();
1919 numbered(row(cur.idx()), false);
1920 cur.forceBufferUpdate();
1922 InsetMathGrid::doDispatch(cur, cmd);
1926 InsetMathGrid::doDispatch(cur, cmd);
1931 case LFUN_INSET_INSERT: {
1932 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1933 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1934 string const name = cmd.getArg(0);
1935 if (name == "label") {
1936 InsetCommandParams p(LABEL_CODE);
1937 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1938 docstring str = p["name"];
1939 cur.recordUndoInset();
1940 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1944 docstring old = label(r);
1947 // The label will take care of the reference update.
1951 // Newly created inset so initialize it.
1952 label_[r]->initView();
1955 cur.forceBufferUpdate();
1958 InsetMathGrid::doDispatch(cur, cmd);
1962 case LFUN_MATH_EXTERN:
1963 cur.recordUndoInset();
1967 case LFUN_MATH_MUTATE: {
1968 cur.recordUndoInset();
1969 row_type row = cur.row();
1970 col_type col = cur.col();
1971 mutate(hullType(cmd.argument()));
1972 cur.idx() = row * ncols() + col;
1973 if (cur.idx() > cur.lastidx()) {
1974 cur.idx() = cur.lastidx();
1975 cur.pos() = cur.lastpos();
1977 if (cur.pos() > cur.lastpos())
1978 cur.pos() = cur.lastpos();
1980 cur.forceBufferUpdate();
1981 // FIXME: find some more clever handling of the selection,
1982 // i.e. preserve it.
1983 cur.clearSelection();
1984 //cur.dispatched(FINISHED);
1988 case LFUN_MATH_DISPLAY: {
1989 cur.recordUndoInset();
1990 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1991 // if the cursor is in a cell that got merged, move it to
1992 // start of the hull inset.
1993 if (cur.idx() > 0) {
1997 if (cur.pos() > cur.lastpos())
1998 cur.pos() = cur.lastpos();
2003 case LFUN_TABULAR_FEATURE:
2004 if (!allowsTabularFeatures())
2007 InsetMathGrid::doDispatch(cur, cmd);
2011 InsetMathGrid::doDispatch(cur, cmd);
2019 bool allowDisplayMath(Cursor const & cur)
2021 LATTEST(cur.depth() > 1);
2022 Cursor tmpcur = cur;
2025 FuncRequest cmd(LFUN_MATH_DISPLAY);
2026 return tmpcur.getStatus(cmd, status) && status.enabled();
2032 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
2033 FuncStatus & status) const
2035 switch (cmd.action()) {
2036 case LFUN_FINISHED_BACKWARD:
2037 case LFUN_FINISHED_FORWARD:
2038 case LFUN_FINISHED_RIGHT:
2039 case LFUN_FINISHED_LEFT:
2042 case LFUN_NEWLINE_INSERT:
2043 case LFUN_MATH_EXTERN:
2045 status.setEnabled(true);
2048 // we never allow this in math, and we want to bind enter
2049 // to another actions in command-alternatives
2050 case LFUN_PARAGRAPH_BREAK:
2051 status.setEnabled(false);
2053 case LFUN_MATH_MUTATE: {
2054 HullType const ht = hullType(cmd.argument());
2055 status.setOnOff(type_ == ht);
2056 status.setEnabled(isMutable(ht) && isMutable(type_));
2058 if (ht != hullSimple && status.enabled())
2059 status.setEnabled(allowDisplayMath(cur));
2062 case LFUN_MATH_DISPLAY: {
2063 status.setEnabled(display() || allowDisplayMath(cur));
2064 status.setOnOff(display());
2068 case LFUN_MATH_NUMBER_TOGGLE:
2069 // FIXME: what is the right test, this or the one of
2071 status.setEnabled(display());
2072 status.setOnOff(numberedType());
2075 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
2076 // FIXME: what is the right test, this or the one of
2078 bool const enable = (type_ == hullMultline)
2079 ? (nrows() - 1 == cur.row())
2081 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2082 status.setEnabled(enable);
2083 status.setOnOff(enable && numbered(r));
2087 case LFUN_LABEL_INSERT:
2088 status.setEnabled(type_ != hullSimple);
2091 case LFUN_LABEL_COPY_AS_REFERENCE: {
2092 bool enabled = false;
2093 if (cmd.argument().empty() && &cur.inset() == this) {
2094 // if there is no argument and we're inside math, we retrieve
2095 // the row number from the cursor position.
2096 row_type row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2097 enabled = numberedType() && label_[row];
2099 // if there is an argument, find the corresponding label, else
2100 // check whether there is at least one label.
2101 for (row_type row = 0; row != nrows(); ++row) {
2103 (cmd.argument().empty() || label(row) == cmd.argument())) {
2109 status.setEnabled(enabled);
2113 case LFUN_INSET_INSERT:
2114 if (cmd.getArg(0) == "label") {
2115 status.setEnabled(type_ != hullSimple);
2118 return InsetMathGrid::getStatus(cur, cmd, status);
2120 case LFUN_TABULAR_FEATURE: {
2121 if (!allowsTabularFeatures())
2123 string s = cmd.getArg(0);
2125 && (s == "append-row"
2126 || s == "delete-row"
2127 || s == "copy-row")) {
2128 status.message(bformat(
2129 from_utf8(N_("Can't change number of rows in '%1$s'")),
2131 status.setEnabled(false);
2135 && (s == "append-column"
2136 || s == "delete-column"
2137 || s == "copy-column")) {
2138 status.message(bformat(
2139 from_utf8(N_("Can't change number of columns in '%1$s'")),
2141 status.setEnabled(false);
2144 if (s == "add-vline-left" || s == "add-vline-right") {
2145 status.message(bformat(
2146 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2148 status.setEnabled(false);
2151 if (s == "valign-top" || s == "valign-middle"
2152 || s == "valign-bottom" || s == "align-left"
2153 || s == "align-center" || s == "align-right") {
2154 status.setEnabled(false);
2157 return InsetMathGrid::getStatus(cur, cmd, status);
2161 return InsetMathGrid::getStatus(cur, cmd, status);
2166 int InsetMathHull::leftMargin() const
2168 return (getType() == hullSimple) ? 0 : InsetMathGrid::leftMargin();
2172 int InsetMathHull::rightMargin() const
2174 return (getType() == hullSimple) ? 0 : InsetMathGrid::rightMargin();
2178 int InsetMathHull::border() const
2180 return (getType() == hullSimple) ? 0 : InsetMathGrid::border();
2184 /////////////////////////////////////////////////////////////////////
2188 // simply scrap this function if you want
2189 void InsetMathHull::mutateToText()
2192 // translate to latex
2194 latex(os, false, false);
2195 string str = os.str();
2198 Text * lt = view_->cursor().innerText();
2199 string::const_iterator cit = str.begin();
2200 string::const_iterator end = str.end();
2201 for (; cit != end; ++cit)
2202 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2205 //dispatch(LFUN_ESCAPE);
2210 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2211 docstring const & font)
2213 // this whole function is a hack and won't work for incremental font
2216 if (cur.inset().asInsetMath()->name() == font)
2217 cur.handleFont(to_utf8(font));
2219 cur.handleNest(createInsetMath(font, cur.buffer()));
2225 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2230 font.fromString(to_utf8(arg), b);
2231 if (font.fontInfo().color() != Color_inherit) {
2232 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2238 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2241 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
2242 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
2243 enter_front ? idxFirst(cur) : idxLast(cur);
2244 // The inset formula dimension is not necessarily the same as the
2245 // one of the instant preview image, so we have to indicate to the
2246 // BufferView that a metrics update is needed.
2247 cur.screenUpdateFlags(Update::Force);
2251 /////////////////////////////////////////////////////////////////////
2255 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2258 // FIXME: completely broken
2259 static InsetMathHull * lastformula = 0;
2260 static CursorBase current = DocIterator(ibegin(nucleus()));
2262 static string laststr;
2264 if (lastformula != this || laststr != str) {
2265 //lyxerr << "reset lastformula to " << this << endl;
2268 current = ibegin(nucleus());
2270 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2274 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2276 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2277 CursorSlice & top = it.back();
2278 MathData const & a = top.asInsetMath()->cell(top.idx_);
2279 if (a.matchpart(ar, top.pos_)) {
2280 bv->cursor().setSelection(it, ar.size());
2282 top.pos_ += ar.size();
2288 //lyxerr << "not found!" << endl;
2295 void InsetMathHull::write(ostream & os) const
2297 odocstringstream oss;
2298 otexrowstream ots(oss);
2299 TeXMathStream wi(ots, false, false, TeXMathStream::wsDefault);
2302 os << to_utf8(oss.str());
2306 void InsetMathHull::read(Lexer & lex)
2309 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2310 operator=(*at->asHullInset());
2314 bool InsetMathHull::readQuiet(Lexer & lex)
2317 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2319 operator=(*at->asHullInset());
2324 int InsetMathHull::plaintext(odocstringstream & os,
2325 OutputParams const & op, size_t max_length) const
2327 // Try enabling this now that there is a flag as requested at #2275.
2328 if (buffer().isExporting() && display()) {
2332 TextPainter tpain(dim.width(), dim.height());
2333 drawT(tpain, 0, dim.ascent());
2335 // reset metrics cache to "real" values
2337 return tpain.textheight();
2340 odocstringstream oss;
2341 otexrowstream ots(oss);
2342 Encoding const * const enc = encodings.fromLyXName("utf8");
2344 TeXMathStream::OutputType ot;
2345 if (op.find_effective())
2346 ot = TeXMathStream::wsSearchAdv;
2348 ot = TeXMathStream::wsDefault;
2350 if (type_ == hullRegexp) {
2351 TeXMathStream wi(ots, false, true, ot, enc);
2355 TeXMathStream wi(ots, false, true, ot, enc);
2356 for (row_type r = 0; r < nrows(); ++r) {
2357 for (col_type c = 0; c < ncols(); ++c)
2358 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2359 // if it's for the TOC, we write just the first line
2360 // and do not include the newline.
2361 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2363 if (r < nrows() - 1)
2367 docstring const str = oss.str();
2373 void InsetMathHull::docbook(XMLStream & xs, OutputParams const & runparams) const {
2374 // Choose the tag around the MathML equation.
2377 if (getType() == hullSimple)
2378 name = from_ascii("inlineequation");
2380 doCR = true; // This is a block equation, always have <informalequation> on its own line.
2381 name = from_ascii("informalequation");
2384 // DocBook also has <equation>, but it comes with a title.
2385 // TODO: recognise \tag from amsmath? This would allow having <equation> with a proper title.
2389 bool mathmlNamespaceInline = buffer().params().docbook_mathml_prefix == BufferParams::NoPrefix;
2390 if (mathmlNamespaceInline)
2391 attr += "xmlns=\"http://www.w3.org/1998/Math/MathML\"";
2393 for (row_type i = 0; i < nrows(); ++i) {
2394 if (!label(i).empty()) {
2398 attr += "xml:id=\"" + xml::cleanID(label(i)) + "\"";
2404 if (!xs.isLastTagCR())
2407 xs << xml::StartTag(name, attr);
2410 // With DocBook 5, MathML must be within its own namespace (defined in Buffer.cpp::writeDocBookSource, except when
2411 // it should be inlined).
2412 // Output everything in a separate stream so that this does not interfere with the standard flow of DocBook tags.
2413 std::string mathmlNamespacePrefix;
2414 if (!mathmlNamespaceInline) {
2415 if (buffer().params().docbook_mathml_prefix == BufferParams::MPrefix)
2416 mathmlNamespacePrefix = "m";
2417 else if (buffer().params().docbook_mathml_prefix == BufferParams::MMLPrefix)
2418 mathmlNamespacePrefix = "mml";
2421 odocstringstream osmath;
2422 MathMLStream ms(osmath, mathmlNamespacePrefix, true);
2424 // Output the MathML subtree.
2425 // TeX transcription. Avoid MTag/ETag so that there are no extraneous spaces.
2426 ms << "<" << from_ascii("alt") << " role='tex'" << ">";
2427 // Workaround for db2latex: db2latex always includes equations with
2428 // \ensuremath{} or \begin{display}\end{display}
2429 // so we strip LyX' math environment
2430 odocstringstream ls;
2432 TeXMathStream wi(ols, false, false, TeXMathStream::wsDefault, runparams.encoding);
2433 InsetMathGrid::write(wi);
2434 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2435 ms << "</" << from_ascii("alt") << ">";
2437 // Actual transformation of the formula into MathML. This translation may fail (for example, due to custom macros).
2438 // The new output stream is required to deal with the errors: first write completely the formula into this
2439 // temporary stream; then, if it is possible without error, then copy it back to the "real" stream. Otherwise,
2440 // some incomplete tags might be put into the real stream.
2442 // First, generate the MathML expression. If there is an error in the generation, this block is not fully
2443 // executed, and the formula is not output to the DocBook stream.
2444 odocstringstream ostmp;
2445 MathMLStream mstmp(ostmp, ms.xmlns(), ms.xmlMode());
2448 // Choose the display style for the formula, to be output as an attribute near the formula root.
2449 std::string mathmlAttr;
2450 if (getType() == hullSimple)
2451 mathmlAttr = "display=\"inline\"";
2453 mathmlAttr = "display=\"block\"";
2455 // Then, output the formula.
2456 ms << MTag("math", mathmlAttr);
2458 osmath << ostmp.str(); // osmath is not a XMLStream, so no need for XMLStream::ESCAPE_NONE.
2460 } catch (MathExportException const &) {
2462 osmath << "<mathphrase>MathML export failed. Please report this as a bug to the LyX developers: "
2463 "https://www.lyx.org/trac.</mathphrase>";
2466 // Output the complete formula to the DocBook stream.
2467 xs << XMLStream::ESCAPE_NONE << osmath.str();
2469 xs << xml::EndTag(name);
2475 bool InsetMathHull::haveNumbers() const
2477 bool havenumbers = false;
2478 // inline formulas are never numbered (bug 7351 part 3)
2479 if (getType() == hullSimple)
2481 for (size_t i = 0; i != numbered_.size(); ++i) {
2492 // We need to do something about alignment here.
2494 // This duplicates code from InsetMathGrid, but
2495 // we need access here to number information,
2496 // and we simply do not have that in InsetMathGrid.
2497 void InsetMathHull::htmlize(HtmlStream & os) const
2499 bool const havenumbers = haveNumbers();
2500 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2503 os << cell(index(0, 0));
2507 os << MTag("table", "class='mathtable'");
2508 for (row_type row = 0; row < nrows(); ++row) {
2510 for (col_type col = 0; col < ncols(); ++col) {
2512 os << cell(index(row, col));
2517 docstring const & num = numbers_[row];
2519 os << '(' << num << ')';
2524 os << ETag("table");
2528 // this duplicates code from InsetMathGrid, but
2529 // we need access here to number information,
2530 // and we simply do not have that in InsetMathGrid.
2531 void InsetMathHull::mathmlize(MathMLStream & ms) const
2533 bool const havetable = haveNumbers() || nrows() > 1 || ncols() > 1;
2536 if (getType() == hullSimple) {
2537 ms << MTag("mtable");
2538 } else if (getType() >= hullAlign && getType() <= hullXXAlignAt) {
2540 for (col_type col = 0; col < ncols(); ++col) {
2541 alignment += (col % 2) ? "left " : "right ";
2543 ms << MTag("mtable", "displaystyle='true' columnalign='" + alignment + "'");
2545 ms << MTag("mtable", "displaystyle='true'");
2549 char const * const celltag = havetable ? "mtd" : "mrow";
2550 // FIXME There does not seem to be wide support at the moment
2551 // for mlabeledtr, so we have to use just mtr for now.
2552 // char const * const rowtag = haveNumbers() ? "mlabeledtr" : "mtr";
2553 char const * const rowtag = "mtr";
2554 for (row_type row = 0; row < nrows(); ++row) {
2557 for (col_type col = 0; col < ncols(); ++col) {
2559 << cell(index(row, col))
2563 if (haveNumbers()) {
2565 docstring const & num = numbers_[row];
2567 ms << MTagInline("mtext") << '(' << num << ')' << ETagInline("mtext");
2574 ms << ETag("mtable");
2578 void InsetMathHull::mathAsLatex(TeXMathStream & os) const
2580 MathEnsurer ensurer(os, false);
2581 bool havenumbers = haveNumbers();
2582 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2585 os << cell(index(0, 0));
2589 os << "<table class='mathtable'>";
2590 for (row_type row = 0; row < nrows(); ++row) {
2592 for (col_type col = 0; col < ncols(); ++col) {
2593 os << "<td class='math'>";
2594 os << cell(index(row, col));
2599 docstring const & num = numbers_[row];
2601 os << '(' << num << ')';
2610 docstring InsetMathHull::xhtml(XMLStream & xs, OutputParams const & op) const
2612 BufferParams::MathOutput const mathtype =
2613 buffer().masterBuffer()->params().html_math_output;
2615 bool success = false;
2617 // we output all the labels just at the beginning of the equation.
2618 // this should be fine.
2619 for (size_t i = 0; i != label_.size(); ++i) {
2620 InsetLabel const * const il = label_[i];
2626 // FIXME Eventually we would like to do this inset by inset.
2627 if (mathtype == BufferParams::MathML) {
2628 odocstringstream os;
2629 MathMLStream ms(os);
2633 } catch (MathExportException const &) {}
2635 if (getType() == hullSimple)
2636 xs << xml::StartTag("math",
2637 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2639 xs << xml::StartTag("math",
2640 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2641 xs << XMLStream::ESCAPE_NONE
2643 << xml::EndTag("math");
2645 } else if (mathtype == BufferParams::HTML) {
2646 odocstringstream os;
2651 } catch (MathExportException const &) {}
2653 string const tag = (getType() == hullSimple) ? "span" : "div";
2654 xs << xml::StartTag(tag, "class='formula'", true)
2655 << XMLStream::ESCAPE_NONE
2657 << xml::EndTag(tag);
2661 // what we actually want is this:
2663 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2665 // || mathtype == BufferParams::Images
2667 // but what follows is equivalent, since we'll enter only if either (a) we
2668 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2669 // aren't doing LaTeX.
2671 // so this is for Images.
2672 if (!success && mathtype != BufferParams::LaTeX) {
2673 graphics::PreviewImage const * pimage = 0;
2675 loadPreview(docit_);
2676 pimage = preview_->getPreviewImage(buffer());
2677 // FIXME Do we always have png?
2680 if (pimage || op.dryrun) {
2681 string const filename = pimage ? pimage->filename().onlyFileName()
2682 : "previewimage.png";
2684 // if we are not in the master buffer, then we need to see that the
2685 // generated image is copied there; otherwise, preview fails.
2686 Buffer const * mbuf = buffer().masterBuffer();
2687 if (mbuf != &buffer()) {
2688 string mbtmp = mbuf->temppath();
2689 FileName const mbufimg(support::addName(mbtmp, filename));
2690 pimage->filename().copyTo(mbufimg);
2692 // add the file to the list of files to be exported
2693 op.exportdata->addExternalFile("xhtml", pimage->filename());
2696 string const tag = (getType() == hullSimple) ? "span" : "div";
2698 << xml::StartTag(tag, "style = \"text-align: center;\"")
2699 << xml::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2706 // so we'll pass this test if we've failed everything else, or
2707 // if mathtype was LaTeX, since we won't have entered any of the
2709 if (!success /* || mathtype != BufferParams::LaTeX */) {
2710 // Unfortunately, we cannot use latexString() because we do not want
2711 // $...$ or whatever.
2712 odocstringstream ls;
2713 otexrowstream ots(ls);
2714 TeXMathStream wi(ots, false, true, TeXMathStream::wsPreview);
2715 ModeSpecifier specifier(wi, MATH_MODE);
2717 docstring const latex = ls.str();
2719 // class='math' allows for use of jsMath
2720 // http://www.math.union.edu/~dpvc/jsMath/
2722 // probably should allow for some kind of customization here
2723 string const tag = (getType() == hullSimple) ? "span" : "div";
2724 xs << xml::StartTag(tag, "class='math'")
2733 void InsetMathHull::toString(odocstream & os) const
2735 odocstringstream ods;
2736 plaintext(ods, OutputParams(0));
2741 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2743 odocstringstream ods;
2746 // FIXME: this results in spilling TeX into the LyXHTML output since the
2747 // outliner is used to generate the LyXHTML list of figures/etc.
2753 string InsetMathHull::contextMenuName() const
2755 return "context-math";
2759 void InsetMathHull::recordLocation(DocIterator const & di)
2765 bool InsetMathHull::canPaintChange(BufferView const &) const
2767 // We let RowPainter do it seamlessly for inline insets