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]->addToToc(pit, output_active, utype, backend);
318 docstring label = nicelabel(row);
320 // this is the only equation
321 b.argumentItem(label);
323 // insert as sub-items
324 b.pushItem(pit, label, output_active);
332 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
334 if (previewState(&cur.bv())) {
338 return InsetMathNest::editXY(cur, x, y);
342 InsetMath::mode_type InsetMathHull::currentMode() const
346 return UNDECIDED_MODE;
348 // definitely math mode ...
368 // FIXME: InsetMathGrid should be changed to let the real column alignment be
369 // given by a virtual method like displayColAlign, because the values produced
370 // by defaultColAlign can be invalidated by lfuns such as add-column. For the
371 // moment the values produced by defaultColAlign are not used, notably because
372 // alignment is not implemented in the LyXHTML output.
373 char InsetMathHull::defaultColAlign(col_type col)
375 return colAlign(type_, col);
379 char InsetMathHull::displayColAlign(idx_type idx) const
383 row_type const r = row(idx);
386 if (r == nrows() - 1)
397 return colAlign(type_, col(idx));
401 return InsetMathGrid::displayColAlign(idx);
405 int InsetMathHull::displayColSpace(col_type col) const
407 return colSpace(type_, col);
411 // FIXME: same comment as for defaultColAlign applies.
412 int InsetMathHull::defaultColSpace(col_type col)
414 return colSpace(type_, col);
418 string InsetMathHull::standardFont() const
424 return "lyxnochange";
431 ColorCode InsetMathHull::standardColor() const
436 return Color_foreground;
444 bool InsetMathHull::previewState(const BufferView *const bv) const
446 if (!editing(bv) && RenderPreview::previewMath()
447 && type_ != hullRegexp)
449 graphics::PreviewImage const * pimage =
450 preview_->getPreviewImage(bv->buffer());
451 return pimage && pimage->image();
458 const int ERROR_FRAME_WIDTH = 2;
460 bool previewTooSmall(Dimension const & dim)
462 return dim.width() <= 10 && dim.height() <= 10;
467 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
469 /* Compute \(above|below)displayskip
470 true value in LaTeX is 10pt plus 2pt minus 5pt (in normal size at 10pt)
471 But we use a fixed number of pixels and scale them with zoom.
473 int const bottom_display_margin = mi.base.bv->zoomedPixels(6);
474 int top_display_margin = bottom_display_margin;
475 // at start of paragraph, add an empty line
477 top_display_margin += theFontMetrics(mi.base.font).maxHeight() + 2;
479 int const ind = indent(*mi.base.bv);
482 if (previewState(mi.base.bv)) {
483 preview_->metrics(mi, dim);
484 if (previewTooSmall(dim)) {
485 // preview image is too small
486 dim.wid += 2 * ERROR_FRAME_WIDTH;
487 dim.asc += 2 * ERROR_FRAME_WIDTH;
489 // insert a gap in front of the formula
490 // value was hardcoded to 1 pixel
491 dim.wid += mi.base.bv->zoomedPixels(1) ;
493 dim.asc += top_display_margin;
494 dim.des += bottom_display_margin;
501 Changer dummy1 = mi.base.changeFontSet(standardFont());
502 Changer dummy2 = mi.base.font.changeStyle(display() ? DISPLAY_STYLE
505 // let the cells adjust themselves
506 InsetMathGrid::metrics(mi, dim);
509 // Check whether the numbering interferes with the equations
510 if (numberedType()) {
511 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
512 int extra_offset = 0;
514 for (row_type row = 0; row < nrows(); ++row) {
515 rowinfo(row).offset[mi.base.bv] += extra_offset;
516 docstring const nl = nicelabel(row);
520 mathed_string_dim(mi.base.font, nl, dimnl);
521 int const x = ind ? ind : (mi.base.textwidth - dim.wid) / 2;
522 // for some reason metrics does not trigger at the
523 // same point as draw, and therefore we use >= instead of >
524 if ((math_number == BufferParams::LEFT && dimnl.wid >= x)
525 || (math_number == BufferParams::RIGHT
526 && dimnl.wid >= mi.base.textwidth - x - dim.wid)) {
527 extra_offset += dimnl.height();
528 } else if (dimnl.wid > max_nlwid)
529 max_nlwid = dimnl.wid;
531 mi.extrawidth += max_nlwid;
532 dim.des += extra_offset;
537 dim.asc += top_display_margin;
538 dim.des += bottom_display_margin;
541 // reserve some space for marker.
546 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
548 BufferView const * const bv = pi.base.bv;
549 if (previewState(bv)) {
550 Dimension const dim = dimension(*pi.base.bv);
551 if (previewTooSmall(dim))
553 return graphics::PreviewLoader::backgroundColor();
559 void InsetMathHull::drawMarkers(PainterInfo & pi, int x, int y) const
561 ColorCode pen_color = mouseHovered(pi.base.bv) || editing(pi.base.bv)?
562 Color_mathframe : Color_mathcorners;
563 // If the corners have the same color as the background, do not paint them.
564 if (lcolor.getX11HexName(Color_mathbg) == lcolor.getX11HexName(pen_color))
567 Inset::drawMarkers(pi, x, y);
568 Dimension const dim = dimension(*pi.base.bv);
569 int const t = x + dim.width() - 1;
570 int const a = y - dim.ascent();
571 pi.pain.line(x, a + 3, x, a, pen_color);
572 pi.pain.line(t, a + 3, t, a, pen_color);
573 pi.pain.line(x, a, x + 3, a, pen_color);
574 pi.pain.line(t - 3, a, t, a, pen_color);
578 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
580 Dimension const dim = dimension(*pi.base.bv);
581 if (previewTooSmall(dim)) {
582 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
583 dim.wid, dim.asc + dim.des, backgroundColor(pi));
587 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
588 dim.height() - 1, pi.backgroundColor(this));
592 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
594 BufferView const * const bv = pi.base.bv;
595 Dimension const dim = dimension(*bv);
597 if (type_ == hullRegexp)
598 pi.pain.rectangle(x + 2, y - dim.ascent() + 1,
599 dim.width() - 3, dim.height() - 2, Color_regexpframe);
601 if (previewState(bv)) {
602 // Do not draw change tracking cue if taken care of by RowPainter
604 Changer dummy = !canPaintChange(*bv) ? changeVar(pi.change, Change())
606 if (previewTooSmall(dim)) {
607 // we have an extra frame
608 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
610 // one pixel gap in front
611 // value was hardcoded to 1 pixel
612 int const gap = pi.base.bv->zoomedPixels(1) ;
613 preview_->draw(pi, x + gap, y);
618 // First draw the numbers
619 if (numberedType()) {
620 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
621 for (row_type row = 0; row < nrows(); ++row) {
622 int yy = y + rowinfo(row).offset[bv];
623 docstring const nl = nicelabel(row);
625 mathed_string_dim(pi.base.font, nl, dimnl);
626 if (math_number == BufferParams::LEFT) {
627 ColorCode const col = pi.selected_left
628 ? Color_selectiontext
629 : pi.base.font.color();
630 Changer dummy0 = pi.base.font.changeColor(col);
631 if (dimnl.wid > x - pi.leftx)
632 yy += rowinfo(row).descent + dimnl.asc;
633 pi.pain.fillRectangle(pi.leftx, yy - dimnl.asc,
634 dimnl.width(), dimnl.height(),
635 pi.selected_left ? Color_selection : pi.background_color);
636 pi.draw(pi.leftx, yy, nl);
638 ColorCode const col = pi.selected_right
639 ? Color_selectiontext
640 : pi.base.font.color();
641 Changer dummy0 = pi.base.font.changeColor(col);
642 if (dimnl.wid > pi.rightx - x - dim.wid)
643 yy += rowinfo(row).descent + dimnl.asc;
644 pi.pain.fillRectangle(pi.rightx - dimnl.wid, yy - dimnl.asc,
645 dimnl.width(), dimnl.height(),
646 pi.selected_right ? Color_selection : pi.background_color);
647 pi.draw(pi.rightx - dimnl.wid, yy, nl);
652 // Then the equations
653 ColorCode color = pi.selected && lyxrc.use_system_colors
654 ? Color_selectiontext : standardColor();
655 bool const really_change_color = pi.base.font.color() == Color_none;
656 Changer dummy0 = really_change_color ? pi.base.font.changeColor(color)
658 Changer dummy1 = pi.base.changeFontSet(standardFont());
659 Changer dummy2 = pi.base.font.changeStyle(display() ? DISPLAY_STYLE
661 InsetMathGrid::draw(pi, x + 1, y);
662 drawMarkers(pi, x, y);
664 // drawing change line
665 if (canPaintChange(*bv)) {
667 int const display_margin = display() ? pi.base.inPixels(Length(12, Length::PT)) : 0;
668 pi.change.paintCue(pi, x + 1, y + 1 - dim.asc + display_margin,
669 x + dim.wid, y + dim.des - display_margin);
674 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
677 InsetMathGrid::metricsT(mi, dim);
680 otexrowstream ots(os);
681 TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault);
683 dim.wid = os.str().size();
690 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
693 InsetMathGrid::drawT(pain, x, y);
696 otexrowstream ots(os);
697 TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault);
699 pain.draw(x, y, os.str().c_str());
704 static docstring latexString(InsetMathHull const & inset)
707 // This has to be static, because a preview snippet or a math
708 // macro containing math in text mode (such as $\text{$\phi$}$ or
709 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
710 // first time as a whole, and the second time only the inner math.
711 // In this last case inset.buffer() would be invalid.
712 static Encoding const * encoding = nullptr;
713 if (inset.isBufferValid())
714 encoding = &(inset.buffer().params().encoding());
715 otexrowstream ots(ls);
716 TeXMathStream wi(ots, false, true, TeXMathStream::wsPreview, encoding);
722 void InsetMathHull::initUnicodeMath() const
724 // Trigger classification of the unicode symbols in this inset
725 docstring const dummy = latexString(*this);
729 void InsetMathHull::addPreview(DocIterator const & inset_pos,
730 graphics::PreviewLoader & /*ploader*/) const
732 if (RenderPreview::previewMath()) {
733 preparePreview(inset_pos);
738 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
739 MacroNameSet & macros, MacroNameSet & defs) const
741 MacroNameSet::iterator const end = macros.end();
743 for (size_t i = 0; i < md.size(); ++i) {
744 InsetMathMacro const * mi = md[i].nucleus()->asMacro();
745 InsetMathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
746 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
747 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
748 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
749 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
751 // Look for macros in the arguments of this macro.
752 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
753 usedMacros(mi->cell(idx), pos, macros, defs);
754 // Make sure this is a macro defined in the document
755 // (as we also spot the macros in the symbols file)
756 // or that we have not already accounted for it.
757 docstring const name = mi->name();
758 if (macros.find(name) == end)
761 // Look for macros in the definition of this macro.
762 MathData ar(pos.buffer());
763 MacroData const * data =
764 pos.buffer()->getMacro(name, pos, true);
766 odocstringstream macro_def;
767 data->write(macro_def, true);
769 defs.insert(macro_def.str());
770 asArray(data->definition(), ar);
772 usedMacros(ar, pos, macros, defs);
774 MathData ar(pos.buffer());
775 asArray(mt->definition(), ar);
776 usedMacros(ar, pos, macros, defs);
778 if (!si->nuc().empty())
779 usedMacros(si->nuc(), pos, macros, defs);
781 usedMacros(si->down(), pos, macros, defs);
783 usedMacros(si->up(), pos, macros, defs);
784 } else if (fi || gi) {
785 idx_type nidx = fi ? fi->nargs() : gi->nargs();
786 for (idx_type idx = 0; idx < nidx; ++idx)
787 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
790 usedMacros(ni->cell(0), pos, macros, defs);
796 void InsetMathHull::preparePreview(DocIterator const & pos,
797 bool forexport) const
799 // there is no need to do all the macro stuff if we're not
800 // actually going to generate the preview.
801 if (!RenderPreview::previewMath() && !forexport)
804 Buffer const * buffer = pos.buffer();
806 // collect macros at this position
808 buffer->listMacroNames(macros);
810 // collect definitions only for the macros used in this inset
812 for (idx_type idx = 0; idx < nargs(); ++idx)
813 usedMacros(cell(idx), pos, macros, defs);
815 docstring macro_preamble;
816 for (auto const & defvar : defs)
817 macro_preamble.append(defvar);
819 // set the font series and size for this snippet
820 DocIterator dit = pos.getInnerText();
821 Paragraph const & par = dit.paragraph();
822 Font font = par.getFontSettings(buffer->params(), dit.pos());
823 font.fontInfo().realize(par.layout().font);
824 string const lsize = font.latexSize();
827 if (font.fontInfo().series() == BOLD_SERIES) {
828 setfont += from_ascii("\\textbf{");
831 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
832 setfont += from_ascii("\\" + lsize + '\n');
834 docstring const snippet = macro_preamble + setfont + latexString(*this) + endfont;
835 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
836 preview_->addPreview(snippet, *buffer, forexport);
840 void InsetMathHull::reloadPreview(DocIterator const & pos) const
843 preview_->startLoading(*pos.buffer());
847 void InsetMathHull::loadPreview(DocIterator const & pos) const
849 bool const forexport = true;
850 preparePreview(pos, forexport);
851 preview_->startLoading(*pos.buffer(), forexport);
855 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
857 if (RenderPreview::previewMath()) {
859 cur.screenUpdateFlags(Update::Force);
865 docstring InsetMathHull::label(row_type row) const
867 LASSERT(row < nrows(), return docstring());
868 if (InsetLabel * il = label_[row])
869 return il->screenLabel();
874 void InsetMathHull::label(row_type row, docstring const & label)
876 //lyxerr << "setting label '" << label << "' for row " << row << endl;
880 label_[row] = dummy_pointer;
883 label_[row]->updateLabelAndRefs(label);
885 label_[row]->setParam("name", label);
889 InsetCommandParams p(LABEL_CODE);
891 label_[row] = new InsetLabel(buffer_, p);
893 label_[row]->setBuffer(buffer());
897 void InsetMathHull::numbered(row_type row, Numbered num)
899 numbered_[row] = num;
903 bool InsetMathHull::numbered(row_type row) const
905 return numbered_[row] == NUMBER;
909 bool InsetMathHull::ams() const
929 for (auto const & row : numbered_)
936 bool InsetMathHull::outerDisplay() const
959 int InsetMathHull::rowFlags() const
976 if (buffer().params().is_math_indent)
977 return Display | AlignLeft;
986 int InsetMathHull::indent(BufferView const & bv) const
988 // FIXME: set this in the textclass. This value is what the article class uses.
989 static Length default_indent(2.5, Length::EM);
990 if (display() && buffer().params().is_math_indent) {
991 Length const & len = buffer().params().getMathIndent();
993 return bv.inPixels(default_indent);
995 return bv.inPixels(len);
997 return Inset::indent(bv);
1001 bool InsetMathHull::numberedType() const
1020 for (row_type row = 0; row < nrows(); ++row)
1027 void InsetMathHull::validate(LaTeXFeatures & features) const
1029 if (features.runparams().isLaTeX()) {
1031 features.require("amsmath");
1033 if (type_ == hullRegexp) {
1034 features.require("color");
1035 docstring frcol = from_utf8(lcolor.getLaTeXName(Color_regexpframe));
1036 docstring bgcol = from_ascii("white");
1037 features.addPreambleSnippet(
1038 "\\newcommand{\\regexp}[1]{\\fcolorbox{"
1040 + bgcol + "}{\\ensuremath{\\mathtt{#1}}}}");
1041 features.addPreambleSnippet(
1042 from_ascii("\\newcommand{\\endregexp}{}"));
1043 } else if (outerDisplay() && features.inDeletedInset()) {
1044 features.require("tikz");
1045 features.require("ct-tikz-object-sout");
1048 // Validation is necessary only if not using AMS math.
1049 // To be safe, we will always run mathedvalidate.
1050 //if (features.amsstyle)
1053 //features.binom = true;
1054 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
1055 // it would be better to do this elsewhere, but we can't validate in
1056 // InsetMathMatrix and we have no way, outside MathExtern, to know if
1057 // we even have any matrices.
1058 features.addCSSSnippet(
1059 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
1060 "table.matrix td{padding: 0.25px;}\n"
1061 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
1062 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
1064 InsetMathGrid::validate(features);
1068 CtObject InsetMathHull::getCtObject(OutputParams const & runparams) const
1070 CtObject res = CtObject::Normal;
1086 case hullMultline: {
1087 if (runparams.inulemcmd
1088 && (!runparams.local_font || runparams.local_font->fontInfo().strikeout() != FONT_ON))
1089 res = CtObject::UDisplayObject;
1091 res = CtObject::DisplayObject;
1099 void InsetMathHull::header_write(TeXMathStream & os) const
1101 bool n = numberedType();
1112 if (cell(0).empty())
1117 writeMathdisplayPreamble(os);
1121 os << "\\begin{equation" << star(n) << "}\n";
1131 writeMathdisplayPreamble(os);
1134 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1141 os << "\\begin{" << hullName(type_) << star(n) << '}'
1142 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1148 os << "\\begin{" << hullName(type_) << '}'
1149 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1159 os << "\\begin{unknown" << star(n) << "}\n";
1165 void InsetMathHull::footer_write(TeXMathStream & os) const
1167 bool n = numberedType();
1184 os << "\\end{equation" << star(n) << "}\n";
1187 writeMathdisplayPostamble(os);
1197 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1198 writeMathdisplayPostamble(os);
1205 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1211 os << "\\end{" << hullName(type_) << "}\n";
1215 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1216 os << "\\endregexp{}}";
1222 os << "\\end{unknown" << star(n) << "}\n";
1228 bool InsetMathHull::allowsTabularFeatures() const
1251 bool InsetMathHull::rowChangeOK() const
1254 type_ == hullEqnArray || type_ == hullAlign ||
1255 type_ == hullFlAlign || type_ == hullAlignAt ||
1256 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1257 type_ == hullGather || type_ == hullMultline;
1261 bool InsetMathHull::colChangeOK() const
1264 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1265 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1269 void InsetMathHull::addRow(row_type row)
1274 bool numbered = numberedType();
1275 // Move the number and raw pointer, do not call label() (bug 7511)
1276 InsetLabel * label = dummy_pointer;
1277 docstring number = empty_docstring();
1278 if (type_ == hullMultline) {
1279 if (row + 1 == nrows()) {
1280 numbered_[row] = NONUMBER;
1281 swap(label, label_[row]);
1282 swap(number, numbers_[row]);
1287 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1288 numbers_.insert(numbers_.begin() + row + 1, number);
1289 label_.insert(label_.begin() + row + 1, label);
1290 InsetMathGrid::addRow(row);
1294 void InsetMathHull::swapRow(row_type row)
1298 if (row + 1 == nrows())
1300 swap(numbered_[row], numbered_[row + 1]);
1301 swap(numbers_[row], numbers_[row + 1]);
1302 swap(label_[row], label_[row + 1]);
1303 InsetMathGrid::swapRow(row);
1307 void InsetMathHull::delRow(row_type row)
1309 if (nrows() <= 1 || !rowChangeOK())
1311 if (row + 1 == nrows() && type_ == hullMultline) {
1312 swap(numbered_[row - 1], numbered_[row]);
1313 swap(numbers_[row - 1], numbers_[row]);
1314 swap(label_[row - 1], label_[row]);
1315 InsetMathGrid::delRow(row);
1318 InsetMathGrid::delRow(row);
1319 // The last dummy row has no number info nor a label.
1320 // Test nrows() + 1 because we have already erased the row.
1321 if (row == nrows() + 1)
1323 numbered_.erase(numbered_.begin() + row);
1324 numbers_.erase(numbers_.begin() + row);
1326 label_.erase(label_.begin() + row);
1330 void InsetMathHull::addCol(col_type col)
1334 InsetMathGrid::addCol(col);
1338 void InsetMathHull::delCol(col_type col)
1340 if (ncols() <= 1 || !colChangeOK())
1342 InsetMathGrid::delCol(col);
1346 docstring InsetMathHull::nicelabel(row_type row) const
1348 if (!numbered(row)) {
1351 return '[' + label_[row]->screenLabel() + ']';
1353 docstring const & val = numbers_[row];
1355 return '(' + val + ')';
1356 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1360 void InsetMathHull::glueall(HullType type)
1363 for (idx_type i = 0; i < nargs(); ++i)
1365 InsetLabel * label = nullptr;
1366 if (type == hullEquation) {
1367 // preserve first non-empty label
1368 for (row_type row = 0; row < nrows(); ++row) {
1370 label = label_[row];
1376 *this = InsetMathHull(buffer_, hullSimple);
1383 void InsetMathHull::splitTo2Cols()
1385 LASSERT(ncols() == 1, return);
1386 InsetMathGrid::addCol(1);
1387 for (row_type row = 0; row < nrows(); ++row) {
1388 idx_type const i = 2 * row;
1389 pos_type pos = firstRelOp(cell(i));
1390 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1391 cell(i).erase(pos, cell(i).size());
1396 void InsetMathHull::splitTo3Cols()
1398 LASSERT(ncols() < 3, return);
1401 InsetMathGrid::addCol(2);
1402 for (row_type row = 0; row < nrows(); ++row) {
1403 idx_type const i = 3 * row + 1;
1404 if (!cell(i).empty()) {
1405 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1406 cell(i).erase(1, cell(i).size());
1412 void InsetMathHull::changeCols(col_type cols)
1414 if (ncols() == cols)
1416 else if (ncols() < cols) {
1422 while (ncols() < cols)
1423 InsetMathGrid::addCol(ncols());
1429 for (row_type row = 0; row < nrows(); ++row) {
1430 idx_type const i = row * ncols();
1431 for (col_type col = cols; col < ncols(); ++col) {
1432 cell(i + cols - 1).append(cell(i + col));
1436 while (ncols() > cols) {
1437 InsetMathGrid::delCol(ncols() - 1);
1442 HullType InsetMathHull::getType() const
1448 void InsetMathHull::setType(HullType type)
1455 bool InsetMathHull::isMutable(HullType type)
1479 void InsetMathHull::mutate(HullType newtype)
1481 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1483 if (newtype == type_)
1486 // This guards the algorithm below it, which is designed with certain types
1488 if (!isMutable(newtype) || !isMutable(type_)) {
1489 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1490 << "' to '" << to_utf8(hullName(newtype))
1491 << "' not implemented" << endl;
1495 // we try to move along the chain
1496 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1498 // +-------------------------------------+
1499 // we use eqnarray as intermediate type for mutations that are not
1500 // directly supported because it handles labels and numbering for
1505 setType(hullSimple);
1511 if (newtype == hullNone) {
1515 setType(hullEquation);
1516 numbered(0, label_[0] != nullptr);
1525 setType(hullSimple);
1530 // split it "nicely" on the first relop
1532 setType(hullEqnArray);
1540 // split it "nicely"
1575 setType(hullEqnArray);
1584 for (row_type row = 0; row < nrows(); ++row)
1585 numbered(row, false);
1595 for (row_type row = 0; row < nrows(); ++row)
1596 numbered(row, false);
1603 setType(hullEqnArray);
1633 for (row_type row = 0; row < nrows(); ++row)
1634 numbered(row, false);
1638 // first we mutate to EqnArray
1640 setType(hullEqnArray);
1647 // we passed the guard so we should not be here
1648 LYXERR0("Mutation not implemented, but should have been.");
1649 LASSERT(false, return);
1655 void InsetMathHull::eol(TeXMathStream & os, row_type row, bool fragile, bool latex,
1656 bool last_eoln) const
1658 if (numberedType()) {
1660 docstring const name =
1661 latex ? escape(label_[row]->getParam("name"))
1662 : label_[row]->getParam("name");
1663 os << "\\label{" + name + '}';
1665 if (type_ != hullMultline) {
1666 if (numbered_[row] == NONUMBER)
1667 os << "\\nonumber ";
1668 else if (numbered_[row] == NOTAG)
1671 if (os.output() == TeXMathStream::wsPreview && !numbers_[row].empty()) {
1672 os << "\\global\\def\\theequation{" << numbers_[row] << "}\n";
1676 // Never add \\ on the last empty line of eqnarray and friends
1678 InsetMathGrid::eol(os, row, fragile, latex, last_eoln);
1681 void InsetMathHull::write(TeXMathStream & os) const
1683 ModeSpecifier specifier(os, MATH_MODE);
1685 InsetMathGrid::write(os);
1690 void InsetMathHull::normalize(NormalStream & os) const
1692 os << "[formula " << hullName(type_) << ' ';
1693 InsetMathGrid::normalize(os);
1698 void InsetMathHull::infoize(odocstream & os) const
1700 os << bformat(_("Type: %1$s"), hullName(type_));
1704 void InsetMathHull::check() const
1706 LATTEST(numbered_.size() == nrows());
1707 LATTEST(numbers_.size() == nrows());
1708 LATTEST(label_.size() == nrows());
1712 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1714 //FIXME: sort out whether we want std::string or docstring for those
1715 string const lang = func.getArg(0);
1716 docstring extra = from_utf8(func.getArg(1));
1718 extra = from_ascii("noextra");
1720 // replace selection with result of computation
1721 if (reduceSelectionToOneCell(cur)) {
1723 asArray(grabAndEraseSelection(cur), ar);
1724 lyxerr << "use selection: " << ar << endl;
1725 cur.insert(pipeThroughExtern(lang, extra, ar));
1729 // only inline, display or eqnarray math is allowed
1730 switch (getType()) {
1736 frontend::Alert::warning(_("Bad math environment"),
1737 _("Computation cannot be performed for AMS "
1738 "math environments.\nChange the math "
1739 "formula type and try again."));
1744 eq.push_back(MathAtom(new InsetMathChar('=')));
1746 // go to first item in line
1747 cur.idx() -= cur.idx() % ncols();
1750 if (getType() == hullSimple) {
1751 size_type pos = cur.cell().find_last(eq);
1753 if (pos == cur.cell().size()) {
1755 lyxerr << "use whole cell: " << ar << endl;
1757 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1758 lyxerr << "use partial cell form pos: " << pos << endl;
1760 cur.cell().append(eq);
1761 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1762 cur.pos() = cur.lastpos();
1766 if (getType() == hullEquation) {
1767 lyxerr << "use equation inset" << endl;
1768 mutate(hullEqnArray);
1769 MathData & ar = cur.cell();
1770 lyxerr << "use cell: " << ar << endl;
1774 cur.cell() = pipeThroughExtern(lang, extra, ar);
1775 // move to end of line
1776 cur.pos() = cur.lastpos();
1781 lyxerr << "use eqnarray" << endl;
1782 cur.idx() += 2 - cur.idx() % ncols();
1784 MathData ar = cur.cell();
1785 lyxerr << "use cell: " << ar << endl;
1786 // FIXME: temporarily disabled
1792 cur.cell() = pipeThroughExtern(lang, extra, ar);
1793 cur.pos() = cur.lastpos();
1798 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1800 //lyxerr << "action: " << cmd.action() << endl;
1801 switch (cmd.action()) {
1803 case LFUN_FINISHED_BACKWARD:
1804 case LFUN_FINISHED_FORWARD:
1805 case LFUN_FINISHED_RIGHT:
1806 case LFUN_FINISHED_LEFT:
1807 //lyxerr << "action: " << cmd.action() << endl;
1808 InsetMathGrid::doDispatch(cur, cmd);
1811 case LFUN_PARAGRAPH_BREAK:
1812 // just swallow this
1815 case LFUN_NEWLINE_INSERT:
1816 // some magic for the common case
1817 if (type_ == hullSimple || type_ == hullEquation) {
1818 cur.recordUndoInset();
1820 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1821 mutate(align ? hullAlign : hullEqnArray);
1822 // mutate() may change labels and such.
1823 cur.forceBufferUpdate();
1824 cur.idx() = nrows() * ncols() - 1;
1825 cur.pos() = cur.lastpos();
1827 InsetMathGrid::doDispatch(cur, cmd);
1830 case LFUN_MATH_NUMBER_TOGGLE: {
1831 //lyxerr << "toggling all numbers" << endl;
1832 cur.recordUndoInset();
1833 bool old = numberedType();
1834 if (type_ == hullMultline) {
1835 row_type row = nrows() - 1;
1836 numbered(row, !old);
1837 if (old && label_[row]) {
1842 for (row_type row = 0; row < nrows(); ++row) {
1843 numbered(row, !old);
1844 if (old && label_[row]) {
1851 cur.message(old ? _("No number") : _("Number"));
1852 cur.forceBufferUpdate();
1856 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1857 cur.recordUndoInset();
1858 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1859 bool old = numbered(r);
1860 cur.message(old ? _("No number") : _("Number"));
1862 if (old && label_[r]) {
1866 cur.forceBufferUpdate();
1870 case LFUN_LABEL_INSERT: {
1871 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1872 docstring old_label = label(r);
1873 docstring const default_label = from_ascii("eq:");
1874 if (old_label.empty())
1875 old_label = default_label;
1877 InsetCommandParams p(LABEL_CODE);
1878 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1879 string const data = InsetCommand::params2string(p);
1881 if (cmd.argument().empty())
1882 cur.bv().showDialog("label", data);
1884 FuncRequest fr(LFUN_INSET_INSERT, data);
1890 case LFUN_LABEL_COPY_AS_REFERENCE: {
1892 if (cmd.argument().empty() && &cur.inset() == this)
1893 // if there is no argument and we're inside math, we retrieve
1894 // the row number from the cursor position.
1895 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1897 // if there is an argument, find the corresponding label, else
1898 // check whether there is at least one label.
1899 for (row = 0; row != nrows(); ++row)
1901 && (cmd.argument().empty() || label(row) == cmd.argument()))
1908 InsetCommandParams p(REF_CODE, "ref");
1909 p["reference"] = label(row);
1910 cap::clearSelection();
1911 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1915 case LFUN_WORD_DELETE_FORWARD:
1916 case LFUN_CHAR_DELETE_FORWARD:
1917 if (col(cur.idx()) + 1 == ncols()
1918 && cur.pos() == cur.lastpos()
1919 && !cur.selection()) {
1920 if (!label(row(cur.idx())).empty()) {
1921 cur.recordUndoInset();
1922 label(row(cur.idx()), docstring());
1923 } else if (numbered(row(cur.idx()))) {
1924 cur.recordUndoInset();
1925 numbered(row(cur.idx()), false);
1926 cur.forceBufferUpdate();
1928 InsetMathGrid::doDispatch(cur, cmd);
1932 InsetMathGrid::doDispatch(cur, cmd);
1937 case LFUN_INSET_INSERT: {
1938 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1939 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1940 string const name = cmd.getArg(0);
1941 if (name == "label") {
1942 InsetCommandParams p(LABEL_CODE);
1943 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1944 docstring str = p["name"];
1945 cur.recordUndoInset();
1946 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1950 docstring old = label(r);
1953 // The label will take care of the reference update.
1957 // Newly created inset so initialize it.
1958 label_[r]->initView();
1961 cur.forceBufferUpdate();
1964 InsetMathGrid::doDispatch(cur, cmd);
1968 case LFUN_MATH_EXTERN:
1969 cur.recordUndoInset();
1973 case LFUN_MATH_MUTATE: {
1974 cur.recordUndoInset();
1975 row_type row = cur.row();
1976 col_type col = cur.col();
1977 mutate(hullType(cmd.argument()));
1978 cur.idx() = row * ncols() + col;
1979 if (cur.idx() > cur.lastidx()) {
1980 cur.idx() = cur.lastidx();
1981 cur.pos() = cur.lastpos();
1983 if (cur.pos() > cur.lastpos())
1984 cur.pos() = cur.lastpos();
1986 cur.forceBufferUpdate();
1987 // FIXME: find some more clever handling of the selection,
1988 // i.e. preserve it.
1989 cur.clearSelection();
1990 //cur.dispatched(FINISHED);
1994 case LFUN_MATH_DISPLAY: {
1995 cur.recordUndoInset();
1996 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1997 // if the cursor is in a cell that got merged, move it to
1998 // start of the hull inset.
1999 if (cur.idx() > 0) {
2003 if (cur.pos() > cur.lastpos())
2004 cur.pos() = cur.lastpos();
2009 case LFUN_TABULAR_FEATURE:
2010 if (!allowsTabularFeatures())
2013 InsetMathGrid::doDispatch(cur, cmd);
2017 InsetMathGrid::doDispatch(cur, cmd);
2025 bool allowDisplayMath(Cursor const & cur)
2027 LATTEST(cur.depth() > 1);
2028 Cursor tmpcur = cur;
2031 FuncRequest cmd(LFUN_MATH_DISPLAY);
2032 return tmpcur.getStatus(cmd, status) && status.enabled();
2038 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
2039 FuncStatus & status) const
2041 switch (cmd.action()) {
2042 case LFUN_FINISHED_BACKWARD:
2043 case LFUN_FINISHED_FORWARD:
2044 case LFUN_FINISHED_RIGHT:
2045 case LFUN_FINISHED_LEFT:
2048 case LFUN_NEWLINE_INSERT:
2049 case LFUN_MATH_EXTERN:
2051 status.setEnabled(true);
2054 // we never allow this in math, and we want to bind enter
2055 // to another actions in command-alternatives
2056 case LFUN_PARAGRAPH_BREAK:
2057 status.setEnabled(false);
2059 case LFUN_MATH_MUTATE: {
2060 HullType const ht = hullType(cmd.argument());
2061 status.setOnOff(type_ == ht);
2062 status.setEnabled(isMutable(ht) && isMutable(type_));
2064 if (ht != hullSimple && status.enabled())
2065 status.setEnabled(allowDisplayMath(cur));
2068 case LFUN_MATH_DISPLAY: {
2069 status.setEnabled(display() || allowDisplayMath(cur));
2070 status.setOnOff(display());
2074 case LFUN_MATH_NUMBER_TOGGLE:
2075 // FIXME: what is the right test, this or the one of
2077 status.setEnabled(display());
2078 status.setOnOff(numberedType());
2081 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
2082 // FIXME: what is the right test, this or the one of
2084 bool const enable = (type_ == hullMultline)
2085 ? (nrows() - 1 == cur.row())
2087 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2088 status.setEnabled(enable);
2089 status.setOnOff(enable && numbered(r));
2093 case LFUN_LABEL_INSERT:
2094 status.setEnabled(type_ != hullSimple);
2097 case LFUN_LABEL_COPY_AS_REFERENCE: {
2098 bool enabled = false;
2099 if (cmd.argument().empty() && &cur.inset() == this) {
2100 // if there is no argument and we're inside math, we retrieve
2101 // the row number from the cursor position.
2102 row_type row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2103 enabled = numberedType() && label_[row];
2105 // if there is an argument, find the corresponding label, else
2106 // check whether there is at least one label.
2107 for (row_type row = 0; row != nrows(); ++row) {
2109 (cmd.argument().empty() || label(row) == cmd.argument())) {
2115 status.setEnabled(enabled);
2119 case LFUN_INSET_INSERT:
2120 if (cmd.getArg(0) == "label") {
2121 status.setEnabled(type_ != hullSimple);
2124 return InsetMathGrid::getStatus(cur, cmd, status);
2126 case LFUN_TABULAR_FEATURE: {
2127 if (!allowsTabularFeatures())
2129 string s = cmd.getArg(0);
2131 && (s == "append-row"
2132 || s == "delete-row"
2133 || s == "copy-row")) {
2134 status.message(bformat(
2135 from_utf8(N_("Can't change number of rows in '%1$s'")),
2137 status.setEnabled(false);
2141 && (s == "append-column"
2142 || s == "delete-column"
2143 || s == "copy-column")) {
2144 status.message(bformat(
2145 from_utf8(N_("Can't change number of columns in '%1$s'")),
2147 status.setEnabled(false);
2150 if (s == "add-vline-left" || s == "add-vline-right") {
2151 status.message(bformat(
2152 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2154 status.setEnabled(false);
2157 if (s == "valign-top" || s == "valign-middle"
2158 || s == "valign-bottom" || s == "align-left"
2159 || s == "align-center" || s == "align-right") {
2160 status.setEnabled(false);
2163 return InsetMathGrid::getStatus(cur, cmd, status);
2167 return InsetMathGrid::getStatus(cur, cmd, status);
2172 int InsetMathHull::leftMargin() const
2174 return (getType() == hullSimple) ? 0 : InsetMathGrid::leftMargin();
2178 int InsetMathHull::rightMargin() const
2180 return (getType() == hullSimple) ? 0 : InsetMathGrid::rightMargin();
2184 int InsetMathHull::border() const
2186 return (getType() == hullSimple) ? 0 : InsetMathGrid::border();
2190 /////////////////////////////////////////////////////////////////////
2194 // simply scrap this function if you want
2195 void InsetMathHull::mutateToText()
2198 // translate to latex
2200 latex(os, false, false);
2201 string str = os.str();
2204 Text * lt = view_->cursor().innerText();
2205 string::const_iterator cit = str.begin();
2206 string::const_iterator end = str.end();
2207 for (; cit != end; ++cit)
2208 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2211 //dispatch(LFUN_ESCAPE);
2216 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2217 docstring const & font)
2219 // this whole function is a hack and won't work for incremental font
2222 if (cur.inset().asInsetMath()->name() == font)
2223 cur.handleFont(to_utf8(font));
2225 cur.handleNest(createInsetMath(font, cur.buffer()));
2231 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2236 font.fromString(to_utf8(arg), b);
2237 if (font.fontInfo().color() != Color_inherit) {
2238 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2244 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2247 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
2248 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
2249 enter_front ? idxFirst(cur) : idxLast(cur);
2250 // The inset formula dimension is not necessarily the same as the
2251 // one of the instant preview image, so we have to indicate to the
2252 // BufferView that a metrics update is needed.
2253 cur.screenUpdateFlags(Update::Force);
2257 /////////////////////////////////////////////////////////////////////
2261 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2264 // FIXME: completely broken
2265 static InsetMathHull * lastformula = 0;
2266 static CursorBase current = DocIterator(ibegin(nucleus()));
2268 static string laststr;
2270 if (lastformula != this || laststr != str) {
2271 //lyxerr << "reset lastformula to " << this << endl;
2274 current = ibegin(nucleus());
2276 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2280 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2282 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2283 CursorSlice & top = it.back();
2284 MathData const & a = top.asInsetMath()->cell(top.idx_);
2285 if (a.matchpart(ar, top.pos_)) {
2286 bv->cursor().setSelection(it, ar.size());
2288 top.pos_ += ar.size();
2294 //lyxerr << "not found!" << endl;
2301 void InsetMathHull::write(ostream & os) const
2303 odocstringstream oss;
2304 otexrowstream ots(oss);
2305 TeXMathStream wi(ots, false, false, TeXMathStream::wsDefault);
2308 os << to_utf8(oss.str());
2312 void InsetMathHull::read(Lexer & lex)
2315 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2316 operator=(*at->asHullInset());
2320 bool InsetMathHull::readQuiet(Lexer & lex)
2323 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2325 operator=(*at->asHullInset());
2330 int InsetMathHull::plaintext(odocstringstream & os,
2331 OutputParams const & op, size_t max_length) const
2333 // Try enabling this now that there is a flag as requested at #2275.
2334 if (buffer().isExporting() && display()) {
2338 TextPainter tpain(dim.width(), dim.height());
2339 drawT(tpain, 0, dim.ascent());
2341 // reset metrics cache to "real" values
2343 return tpain.textheight();
2346 odocstringstream oss;
2347 otexrowstream ots(oss);
2348 Encoding const * const enc = encodings.fromLyXName("utf8");
2350 TeXMathStream::OutputType ot;
2351 if (op.find_effective())
2352 ot = TeXMathStream::wsSearchAdv;
2354 ot = TeXMathStream::wsDefault;
2356 if (type_ == hullRegexp) {
2357 TeXMathStream wi(ots, false, true, ot, enc);
2361 TeXMathStream wi(ots, false, true, ot, enc);
2362 for (row_type r = 0; r < nrows(); ++r) {
2363 for (col_type c = 0; c < ncols(); ++c)
2364 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2365 // if it's for the TOC, we write just the first line
2366 // and do not include the newline.
2367 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2369 if (r < nrows() - 1)
2373 docstring const str = oss.str();
2379 void InsetMathHull::docbook(XMLStream & xs, OutputParams const & runparams) const {
2380 // Choose the tag around the MathML equation.
2383 if (getType() == hullSimple)
2384 name = from_ascii("inlineequation");
2386 doCR = true; // This is a block equation, always have <informalequation> on its own line.
2387 name = from_ascii("informalequation");
2390 // DocBook also has <equation>, but it comes with a title.
2391 // TODO: recognise \tag from amsmath? This would allow having <equation> with a proper title.
2395 bool mathmlNamespaceInline = buffer().params().docbook_mathml_prefix == BufferParams::NoPrefix;
2396 if (mathmlNamespaceInline)
2397 attr += "xmlns=\"http://www.w3.org/1998/Math/MathML\"";
2399 for (row_type i = 0; i < nrows(); ++i) {
2400 if (!label(i).empty()) {
2404 attr += "xml:id=\"" + xml::cleanID(label(i)) + "\"";
2410 if (!xs.isLastTagCR())
2413 xs << xml::StartTag(name, attr);
2416 // With DocBook 5, MathML must be within its own namespace (defined in Buffer.cpp::writeDocBookSource, except when
2417 // it should be inlined).
2418 // Output everything in a separate stream so that this does not interfere with the standard flow of DocBook tags.
2419 std::string mathmlNamespacePrefix;
2420 if (!mathmlNamespaceInline) {
2421 if (buffer().params().docbook_mathml_prefix == BufferParams::MPrefix)
2422 mathmlNamespacePrefix = "m";
2423 else if (buffer().params().docbook_mathml_prefix == BufferParams::MMLPrefix)
2424 mathmlNamespacePrefix = "mml";
2427 odocstringstream osmath;
2428 MathMLStream ms(osmath, mathmlNamespacePrefix);
2430 // Output the MathML subtree.
2431 // TeX transcription. Avoid MTag/ETag so that there are no extraneous spaces.
2432 ms << "<" << from_ascii("alt") << " role='tex'" << ">";
2433 // Workaround for db2latex: db2latex always includes equations with
2434 // \ensuremath{} or \begin{display}\end{display}
2435 // so we strip LyX' math environment
2436 odocstringstream ls;
2438 TeXMathStream wi(ols, false, false, TeXMathStream::wsDefault, runparams.encoding);
2439 InsetMathGrid::write(wi);
2440 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2441 ms << "</" << from_ascii("alt") << ">";
2443 // Actual transformation of the formula into MathML. This translation may fail (for example, due to custom macros).
2444 // The new output stream is required to deal with the errors: first write completely the formula into this
2445 // temporary stream; then, if it is possible without error, then copy it back to the "real" stream. Otherwise,
2446 // some incomplete tags might be put into the real stream.
2448 // First, generate the MathML expression. If there is an error in the generation, this block is not fully
2449 // executed, and the formula is not output to the DocBook stream.
2450 odocstringstream ostmp;
2451 MathMLStream mstmp(ostmp, ms.xmlns());
2454 // Choose the display style for the formula, to be output as an attribute near the formula root.
2455 std::string mathmlAttr;
2456 if (getType() == hullSimple)
2457 mathmlAttr = "display=\"inline\"";
2459 mathmlAttr = "display=\"block\"";
2461 // Then, output the formula.
2462 ms << MTag("math", mathmlAttr);
2464 osmath << ostmp.str(); // osmath is not a XMLStream, so no need for XMLStream::ESCAPE_NONE.
2466 } catch (MathExportException const &) {
2468 osmath << "<mathphrase>MathML export failed. Please report this as a bug to the LyX developers: "
2469 "https://www.lyx.org/trac.</mathphrase>";
2472 // Output the complete formula to the DocBook stream.
2473 xs << XMLStream::ESCAPE_NONE << osmath.str();
2475 xs << xml::EndTag(name);
2481 bool InsetMathHull::haveNumbers() const
2483 bool havenumbers = false;
2484 // inline formulas are never numbered (bug 7351 part 3)
2485 if (getType() == hullSimple)
2487 for (size_t i = 0; i != numbered_.size(); ++i) {
2498 // We need to do something about alignment here.
2500 // This duplicates code from InsetMathGrid, but
2501 // we need access here to number information,
2502 // and we simply do not have that in InsetMathGrid.
2503 void InsetMathHull::htmlize(HtmlStream & os) const
2505 bool const havenumbers = haveNumbers();
2506 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2509 os << cell(index(0, 0));
2513 os << MTag("table", "class='mathtable'");
2514 for (row_type row = 0; row < nrows(); ++row) {
2516 for (col_type col = 0; col < ncols(); ++col) {
2518 os << cell(index(row, col));
2523 docstring const & num = numbers_[row];
2525 os << '(' << num << ')';
2530 os << ETag("table");
2534 // this duplicates code from InsetMathGrid, but
2535 // we need access here to number information,
2536 // and we simply do not have that in InsetMathGrid.
2537 void InsetMathHull::mathmlize(MathMLStream & ms) const
2539 bool const havetable = haveNumbers() || nrows() > 1 || ncols() > 1;
2541 // Simplest case: single row, single column, no numbering.
2543 ms << cell(index(0, 0));
2547 // More complex case: wrap elements in a table.
2548 if (getType() == hullSimple) {
2549 ms << MTag("mtable");
2550 } else if (getType() >= hullAlign && getType() <= hullXXAlignAt) {
2551 // hullAlign, hullAlignAt, hullXAlignAt, hullXXAlignAt
2553 for (col_type col = 0; col < ncols(); ++col) {
2554 alignment += (col % 2) ? "left " : "right ";
2556 ms << MTag("mtable", "displaystyle='true' columnalign='" + alignment + "'");
2558 ms << MTag("mtable", "displaystyle='true'");
2561 for (row_type row = 0; row < nrows(); ++row) {
2562 // No Wed browser supports mlabeledtr in 2023, even though it has been introduced in
2563 // MathML 2 (2003). Moreover, it is not supported in MathML 4 Core.
2566 for (col_type col = 0; col < ncols(); ++col) {
2568 << cell(index(row, col))
2573 if (haveNumbers()) {
2575 docstring const & num = numbers_[row];
2577 ms << MTagInline("mtext") << '(' << num << ')' << ETagInline("mtext");
2584 ms << ETag("mtable");
2588 void InsetMathHull::mathAsLatex(TeXMathStream & os) const
2590 MathEnsurer ensurer(os, false);
2591 bool const havenumbers = haveNumbers();
2592 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2595 os << cell(index(0, 0));
2599 os << "<table class='mathtable'>";
2600 for (row_type row = 0; row < nrows(); ++row) {
2602 for (col_type col = 0; col < ncols(); ++col) {
2603 os << "<td class='math'>";
2604 os << cell(index(row, col));
2609 docstring const & num = numbers_[row];
2611 os << '(' << num << ')';
2620 docstring InsetMathHull::xhtml(XMLStream & xs, OutputParams const & op) const
2622 BufferParams::MathOutput const mathtype =
2623 buffer().masterBuffer()->params().html_math_output;
2625 bool success = false;
2627 // we output all the labels just at the beginning of the equation.
2628 // this should be fine.
2629 for (size_t i = 0; i != label_.size(); ++i) {
2630 InsetLabel const * const il = label_[i];
2636 // FIXME Eventually we would like to do this inset by inset.
2637 if (mathtype == BufferParams::MathML) {
2638 odocstringstream os;
2639 MathMLStream ms(os);
2643 } catch (MathExportException const &) {}
2645 string const name_space_declaration = "xmlns='http://www.w3.org/1998/Math/MathML'";
2646 if (getType() == hullSimple)
2647 xs << xml::StartTag("math", name_space_declaration, true);
2649 if (!xs.isLastTagCR())
2651 xs << xml::StartTag("math", name_space_declaration + " display='block'", true);
2654 xs << XMLStream::ESCAPE_NONE
2657 if (!xs.isLastTagCR())
2659 xs << xml::EndTag("math") << xml::CR();
2661 // In case of failure, generate an image.
2662 } else if (mathtype == BufferParams::HTML) {
2663 odocstringstream os;
2668 } catch (MathExportException const &) {}
2670 string const tag = (getType() == hullSimple) ? "span" : "div";
2671 xs << xml::StartTag(tag, "class='formula'", true)
2672 << XMLStream::ESCAPE_NONE
2674 << xml::EndTag(tag);
2676 // In case of failure, generate an image.
2679 // what we actually want is this:
2681 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2683 // || mathtype == BufferParams::Images
2685 // but what follows is equivalent, since we'll enter only if either (a) we
2686 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2687 // aren't doing LaTeX.
2689 // so this is for Images.
2690 if (!success && mathtype != BufferParams::LaTeX) {
2691 graphics::PreviewImage const * pimage = nullptr;
2693 loadPreview(docit_);
2694 pimage = preview_->getPreviewImage(buffer());
2695 // FIXME Do we always have png?
2698 if (pimage || op.dryrun) {
2699 string const filename = pimage ? pimage->filename().onlyFileName()
2700 : "previewimage.png";
2702 // if we are not in the master buffer, then we need to see that the
2703 // generated image is copied there; otherwise, preview fails.
2704 Buffer const * mbuf = buffer().masterBuffer();
2705 if (mbuf != &buffer()) {
2706 string mbtmp = mbuf->temppath();
2707 FileName const mbufimg(support::addName(mbtmp, filename));
2708 pimage->filename().copyTo(mbufimg);
2710 // add the file to the list of files to be exported
2711 op.exportdata->addExternalFile("xhtml", pimage->filename());
2714 string const tag = (getType() == hullSimple) ? "span" : "div";
2716 << xml::StartTag(tag, "style = \"text-align: center;\"")
2717 << xml::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2724 // so we'll pass this test if we've failed everything else, or
2725 // if mathtype was LaTeX, since we won't have entered any of the
2727 if (!success /* || mathtype != BufferParams::LaTeX */) {
2728 // Unfortunately, we cannot use latexString() because we do not want
2729 // $...$ or whatever.
2730 odocstringstream ls;
2731 otexrowstream ots(ls);
2732 TeXMathStream wi(ots, false, true, TeXMathStream::wsPreview);
2733 ModeSpecifier specifier(wi, MATH_MODE);
2735 docstring const latex = ls.str();
2737 // class='math' allows for use of jsMath
2738 // http://www.math.union.edu/~dpvc/jsMath/
2740 // probably should allow for some kind of customization here
2741 string const tag = (getType() == hullSimple) ? "span" : "div";
2742 xs << xml::StartTag(tag, "class='math'")
2751 void InsetMathHull::toString(odocstream & os) const
2753 odocstringstream ods;
2754 plaintext(ods, OutputParams(nullptr));
2759 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2761 odocstringstream ods;
2762 OutputParams op(nullptr);
2764 // FIXME: this results in spilling TeX into the LyXHTML output since the
2765 // outliner is used to generate the LyXHTML list of figures/etc.
2771 string InsetMathHull::contextMenuName() const
2773 return "context-math";
2777 void InsetMathHull::recordLocation(DocIterator const & di)
2783 bool InsetMathHull::canPaintChange(BufferView const &) const
2785 // We let RowPainter do it seamlessly for inline insets