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 = nullptr;
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 // compute first and last item
293 row_type first = nrows();
294 for (row_type row = 0; row != nrows(); ++row)
299 if (first == nrows())
302 row_type last = nrows() - 1;
303 for (; last != 0; --last)
307 TocBuilder & b = backend.builder("equation");
308 // add equation numbers
309 b.pushItem(pit, docstring(), output_active);
311 b.argumentItem(bformat(from_ascii("(%1$s-%2$s)"),
312 numbers_[first], numbers_[last]));
313 for (row_type row = 0; row != nrows(); ++row) {
317 label_[row]->setPrettyCounter(_("Equation") + " " + numbers_[row]);
318 label_[row]->setFormattedCounter(_("Equation") + " " + numbers_[row]);
319 label_[row]->addToToc(pit, output_active, utype, backend);
321 docstring label = nicelabel(row);
323 // this is the only equation
324 b.argumentItem(label);
326 // insert as sub-items
327 b.pushItem(pit, label, output_active);
335 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
337 if (previewState(&cur.bv())) {
341 return InsetMathNest::editXY(cur, x, y);
345 InsetMath::mode_type InsetMathHull::currentMode() const
349 return UNDECIDED_MODE;
351 // definitely math mode ...
371 // FIXME: InsetMathGrid should be changed to let the real column alignment be
372 // given by a virtual method like displayColAlign, because the values produced
373 // by defaultColAlign can be invalidated by lfuns such as add-column. For the
374 // moment the values produced by defaultColAlign are not used, notably because
375 // alignment is not implemented in the LyXHTML output.
376 char InsetMathHull::defaultColAlign(col_type col)
378 return colAlign(type_, col);
382 char InsetMathHull::displayColAlign(idx_type idx) const
386 row_type const r = row(idx);
389 if (r == nrows() - 1)
400 return colAlign(type_, col(idx));
404 return InsetMathGrid::displayColAlign(idx);
408 int InsetMathHull::displayColSpace(col_type col) const
410 return colSpace(type_, col);
414 // FIXME: same comment as for defaultColAlign applies.
415 int InsetMathHull::defaultColSpace(col_type col)
417 return colSpace(type_, col);
421 string InsetMathHull::standardFont() const
427 return "lyxnochange";
434 ColorCode InsetMathHull::standardColor() const
439 return Color_foreground;
447 bool InsetMathHull::previewState(const BufferView *const bv) const
449 if (!editing(bv) && RenderPreview::previewMath()
450 && type_ != hullRegexp)
452 graphics::PreviewImage const * pimage =
453 preview_->getPreviewImage(bv->buffer());
454 return pimage && pimage->image();
461 const int ERROR_FRAME_WIDTH = 2;
463 bool previewTooSmall(Dimension const & dim)
465 return dim.width() <= 10 && dim.height() <= 10;
470 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
472 /* Compute \(above|below)displayskip
473 true value in LaTeX is 10pt plus 2pt minus 5pt (in normal size at 10pt)
474 But we use a fixed number of pixels and scale them with zoom.
476 int const bottom_display_margin = mi.base.bv->zoomedPixels(6);
477 int top_display_margin = bottom_display_margin;
478 // at start of paragraph, add an empty line
480 top_display_margin += theFontMetrics(mi.base.font).maxHeight() + 2;
482 int const ind = indent(*mi.base.bv);
485 if (previewState(mi.base.bv)) {
486 preview_->metrics(mi, dim);
487 if (previewTooSmall(dim)) {
488 // preview image is too small
489 dim.wid += 2 * ERROR_FRAME_WIDTH;
490 dim.asc += 2 * ERROR_FRAME_WIDTH;
492 // insert a gap in front of the formula
493 // value was hardcoded to 1 pixel
494 dim.wid += mi.base.bv->zoomedPixels(1) ;
496 dim.asc += top_display_margin;
497 dim.des += bottom_display_margin;
504 Changer dummy1 = mi.base.changeFontSet(standardFont());
505 Changer dummy2 = mi.base.font.changeStyle(display() ? DISPLAY_STYLE
508 // let the cells adjust themselves
509 InsetMathGrid::metrics(mi, dim);
512 // Check whether the numbering interferes with the equations
513 if (numberedType()) {
514 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
515 int extra_offset = 0;
517 for (row_type row = 0; row < nrows(); ++row) {
518 rowinfo(row).offset[mi.base.bv] += extra_offset;
519 docstring const nl = nicelabel(row);
523 mathed_string_dim(mi.base.font, nl, dimnl);
524 int const x = ind ? ind : (mi.base.textwidth - dim.wid) / 2;
525 // for some reason metrics does not trigger at the
526 // same point as draw, and therefore we use >= instead of >
527 if ((math_number == BufferParams::LEFT && dimnl.wid >= x)
528 || (math_number == BufferParams::RIGHT
529 && dimnl.wid >= mi.base.textwidth - x - dim.wid)) {
530 extra_offset += dimnl.height();
531 } else if (dimnl.wid > max_nlwid)
532 max_nlwid = dimnl.wid;
534 mi.extrawidth += max_nlwid;
535 dim.des += extra_offset;
540 dim.asc += top_display_margin;
541 dim.des += bottom_display_margin;
544 // reserve some space for marker.
549 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
551 BufferView const * const bv = pi.base.bv;
552 if (previewState(bv)) {
553 Dimension const dim = dimension(*pi.base.bv);
554 if (previewTooSmall(dim))
556 return graphics::PreviewLoader::backgroundColor();
562 void InsetMathHull::drawMarkers(PainterInfo & pi, int x, int y) const
564 ColorCode pen_color = mouseHovered(pi.base.bv) || editing(pi.base.bv)?
565 Color_mathframe : Color_mathcorners;
566 // If the corners have the same color as the background, do not paint them.
567 if (lcolor.getX11HexName(Color_mathbg) == lcolor.getX11HexName(pen_color))
570 Inset::drawMarkers(pi, x, y);
571 Dimension const dim = dimension(*pi.base.bv);
572 int const t = x + dim.width() - 1;
573 int const a = y - dim.ascent();
574 pi.pain.line(x, a + 3, x, a, pen_color);
575 pi.pain.line(t, a + 3, t, a, pen_color);
576 pi.pain.line(x, a, x + 3, a, pen_color);
577 pi.pain.line(t - 3, a, t, a, pen_color);
581 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
583 Dimension const dim = dimension(*pi.base.bv);
584 if (previewTooSmall(dim)) {
585 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
586 dim.wid, dim.asc + dim.des, backgroundColor(pi));
590 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
591 dim.height() - 1, pi.backgroundColor(this));
595 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
597 BufferView const * const bv = pi.base.bv;
598 Dimension const dim = dimension(*bv);
600 if (type_ == hullRegexp)
601 pi.pain.rectangle(x + 2, y - dim.ascent() + 1,
602 dim.width() - 3, dim.height() - 2, Color_regexpframe);
604 if (previewState(bv)) {
605 // Do not draw change tracking cue if taken care of by RowPainter
607 Changer dummy = !canPaintChange(*bv) ? changeVar(pi.change, Change())
609 if (previewTooSmall(dim)) {
610 // we have an extra frame
611 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
613 // one pixel gap in front
614 // value was hardcoded to 1 pixel
615 int const gap = pi.base.bv->zoomedPixels(1) ;
616 preview_->draw(pi, x + gap, y);
621 // First draw the numbers
622 if (numberedType()) {
623 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
624 for (row_type row = 0; row < nrows(); ++row) {
625 int yy = y + rowinfo(row).offset[bv];
626 docstring const nl = nicelabel(row);
628 mathed_string_dim(pi.base.font, nl, dimnl);
629 if (math_number == BufferParams::LEFT) {
630 ColorCode const col = pi.selected_left
631 ? Color_selectiontext
632 : pi.base.font.color();
633 Changer dummy0 = pi.base.font.changeColor(col);
634 if (dimnl.wid > x - pi.leftx)
635 yy += rowinfo(row).descent + dimnl.asc;
636 pi.pain.fillRectangle(pi.leftx, yy - dimnl.asc,
637 dimnl.width(), dimnl.height(),
638 pi.selected_left ? Color_selection : pi.background_color);
639 pi.draw(pi.leftx, yy, nl);
641 ColorCode const col = pi.selected_right
642 ? Color_selectiontext
643 : pi.base.font.color();
644 Changer dummy0 = pi.base.font.changeColor(col);
645 if (dimnl.wid > pi.rightx - x - dim.wid)
646 yy += rowinfo(row).descent + dimnl.asc;
647 pi.pain.fillRectangle(pi.rightx - dimnl.wid, yy - dimnl.asc,
648 dimnl.width(), dimnl.height(),
649 pi.selected_right ? Color_selection : pi.background_color);
650 pi.draw(pi.rightx - dimnl.wid, yy, nl);
655 // Then the equations
656 ColorCode color = pi.selected && lyxrc.use_system_colors
657 ? Color_selectiontext : standardColor();
658 bool const really_change_color = pi.base.font.color() == Color_none;
659 Changer dummy0 = really_change_color ? pi.base.font.changeColor(color)
661 Changer dummy1 = pi.base.changeFontSet(standardFont());
662 Changer dummy2 = pi.base.font.changeStyle(display() ? DISPLAY_STYLE
664 InsetMathGrid::draw(pi, x + 1, y);
665 drawMarkers(pi, x, y);
667 // drawing change line
668 if (canPaintChange(*bv)) {
670 int const display_margin = display() ? pi.base.inPixels(Length(12, Length::PT)) : 0;
671 pi.change.paintCue(pi, x + 1, y + 1 - dim.asc + display_margin,
672 x + dim.wid, y + dim.des - display_margin);
677 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
680 InsetMathGrid::metricsT(mi, dim);
683 otexrowstream ots(os);
684 TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault);
686 dim.wid = os.str().size();
693 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
696 InsetMathGrid::drawT(pain, x, y);
699 otexrowstream ots(os);
700 TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault);
702 pain.draw(x, y, os.str().c_str());
707 static docstring latexString(InsetMathHull const & inset)
710 // This has to be static, because a preview snippet or a math
711 // macro containing math in text mode (such as $\text{$\phi$}$ or
712 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
713 // first time as a whole, and the second time only the inner math.
714 // In this last case inset.buffer() would be invalid.
715 static Encoding const * encoding = nullptr;
716 if (inset.isBufferValid())
717 encoding = &(inset.buffer().params().encoding());
718 otexrowstream ots(ls);
719 TeXMathStream wi(ots, false, true, TeXMathStream::wsPreview, encoding);
725 void InsetMathHull::initUnicodeMath() const
727 // Trigger classification of the unicode symbols in this inset
728 docstring const dummy = latexString(*this);
732 void InsetMathHull::addPreview(DocIterator const & inset_pos,
733 graphics::PreviewLoader & /*ploader*/) const
735 if (RenderPreview::previewMath()) {
736 preparePreview(inset_pos);
741 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
742 MacroNameSet & macros, MacroNameSet & defs) const
744 MacroNameSet::iterator const end = macros.end();
746 for (size_t i = 0; i < md.size(); ++i) {
747 InsetMathMacro const * mi = md[i].nucleus()->asMacro();
748 InsetMathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
749 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
750 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
751 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
752 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
754 // Look for macros in the arguments of this macro.
755 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
756 usedMacros(mi->cell(idx), pos, macros, defs);
757 // Make sure this is a macro defined in the document
758 // (as we also spot the macros in the symbols file)
759 // or that we have not already accounted for it.
760 docstring const name = mi->name();
761 if (macros.find(name) == end)
764 // Look for macros in the definition of this macro.
765 MathData ar(pos.buffer());
766 MacroData const * data =
767 pos.buffer()->getMacro(name, pos, true);
769 odocstringstream macro_def;
770 data->write(macro_def, true);
772 defs.insert(macro_def.str());
773 asArray(data->definition(), ar);
775 usedMacros(ar, pos, macros, defs);
777 MathData ar(pos.buffer());
778 asArray(mt->definition(), ar);
779 usedMacros(ar, pos, macros, defs);
781 if (!si->nuc().empty())
782 usedMacros(si->nuc(), pos, macros, defs);
784 usedMacros(si->down(), pos, macros, defs);
786 usedMacros(si->up(), pos, macros, defs);
787 } else if (fi || gi) {
788 idx_type nidx = fi ? fi->nargs() : gi->nargs();
789 for (idx_type idx = 0; idx < nidx; ++idx)
790 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
793 usedMacros(ni->cell(0), pos, macros, defs);
799 void InsetMathHull::preparePreview(DocIterator const & pos,
800 bool forexport) const
802 // there is no need to do all the macro stuff if we're not
803 // actually going to generate the preview.
804 if (!RenderPreview::previewMath() && !forexport)
807 Buffer const * buffer = pos.buffer();
809 // collect macros at this position
811 buffer->listMacroNames(macros);
813 // collect definitions only for the macros used in this inset
815 for (idx_type idx = 0; idx < nargs(); ++idx)
816 usedMacros(cell(idx), pos, macros, defs);
818 docstring macro_preamble;
819 for (auto const & defvar : defs)
820 macro_preamble.append(defvar);
822 // set the font series and size for this snippet
823 DocIterator dit = pos.getInnerText();
824 Paragraph const & par = dit.paragraph();
825 Font font = par.getFontSettings(buffer->params(), dit.pos());
826 font.fontInfo().realize(par.layout().font);
827 string const lsize = font.latexSize();
830 if (font.fontInfo().series() == BOLD_SERIES) {
831 setfont += from_ascii("\\textbf{");
834 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
835 setfont += from_ascii("\\" + lsize + '\n');
837 docstring const snippet = macro_preamble + setfont + latexString(*this) + endfont;
838 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
839 preview_->addPreview(snippet, *buffer, forexport);
843 void InsetMathHull::reloadPreview(DocIterator const & pos) const
846 preview_->startLoading(*pos.buffer());
850 void InsetMathHull::loadPreview(DocIterator const & pos) const
852 bool const forexport = true;
853 preparePreview(pos, forexport);
854 preview_->startLoading(*pos.buffer(), forexport);
858 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
860 if (RenderPreview::previewMath()) {
862 cur.screenUpdateFlags(Update::Force);
868 docstring InsetMathHull::label(row_type row) const
870 LASSERT(row < nrows(), return docstring());
871 if (InsetLabel * il = label_[row])
872 return il->screenLabel();
877 void InsetMathHull::label(row_type row, docstring const & label)
879 //lyxerr << "setting label '" << label << "' for row " << row << endl;
883 label_[row] = dummy_pointer;
886 label_[row]->updateLabelAndRefs(label);
888 label_[row]->setParam("name", label);
892 InsetCommandParams p(LABEL_CODE);
894 label_[row] = new InsetLabel(buffer_, p);
896 label_[row]->setBuffer(buffer());
900 void InsetMathHull::numbered(row_type row, Numbered num)
902 numbered_[row] = num;
906 bool InsetMathHull::numbered(row_type row) const
908 return numbered_[row] == NUMBER;
912 bool InsetMathHull::ams() const
932 for (auto const & row : numbered_)
939 bool InsetMathHull::outerDisplay() const
962 int InsetMathHull::rowFlags() const
979 if (buffer().params().is_math_indent)
980 return Display | AlignLeft;
989 int InsetMathHull::indent(BufferView const & bv) const
991 // FIXME: set this in the textclass. This value is what the article class uses.
992 static Length default_indent(2.5, Length::EM);
993 if (display() && buffer().params().is_math_indent) {
994 Length const & len = buffer().params().getMathIndent();
996 return bv.inPixels(default_indent);
998 return bv.inPixels(len);
1000 return Inset::indent(bv);
1004 bool InsetMathHull::numberedType() const
1023 for (row_type row = 0; row < nrows(); ++row)
1030 void InsetMathHull::validate(LaTeXFeatures & features) const
1032 if (features.runparams().isLaTeX()) {
1034 features.require("amsmath");
1036 if (type_ == hullRegexp) {
1037 features.require("color");
1038 docstring frcol = from_utf8(lcolor.getLaTeXName(Color_regexpframe));
1039 docstring bgcol = from_ascii("white");
1040 features.addPreambleSnippet(
1041 "\\newcommand{\\regexp}[1]{\\fcolorbox{"
1043 + bgcol + "}{\\ensuremath{\\mathtt{#1}}}}");
1044 features.addPreambleSnippet(
1045 from_ascii("\\newcommand{\\endregexp}{}"));
1046 } else if (outerDisplay() && features.inDeletedInset()) {
1047 features.require("tikz");
1048 features.require("ct-tikz-object-sout");
1051 // Validation is necessary only if not using AMS math.
1052 // To be safe, we will always run mathedvalidate.
1053 //if (features.amsstyle)
1056 //features.binom = true;
1057 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
1058 // it would be better to do this elsewhere, but we can't validate in
1059 // InsetMathMatrix and we have no way, outside MathExtern, to know if
1060 // we even have any matrices.
1061 features.addCSSSnippet(
1062 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
1063 "table.matrix td{padding: 0.25px;}\n"
1064 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
1065 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
1067 InsetMathGrid::validate(features);
1071 CtObject InsetMathHull::getCtObject(OutputParams const & runparams) const
1073 CtObject res = CtObject::Normal;
1089 case hullMultline: {
1090 if (runparams.inulemcmd
1091 && (!runparams.local_font || runparams.local_font->fontInfo().strikeout() != FONT_ON))
1092 res = CtObject::UDisplayObject;
1094 res = CtObject::DisplayObject;
1102 void InsetMathHull::header_write(TeXMathStream & os) const
1104 bool n = numberedType();
1115 if (cell(0).empty())
1120 writeMathdisplayPreamble(os);
1124 os << "\\begin{equation" << star(n) << "}\n";
1134 writeMathdisplayPreamble(os);
1137 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1144 os << "\\begin{" << hullName(type_) << star(n) << '}'
1145 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1151 os << "\\begin{" << hullName(type_) << '}'
1152 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1162 os << "\\begin{unknown" << star(n) << "}\n";
1168 void InsetMathHull::footer_write(TeXMathStream & os) const
1170 bool n = numberedType();
1187 os << "\\end{equation" << star(n) << "}\n";
1190 writeMathdisplayPostamble(os);
1200 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1201 writeMathdisplayPostamble(os);
1208 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1214 os << "\\end{" << hullName(type_) << "}\n";
1218 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1219 os << "\\endregexp{}}";
1225 os << "\\end{unknown" << star(n) << "}\n";
1231 bool InsetMathHull::allowsTabularFeatures() const
1254 bool InsetMathHull::rowChangeOK() const
1257 type_ == hullEqnArray || type_ == hullAlign ||
1258 type_ == hullFlAlign || type_ == hullAlignAt ||
1259 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1260 type_ == hullGather || type_ == hullMultline;
1264 bool InsetMathHull::colChangeOK() const
1267 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1268 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1272 void InsetMathHull::addRow(row_type row)
1277 bool numbered = numberedType();
1278 // Move the number and raw pointer, do not call label() (bug 7511)
1279 InsetLabel * label = dummy_pointer;
1280 docstring number = empty_docstring();
1281 if (type_ == hullMultline) {
1282 if (row + 1 == nrows()) {
1283 numbered_[row] = NONUMBER;
1284 swap(label, label_[row]);
1285 swap(number, numbers_[row]);
1290 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1291 numbers_.insert(numbers_.begin() + row + 1, number);
1292 label_.insert(label_.begin() + row + 1, label);
1293 InsetMathGrid::addRow(row);
1297 void InsetMathHull::swapRow(row_type row)
1301 if (row + 1 == nrows())
1303 swap(numbered_[row], numbered_[row + 1]);
1304 swap(numbers_[row], numbers_[row + 1]);
1305 swap(label_[row], label_[row + 1]);
1306 InsetMathGrid::swapRow(row);
1310 void InsetMathHull::delRow(row_type row)
1312 if (nrows() <= 1 || !rowChangeOK())
1314 if (row + 1 == nrows() && type_ == hullMultline) {
1315 swap(numbered_[row - 1], numbered_[row]);
1316 swap(numbers_[row - 1], numbers_[row]);
1317 swap(label_[row - 1], label_[row]);
1318 InsetMathGrid::delRow(row);
1321 InsetMathGrid::delRow(row);
1322 // The last dummy row has no number info nor a label.
1323 // Test nrows() + 1 because we have already erased the row.
1324 if (row == nrows() + 1)
1326 numbered_.erase(numbered_.begin() + row);
1327 numbers_.erase(numbers_.begin() + row);
1329 label_.erase(label_.begin() + row);
1333 void InsetMathHull::addCol(col_type col)
1337 InsetMathGrid::addCol(col);
1341 void InsetMathHull::delCol(col_type col)
1343 if (ncols() <= 1 || !colChangeOK())
1345 InsetMathGrid::delCol(col);
1349 docstring InsetMathHull::nicelabel(row_type row) const
1351 if (!numbered(row)) {
1354 return '[' + label_[row]->screenLabel() + ']';
1356 docstring const & val = numbers_[row];
1358 return '(' + val + ')';
1359 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1363 void InsetMathHull::glueall(HullType type)
1366 for (idx_type i = 0; i < nargs(); ++i)
1368 InsetLabel * label = nullptr;
1369 if (type == hullEquation) {
1370 // preserve first non-empty label
1371 for (row_type row = 0; row < nrows(); ++row) {
1373 label = label_[row];
1379 *this = InsetMathHull(buffer_, hullSimple);
1386 void InsetMathHull::splitTo2Cols()
1388 LASSERT(ncols() == 1, return);
1389 InsetMathGrid::addCol(1);
1390 for (row_type row = 0; row < nrows(); ++row) {
1391 idx_type const i = 2 * row;
1392 pos_type pos = firstRelOp(cell(i));
1393 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1394 cell(i).erase(pos, cell(i).size());
1399 void InsetMathHull::splitTo3Cols()
1401 LASSERT(ncols() < 3, return);
1404 InsetMathGrid::addCol(2);
1405 for (row_type row = 0; row < nrows(); ++row) {
1406 idx_type const i = 3 * row + 1;
1407 if (!cell(i).empty()) {
1408 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1409 cell(i).erase(1, cell(i).size());
1415 void InsetMathHull::changeCols(col_type cols)
1417 if (ncols() == cols)
1419 else if (ncols() < cols) {
1425 while (ncols() < cols)
1426 InsetMathGrid::addCol(ncols());
1432 for (row_type row = 0; row < nrows(); ++row) {
1433 idx_type const i = row * ncols();
1434 for (col_type col = cols; col < ncols(); ++col) {
1435 cell(i + cols - 1).append(cell(i + col));
1439 while (ncols() > cols) {
1440 InsetMathGrid::delCol(ncols() - 1);
1445 HullType InsetMathHull::getType() const
1451 void InsetMathHull::setType(HullType type)
1458 bool InsetMathHull::isMutable(HullType type)
1482 void InsetMathHull::mutate(HullType newtype)
1484 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1486 if (newtype == type_)
1489 // This guards the algorithm below it, which is designed with certain types
1491 if (!isMutable(newtype) || !isMutable(type_)) {
1492 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1493 << "' to '" << to_utf8(hullName(newtype))
1494 << "' not implemented" << endl;
1498 // we try to move along the chain
1499 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1501 // +-------------------------------------+
1502 // we use eqnarray as intermediate type for mutations that are not
1503 // directly supported because it handles labels and numbering for
1508 setType(hullSimple);
1514 if (newtype == hullNone) {
1518 setType(hullEquation);
1519 numbered(0, label_[0] != nullptr);
1528 setType(hullSimple);
1533 // split it "nicely" on the first relop
1535 setType(hullEqnArray);
1543 // split it "nicely"
1578 setType(hullEqnArray);
1587 for (row_type row = 0; row < nrows(); ++row)
1588 numbered(row, false);
1598 for (row_type row = 0; row < nrows(); ++row)
1599 numbered(row, false);
1606 setType(hullEqnArray);
1636 for (row_type row = 0; row < nrows(); ++row)
1637 numbered(row, false);
1641 // first we mutate to EqnArray
1643 setType(hullEqnArray);
1650 // we passed the guard so we should not be here
1651 LYXERR0("Mutation not implemented, but should have been.");
1652 LASSERT(false, return);
1658 void InsetMathHull::eol(TeXMathStream & os, row_type row, bool fragile, bool latex,
1659 bool last_eoln) const
1661 if (numberedType()) {
1663 docstring const name =
1664 latex ? escape(label_[row]->getParam("name"))
1665 : label_[row]->getParam("name");
1666 os << "\\label{" + name + '}';
1668 if (type_ != hullMultline) {
1669 if (numbered_[row] == NONUMBER)
1670 os << "\\nonumber ";
1671 else if (numbered_[row] == NOTAG)
1674 if (os.output() == TeXMathStream::wsPreview && !numbers_[row].empty()) {
1675 os << "\\global\\def\\theequation{" << numbers_[row] << "}\n";
1679 // Never add \\ on the last empty line of eqnarray and friends
1681 InsetMathGrid::eol(os, row, fragile, latex, last_eoln);
1684 void InsetMathHull::write(TeXMathStream & os) const
1686 ModeSpecifier specifier(os, MATH_MODE);
1688 InsetMathGrid::write(os);
1693 void InsetMathHull::normalize(NormalStream & os) const
1695 os << "[formula " << hullName(type_) << ' ';
1696 InsetMathGrid::normalize(os);
1701 void InsetMathHull::infoize(odocstream & os) const
1703 os << bformat(_("Type: %1$s"), hullName(type_));
1707 void InsetMathHull::check() const
1709 LATTEST(numbered_.size() == nrows());
1710 LATTEST(numbers_.size() == nrows());
1711 LATTEST(label_.size() == nrows());
1715 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1717 //FIXME: sort out whether we want std::string or docstring for those
1718 string const lang = func.getArg(0);
1719 docstring extra = from_utf8(func.getArg(1));
1721 extra = from_ascii("noextra");
1723 // replace selection with result of computation
1724 if (reduceSelectionToOneCell(cur)) {
1726 asArray(grabAndEraseSelection(cur), ar);
1727 lyxerr << "use selection: " << ar << endl;
1728 cur.insert(pipeThroughExtern(lang, extra, ar));
1732 // only inline, display or eqnarray math is allowed
1733 switch (getType()) {
1739 frontend::Alert::warning(_("Bad math environment"),
1740 _("Computation cannot be performed for AMS "
1741 "math environments.\nChange the math "
1742 "formula type and try again."));
1747 eq.push_back(MathAtom(new InsetMathChar('=')));
1749 // go to first item in line
1750 cur.idx() -= cur.idx() % ncols();
1753 if (getType() == hullSimple) {
1754 size_type pos = cur.cell().find_last(eq);
1756 if (pos == cur.cell().size()) {
1758 lyxerr << "use whole cell: " << ar << endl;
1760 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1761 lyxerr << "use partial cell form pos: " << pos << endl;
1763 cur.cell().append(eq);
1764 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1765 cur.pos() = cur.lastpos();
1769 if (getType() == hullEquation) {
1770 lyxerr << "use equation inset" << endl;
1771 mutate(hullEqnArray);
1772 MathData & ar = cur.cell();
1773 lyxerr << "use cell: " << ar << endl;
1777 cur.cell() = pipeThroughExtern(lang, extra, ar);
1778 // move to end of line
1779 cur.pos() = cur.lastpos();
1784 lyxerr << "use eqnarray" << endl;
1785 cur.idx() += 2 - cur.idx() % ncols();
1787 MathData ar = cur.cell();
1788 lyxerr << "use cell: " << ar << endl;
1789 // FIXME: temporarily disabled
1795 cur.cell() = pipeThroughExtern(lang, extra, ar);
1796 cur.pos() = cur.lastpos();
1801 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1803 //lyxerr << "action: " << cmd.action() << endl;
1804 switch (cmd.action()) {
1806 case LFUN_FINISHED_BACKWARD:
1807 case LFUN_FINISHED_FORWARD:
1808 case LFUN_FINISHED_RIGHT:
1809 case LFUN_FINISHED_LEFT:
1810 //lyxerr << "action: " << cmd.action() << endl;
1811 InsetMathGrid::doDispatch(cur, cmd);
1814 case LFUN_PARAGRAPH_BREAK:
1815 // just swallow this
1818 case LFUN_NEWLINE_INSERT:
1819 // some magic for the common case
1820 if (type_ == hullSimple || type_ == hullEquation) {
1821 cur.recordUndoInset();
1823 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1824 mutate(align ? hullAlign : hullEqnArray);
1825 // mutate() may change labels and such.
1826 cur.forceBufferUpdate();
1827 cur.idx() = nrows() * ncols() - 1;
1828 cur.pos() = cur.lastpos();
1830 InsetMathGrid::doDispatch(cur, cmd);
1833 case LFUN_MATH_NUMBER_TOGGLE: {
1834 //lyxerr << "toggling all numbers" << endl;
1835 cur.recordUndoInset();
1836 bool old = numberedType();
1837 if (type_ == hullMultline) {
1838 row_type row = nrows() - 1;
1839 numbered(row, !old);
1840 if (old && label_[row]) {
1845 for (row_type row = 0; row < nrows(); ++row) {
1846 numbered(row, !old);
1847 if (old && label_[row]) {
1854 cur.message(old ? _("No number") : _("Number"));
1855 cur.forceBufferUpdate();
1859 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1860 cur.recordUndoInset();
1861 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1862 bool old = numbered(r);
1863 cur.message(old ? _("No number") : _("Number"));
1865 if (old && label_[r]) {
1869 cur.forceBufferUpdate();
1873 case LFUN_LABEL_INSERT: {
1874 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1875 docstring old_label = label(r);
1876 docstring const default_label = from_ascii("eq:");
1877 if (old_label.empty())
1878 old_label = default_label;
1880 InsetCommandParams p(LABEL_CODE);
1881 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1882 string const data = InsetCommand::params2string(p);
1884 if (cmd.argument().empty())
1885 cur.bv().showDialog("label", data);
1887 FuncRequest fr(LFUN_INSET_INSERT, data);
1893 case LFUN_LABEL_COPY_AS_REFERENCE: {
1895 if (cmd.argument().empty() && &cur.inset() == this)
1896 // if there is no argument and we're inside math, we retrieve
1897 // the row number from the cursor position.
1898 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1900 // if there is an argument, find the corresponding label, else
1901 // check whether there is at least one label.
1902 for (row = 0; row != nrows(); ++row)
1904 && (cmd.argument().empty() || label(row) == cmd.argument()))
1911 InsetCommandParams p(REF_CODE, "ref");
1912 p["reference"] = label(row);
1913 cap::clearSelection();
1914 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1918 case LFUN_WORD_DELETE_FORWARD:
1919 case LFUN_CHAR_DELETE_FORWARD:
1920 if (col(cur.idx()) + 1 == ncols()
1921 && cur.pos() == cur.lastpos()
1922 && !cur.selection()) {
1923 if (!label(row(cur.idx())).empty()) {
1924 cur.recordUndoInset();
1925 label(row(cur.idx()), docstring());
1926 } else if (numbered(row(cur.idx()))) {
1927 cur.recordUndoInset();
1928 numbered(row(cur.idx()), false);
1929 cur.forceBufferUpdate();
1931 InsetMathGrid::doDispatch(cur, cmd);
1935 InsetMathGrid::doDispatch(cur, cmd);
1940 case LFUN_INSET_INSERT: {
1941 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1942 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1943 string const name = cmd.getArg(0);
1944 if (name == "label") {
1945 InsetCommandParams p(LABEL_CODE);
1946 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1947 docstring str = p["name"];
1948 cur.recordUndoInset();
1949 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1953 docstring old = label(r);
1956 // The label will take care of the reference update.
1960 // Newly created inset so initialize it.
1961 label_[r]->initView();
1964 cur.forceBufferUpdate();
1967 InsetMathGrid::doDispatch(cur, cmd);
1971 case LFUN_MATH_EXTERN:
1972 cur.recordUndoInset();
1976 case LFUN_MATH_MUTATE: {
1977 cur.recordUndoInset();
1978 row_type row = cur.row();
1979 col_type col = cur.col();
1980 mutate(hullType(cmd.argument()));
1981 cur.idx() = row * ncols() + col;
1982 if (cur.idx() > cur.lastidx()) {
1983 cur.idx() = cur.lastidx();
1984 cur.pos() = cur.lastpos();
1986 if (cur.pos() > cur.lastpos())
1987 cur.pos() = cur.lastpos();
1989 cur.forceBufferUpdate();
1990 // FIXME: find some more clever handling of the selection,
1991 // i.e. preserve it.
1992 cur.clearSelection();
1993 //cur.dispatched(FINISHED);
1997 case LFUN_MATH_DISPLAY: {
1998 cur.recordUndoInset();
1999 mutate(type_ == hullSimple ? hullEquation : hullSimple);
2000 // if the cursor is in a cell that got merged, move it to
2001 // start of the hull inset.
2002 if (cur.idx() > 0) {
2006 if (cur.pos() > cur.lastpos())
2007 cur.pos() = cur.lastpos();
2012 case LFUN_TABULAR_FEATURE:
2013 if (!allowsTabularFeatures())
2016 InsetMathGrid::doDispatch(cur, cmd);
2020 InsetMathGrid::doDispatch(cur, cmd);
2028 bool allowDisplayMath(Cursor const & cur)
2030 LATTEST(cur.depth() > 1);
2031 Cursor tmpcur = cur;
2034 FuncRequest cmd(LFUN_MATH_DISPLAY);
2035 return tmpcur.getStatus(cmd, status) && status.enabled();
2041 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
2042 FuncStatus & status) const
2044 switch (cmd.action()) {
2045 case LFUN_FINISHED_BACKWARD:
2046 case LFUN_FINISHED_FORWARD:
2047 case LFUN_FINISHED_RIGHT:
2048 case LFUN_FINISHED_LEFT:
2051 case LFUN_NEWLINE_INSERT:
2052 case LFUN_MATH_EXTERN:
2054 status.setEnabled(true);
2057 // we never allow this in math, and we want to bind enter
2058 // to another actions in command-alternatives
2059 case LFUN_PARAGRAPH_BREAK:
2060 status.setEnabled(false);
2062 case LFUN_MATH_MUTATE: {
2063 HullType const ht = hullType(cmd.argument());
2064 status.setOnOff(type_ == ht);
2065 status.setEnabled(isMutable(ht) && isMutable(type_));
2067 if (ht != hullSimple && status.enabled())
2068 status.setEnabled(allowDisplayMath(cur));
2071 case LFUN_MATH_DISPLAY: {
2072 status.setEnabled(display() || allowDisplayMath(cur));
2073 status.setOnOff(display());
2077 case LFUN_MATH_NUMBER_TOGGLE:
2078 // FIXME: what is the right test, this or the one of
2080 status.setEnabled(display());
2081 status.setOnOff(numberedType());
2084 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
2085 // FIXME: what is the right test, this or the one of
2087 bool const enable = (type_ == hullMultline)
2088 ? (nrows() - 1 == cur.row())
2090 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2091 status.setEnabled(enable);
2092 status.setOnOff(enable && numbered(r));
2096 case LFUN_LABEL_INSERT:
2097 status.setEnabled(type_ != hullSimple);
2100 case LFUN_LABEL_COPY_AS_REFERENCE: {
2101 bool enabled = false;
2102 if (cmd.argument().empty() && &cur.inset() == this) {
2103 // if there is no argument and we're inside math, we retrieve
2104 // the row number from the cursor position.
2105 row_type row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2106 enabled = numberedType() && label_[row];
2108 // if there is an argument, find the corresponding label, else
2109 // check whether there is at least one label.
2110 for (row_type row = 0; row != nrows(); ++row) {
2112 (cmd.argument().empty() || label(row) == cmd.argument())) {
2118 status.setEnabled(enabled);
2122 case LFUN_INSET_INSERT:
2123 if (cmd.getArg(0) == "label") {
2124 status.setEnabled(type_ != hullSimple);
2127 return InsetMathGrid::getStatus(cur, cmd, status);
2129 case LFUN_TABULAR_FEATURE: {
2130 if (!allowsTabularFeatures())
2132 string s = cmd.getArg(0);
2134 && (s == "append-row"
2135 || s == "delete-row"
2136 || s == "copy-row")) {
2137 status.message(bformat(
2138 from_utf8(N_("Can't change number of rows in '%1$s'")),
2140 status.setEnabled(false);
2144 && (s == "append-column"
2145 || s == "delete-column"
2146 || s == "copy-column")) {
2147 status.message(bformat(
2148 from_utf8(N_("Can't change number of columns in '%1$s'")),
2150 status.setEnabled(false);
2153 if (s == "add-vline-left" || s == "add-vline-right") {
2154 status.message(bformat(
2155 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2157 status.setEnabled(false);
2160 if (s == "valign-top" || s == "valign-middle"
2161 || s == "valign-bottom" || s == "align-left"
2162 || s == "align-center" || s == "align-right") {
2163 status.setEnabled(false);
2166 return InsetMathGrid::getStatus(cur, cmd, status);
2170 return InsetMathGrid::getStatus(cur, cmd, status);
2175 int InsetMathHull::leftMargin() const
2177 return (getType() == hullSimple) ? 0 : InsetMathGrid::leftMargin();
2181 int InsetMathHull::rightMargin() const
2183 return (getType() == hullSimple) ? 0 : InsetMathGrid::rightMargin();
2187 int InsetMathHull::border() const
2189 return (getType() == hullSimple) ? 0 : InsetMathGrid::border();
2193 /////////////////////////////////////////////////////////////////////
2197 // simply scrap this function if you want
2198 void InsetMathHull::mutateToText()
2201 // translate to latex
2203 latex(os, false, false);
2204 string str = os.str();
2207 Text * lt = view_->cursor().innerText();
2208 string::const_iterator cit = str.begin();
2209 string::const_iterator end = str.end();
2210 for (; cit != end; ++cit)
2211 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2214 //dispatch(LFUN_ESCAPE);
2219 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2220 docstring const & font)
2222 // this whole function is a hack and won't work for incremental font
2225 if (cur.inset().asInsetMath()->name() == font)
2226 cur.handleFont(to_utf8(font));
2228 cur.handleNest(createInsetMath(font, cur.buffer()));
2234 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2239 font.fromString(to_utf8(arg), b);
2240 if (font.fontInfo().color() != Color_inherit) {
2241 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2247 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2250 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
2251 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
2252 enter_front ? idxFirst(cur) : idxLast(cur);
2253 // The inset formula dimension is not necessarily the same as the
2254 // one of the instant preview image, so we have to indicate to the
2255 // BufferView that a metrics update is needed.
2256 cur.screenUpdateFlags(Update::Force);
2260 /////////////////////////////////////////////////////////////////////
2264 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2267 // FIXME: completely broken
2268 static InsetMathHull * lastformula = 0;
2269 static CursorBase current = DocIterator(ibegin(nucleus()));
2271 static string laststr;
2273 if (lastformula != this || laststr != str) {
2274 //lyxerr << "reset lastformula to " << this << endl;
2277 current = ibegin(nucleus());
2279 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2283 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2285 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2286 CursorSlice & top = it.back();
2287 MathData const & a = top.asInsetMath()->cell(top.idx_);
2288 if (a.matchpart(ar, top.pos_)) {
2289 bv->cursor().setSelection(it, ar.size());
2291 top.pos_ += ar.size();
2297 //lyxerr << "not found!" << endl;
2304 void InsetMathHull::write(ostream & os) const
2306 odocstringstream oss;
2307 otexrowstream ots(oss);
2308 TeXMathStream wi(ots, false, false, TeXMathStream::wsDefault);
2311 os << to_utf8(oss.str());
2315 void InsetMathHull::read(Lexer & lex)
2318 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2319 operator=(*at->asHullInset());
2323 bool InsetMathHull::readQuiet(Lexer & lex)
2326 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2328 operator=(*at->asHullInset());
2333 int InsetMathHull::plaintext(odocstringstream & os,
2334 OutputParams const & op, size_t max_length) const
2336 // Try enabling this now that there is a flag as requested at #2275.
2337 if (buffer().isExporting() && display()) {
2341 TextPainter tpain(dim.width(), dim.height());
2342 drawT(tpain, 0, dim.ascent());
2344 // reset metrics cache to "real" values
2346 return tpain.textheight();
2349 odocstringstream oss;
2350 otexrowstream ots(oss);
2351 Encoding const * const enc = encodings.fromLyXName("utf8");
2353 TeXMathStream::OutputType ot;
2354 if (op.find_effective())
2355 ot = TeXMathStream::wsSearchAdv;
2357 ot = TeXMathStream::wsDefault;
2359 if (type_ == hullRegexp) {
2360 TeXMathStream wi(ots, false, true, ot, enc);
2364 TeXMathStream wi(ots, false, true, ot, enc);
2365 for (row_type r = 0; r < nrows(); ++r) {
2366 for (col_type c = 0; c < ncols(); ++c)
2367 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2368 // if it's for the TOC, we write just the first line
2369 // and do not include the newline.
2370 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2372 if (r < nrows() - 1)
2376 docstring const str = oss.str();
2382 void InsetMathHull::docbook(XMLStream & xs, OutputParams const & runparams) const {
2383 // Choose the tag around the MathML equation.
2386 if (getType() == hullSimple)
2387 name = from_ascii("inlineequation");
2389 doCR = true; // This is a block equation, always have <informalequation> on its own line.
2390 name = from_ascii("informalequation");
2393 // DocBook also has <equation>, but it comes with a title.
2394 // TODO: recognise \tag from amsmath? This would allow having <equation> with a proper title.
2398 bool mathmlNamespaceInline = buffer().params().docbook_mathml_prefix == BufferParams::NoPrefix;
2399 if (mathmlNamespaceInline)
2400 attr += "xmlns=\"http://www.w3.org/1998/Math/MathML\"";
2402 for (row_type i = 0; i < nrows(); ++i) {
2403 if (!label(i).empty()) {
2407 attr += "xml:id=\"" + xml::cleanID(label(i)) + "\"";
2413 if (!xs.isLastTagCR())
2416 xs << xml::StartTag(name, attr);
2419 // With DocBook 5, MathML must be within its own namespace (defined in Buffer.cpp::writeDocBookSource, except when
2420 // it should be inlined).
2421 // Output everything in a separate stream so that this does not interfere with the standard flow of DocBook tags.
2422 std::string mathmlNamespacePrefix;
2423 if (!mathmlNamespaceInline) {
2424 if (buffer().params().docbook_mathml_prefix == BufferParams::MPrefix)
2425 mathmlNamespacePrefix = "m";
2426 else if (buffer().params().docbook_mathml_prefix == BufferParams::MMLPrefix)
2427 mathmlNamespacePrefix = "mml";
2430 odocstringstream osmath;
2431 MathMLStream ms(osmath, mathmlNamespacePrefix);
2433 // Output the MathML subtree.
2434 // TeX transcription. Avoid MTag/ETag so that there are no extraneous spaces.
2435 ms << "<" << from_ascii("alt") << " role='tex'" << ">";
2436 // Workaround for db2latex: db2latex always includes equations with
2437 // \ensuremath{} or \begin{display}\end{display}
2438 // so we strip LyX' math environment
2439 odocstringstream ls;
2441 TeXMathStream wi(ols, false, false, TeXMathStream::wsDefault, runparams.encoding);
2442 InsetMathGrid::write(wi);
2443 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2444 ms << "</" << from_ascii("alt") << ">";
2446 // Actual transformation of the formula into MathML. This translation may fail (for example, due to custom macros).
2447 // The new output stream is required to deal with the errors: first write completely the formula into this
2448 // temporary stream; then, if it is possible without error, then copy it back to the "real" stream. Otherwise,
2449 // some incomplete tags might be put into the real stream.
2451 // First, generate the MathML expression. If there is an error in the generation, this block is not fully
2452 // executed, and the formula is not output to the DocBook stream.
2453 odocstringstream ostmp;
2454 MathMLStream mstmp(ostmp, ms.xmlns());
2457 // Choose the display style for the formula, to be output as an attribute near the formula root.
2458 std::string mathmlAttr;
2459 if (getType() == hullSimple)
2460 mathmlAttr = "display=\"inline\"";
2462 mathmlAttr = "display=\"block\"";
2464 // Then, output the formula.
2465 ms << MTag("math", mathmlAttr);
2467 osmath << ostmp.str(); // osmath is not a XMLStream, so no need for XMLStream::ESCAPE_NONE.
2469 } catch (MathExportException const &) {
2471 osmath << "<mathphrase>MathML export failed. Please report this as a bug to the LyX developers: "
2472 "https://www.lyx.org/trac.</mathphrase>";
2475 // Output the complete formula to the DocBook stream.
2476 xs << XMLStream::ESCAPE_NONE << osmath.str();
2478 xs << xml::EndTag(name);
2484 bool InsetMathHull::haveNumbers() const
2486 bool havenumbers = false;
2487 // inline formulas are never numbered (bug 7351 part 3)
2488 if (getType() == hullSimple)
2490 for (size_t i = 0; i != numbered_.size(); ++i) {
2501 // We need to do something about alignment here.
2503 // This duplicates code from InsetMathGrid, but
2504 // we need access here to number information,
2505 // and we simply do not have that in InsetMathGrid.
2506 void InsetMathHull::htmlize(HtmlStream & os) const
2508 bool const havenumbers = haveNumbers();
2509 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2512 os << cell(index(0, 0));
2516 os << MTag("table", "class='mathtable'");
2517 for (row_type row = 0; row < nrows(); ++row) {
2519 for (col_type col = 0; col < ncols(); ++col) {
2521 os << cell(index(row, col));
2526 docstring const & num = numbers_[row];
2528 os << '(' << num << ')';
2533 os << ETag("table");
2537 // this duplicates code from InsetMathGrid, but
2538 // we need access here to number information,
2539 // and we simply do not have that in InsetMathGrid.
2540 void InsetMathHull::mathmlize(MathMLStream & ms) const
2542 bool const havetable = haveNumbers() || nrows() > 1 || ncols() > 1;
2544 // Simplest case: single row, single column, no numbering.
2546 ms << cell(index(0, 0));
2550 // More complex case: wrap elements in a table.
2551 if (getType() == hullSimple) {
2552 ms << MTag("mtable");
2553 } else if (getType() >= hullAlign && getType() <= hullXXAlignAt) {
2554 // hullAlign, hullAlignAt, hullXAlignAt, hullXXAlignAt
2556 for (col_type col = 0; col < ncols(); ++col) {
2557 alignment += (col % 2) ? "left " : "right ";
2559 ms << MTag("mtable", "displaystyle='true' columnalign='" + alignment + "'");
2561 ms << MTag("mtable", "displaystyle='true'");
2564 for (row_type row = 0; row < nrows(); ++row) {
2565 // No Wed browser supports mlabeledtr in 2023, even though it has been introduced in
2566 // MathML 2 (2003). Moreover, it is not supported in MathML 4 Core.
2569 for (col_type col = 0; col < ncols(); ++col) {
2571 << cell(index(row, col))
2576 if (haveNumbers()) {
2578 docstring const & num = numbers_[row];
2580 ms << MTagInline("mtext") << '(' << num << ')' << ETagInline("mtext");
2587 ms << ETag("mtable");
2591 void InsetMathHull::mathAsLatex(TeXMathStream & os) const
2593 MathEnsurer ensurer(os, false);
2594 bool const havenumbers = haveNumbers();
2595 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2598 os << cell(index(0, 0));
2602 os << "<table class='mathtable'>";
2603 for (row_type row = 0; row < nrows(); ++row) {
2605 for (col_type col = 0; col < ncols(); ++col) {
2606 os << "<td class='math'>";
2607 os << cell(index(row, col));
2612 docstring const & num = numbers_[row];
2614 os << '(' << num << ')';
2623 docstring InsetMathHull::xhtml(XMLStream & xs, OutputParams const & op) const
2625 BufferParams::MathOutput const mathtype =
2626 buffer().masterBuffer()->params().html_math_output;
2628 bool success = false;
2630 // we output all the labels just at the beginning of the equation.
2631 // this should be fine.
2632 for (size_t i = 0; i != label_.size(); ++i) {
2633 InsetLabel const * const il = label_[i];
2639 // FIXME Eventually we would like to do this inset by inset.
2640 if (mathtype == BufferParams::MathML) {
2641 odocstringstream os;
2642 MathMLStream ms(os);
2646 } catch (MathExportException const &) {}
2648 string const name_space_declaration = "xmlns='http://www.w3.org/1998/Math/MathML'";
2649 if (getType() == hullSimple)
2650 xs << xml::StartTag("math", name_space_declaration, true);
2652 if (!xs.isLastTagCR())
2654 xs << xml::StartTag("math", name_space_declaration + " display='block'", true);
2657 xs << XMLStream::ESCAPE_NONE
2660 if (!xs.isLastTagCR())
2662 xs << xml::EndTag("math") << xml::CR();
2664 // In case of failure, generate an image.
2665 } else if (mathtype == BufferParams::HTML) {
2666 odocstringstream os;
2671 } catch (MathExportException const &) {}
2673 string const tag = (getType() == hullSimple) ? "span" : "div";
2674 xs << xml::StartTag(tag, "class='formula'", true)
2675 << XMLStream::ESCAPE_NONE
2677 << xml::EndTag(tag);
2679 // In case of failure, generate an image.
2682 // what we actually want is this:
2684 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2686 // || mathtype == BufferParams::Images
2688 // but what follows is equivalent, since we'll enter only if either (a) we
2689 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2690 // aren't doing LaTeX.
2692 // so this is for Images.
2693 if (!success && mathtype != BufferParams::LaTeX) {
2694 graphics::PreviewImage const * pimage = nullptr;
2696 loadPreview(docit_);
2697 pimage = preview_->getPreviewImage(buffer());
2698 // FIXME Do we always have png?
2701 if (pimage || op.dryrun) {
2702 string const filename = pimage ? pimage->filename().onlyFileName()
2703 : "previewimage.png";
2705 // if we are not in the master buffer, then we need to see that the
2706 // generated image is copied there; otherwise, preview fails.
2707 Buffer const * mbuf = buffer().masterBuffer();
2708 if (mbuf != &buffer()) {
2709 string mbtmp = mbuf->temppath();
2710 FileName const mbufimg(support::addName(mbtmp, filename));
2711 pimage->filename().copyTo(mbufimg);
2713 // add the file to the list of files to be exported
2714 op.exportdata->addExternalFile("xhtml", pimage->filename());
2717 string const tag = (getType() == hullSimple) ? "span" : "div";
2719 << xml::StartTag(tag, "style = \"text-align: center;\"")
2720 << xml::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2727 // so we'll pass this test if we've failed everything else, or
2728 // if mathtype was LaTeX, since we won't have entered any of the
2730 if (!success /* || mathtype != BufferParams::LaTeX */) {
2731 // Unfortunately, we cannot use latexString() because we do not want
2732 // $...$ or whatever.
2733 odocstringstream ls;
2734 otexrowstream ots(ls);
2735 TeXMathStream wi(ots, false, true, TeXMathStream::wsPreview);
2736 ModeSpecifier specifier(wi, MATH_MODE);
2738 docstring const latex = ls.str();
2740 // class='math' allows for use of jsMath
2741 // http://www.math.union.edu/~dpvc/jsMath/
2743 // probably should allow for some kind of customization here
2744 string const tag = (getType() == hullSimple) ? "span" : "div";
2745 xs << xml::StartTag(tag, "class='math'")
2754 void InsetMathHull::toString(odocstream & os) const
2756 odocstringstream ods;
2757 plaintext(ods, OutputParams(nullptr));
2762 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2764 odocstringstream ods;
2765 OutputParams op(nullptr);
2767 // FIXME: this results in spilling TeX into the LyXHTML output since the
2768 // outliner is used to generate the LyXHTML list of figures/etc.
2774 string InsetMathHull::contextMenuName() const
2776 return "context-math";
2780 void InsetMathHull::recordLocation(DocIterator const & di)
2786 bool InsetMathHull::canPaintChange(BufferView const &) const
2788 // We let RowPainter do it seamlessly for inline insets