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);
277 // set up equation numbers
279 // compute first and last item
280 row_type first = nrows();
281 for (row_type row = 0; row != nrows(); ++row)
286 if (first != nrows()) {
287 row_type last = nrows() - 1;
288 for (; last != 0; --last)
292 for (row_type row = 0; row != nrows(); ++row) {
296 label_[row]->setCounterValue(numbers_[row]);
297 label_[row]->setPrettyCounter("(" + numbers_[row] + ")");
298 label_[row]->setFormattedCounter("(" + numbers_[row] + ")");
304 InsetMathGrid::updateBuffer(it, utype, deleted);
308 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active,
309 UpdateType utype, TocBackend & backend) const
312 //FIXME: buffer_ should be set at creation for this inset! Problem is
313 // This inset is created at too many places (see Parser::parse1() in
318 // compute first and last item
319 row_type first = nrows();
320 for (row_type row = 0; row != nrows(); ++row)
325 if (first == nrows())
328 row_type last = nrows() - 1;
329 for (; last != 0; --last)
333 TocBuilder & b = backend.builder("equation");
334 b.pushItem(pit, docstring(), output_active);
336 b.argumentItem(bformat(from_ascii("(%1$s-%2$s)"),
337 numbers_[first], numbers_[last]));
339 odocstringstream ods;
340 Encoding const * enc = encodings.fromLyXName("utf8");
341 OutputParams ops(enc);
343 int const max_length = 30;
345 for (row_type row = 0; row != nrows(); ++row) {
349 label_[row]->addToToc(pit, output_active, utype, backend);
351 docstring label = nicelabel(row);
353 // this is the only equation
354 plaintext(ods, ops, max_length);
355 b.argumentItem(label + " " + ods.str());
357 // insert as sub-items
358 otexrowstream ots(ods);
359 TeXMathStream wi(ots, false, false, TeXMathStream::wsDefault, enc);
361 for (col_type c = 0; c < ncols(); ++c) {
362 wi << cell(index(row, c));
364 if (d.size() > max_length) {
365 d = d.substr(0, max_length - 1);
369 b.pushItem(pit, label+ " " + d, output_active);
370 // clear the stringstream
371 odocstringstream().swap(ods);
379 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
381 if (previewState(&cur.bv())) {
385 return InsetMathNest::editXY(cur, x, y);
389 InsetMath::mode_type InsetMathHull::currentMode() const
393 return UNDECIDED_MODE;
395 // definitely math mode ...
415 // FIXME: InsetMathGrid should be changed to let the real column alignment be
416 // given by a virtual method like displayColAlign, because the values produced
417 // by defaultColAlign can be invalidated by lfuns such as add-column. For the
418 // moment the values produced by defaultColAlign are not used, notably because
419 // alignment is not implemented in the LyXHTML output.
420 char InsetMathHull::defaultColAlign(col_type col)
422 return colAlign(type_, col);
426 char InsetMathHull::displayColAlign(idx_type idx) const
430 row_type const r = row(idx);
433 if (r == nrows() - 1)
444 return colAlign(type_, col(idx));
448 return InsetMathGrid::displayColAlign(idx);
452 int InsetMathHull::displayColSpace(col_type col) const
454 return colSpace(type_, col);
458 // FIXME: same comment as for defaultColAlign applies.
459 int InsetMathHull::defaultColSpace(col_type col)
461 return colSpace(type_, col);
465 string InsetMathHull::standardFont() const
471 return "lyxnochange";
478 ColorCode InsetMathHull::standardColor() const
483 return Color_foreground;
491 bool InsetMathHull::previewState(const BufferView *const bv) const
493 if (!editing(bv) && RenderPreview::previewMath()
494 && type_ != hullRegexp)
496 graphics::PreviewImage const * pimage =
497 preview_->getPreviewImage(bv->buffer());
498 return pimage && pimage->image();
505 const int ERROR_FRAME_WIDTH = 2;
507 bool previewTooSmall(Dimension const & dim)
509 return dim.width() <= 10 && dim.height() <= 10;
514 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
516 /* Compute \(above|below)displayskip
517 true value in LaTeX is 10pt plus 2pt minus 5pt (in normal size at 10pt)
518 But we use a fixed number of pixels and scale them with zoom.
520 int const bottom_display_margin = mi.base.bv->zoomedPixels(6);
521 int top_display_margin = bottom_display_margin;
522 // at start of paragraph, add an empty line
524 top_display_margin += theFontMetrics(mi.base.font).maxHeight() + 2;
526 int const ind = indent(*mi.base.bv);
529 if (previewState(mi.base.bv)) {
530 preview_->metrics(mi, dim);
531 if (previewTooSmall(dim)) {
532 // preview image is too small
533 dim.wid += 2 * ERROR_FRAME_WIDTH;
534 dim.asc += 2 * ERROR_FRAME_WIDTH;
536 // insert a gap in front of the formula
537 // value was hardcoded to 1 pixel
538 dim.wid += mi.base.bv->zoomedPixels(1) ;
540 dim.asc += top_display_margin;
541 dim.des += bottom_display_margin;
548 Changer dummy1 = mi.base.changeFontSet(standardFont());
549 Changer dummy2 = mi.base.font.changeStyle(display() ? DISPLAY_STYLE
552 // let the cells adjust themselves
553 InsetMathGrid::metrics(mi, dim);
556 // Check whether the numbering interferes with the equations
557 if (numberedType()) {
558 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
559 int extra_offset = 0;
561 for (row_type row = 0; row < nrows(); ++row) {
562 rowinfo(row).offset[mi.base.bv] += extra_offset;
563 docstring const nl = nicelabel(row);
567 mathed_string_dim(mi.base.font, nl, dimnl);
568 int const x = ind ? ind : (mi.base.textwidth - dim.wid) / 2;
569 // for some reason metrics does not trigger at the
570 // same point as draw, and therefore we use >= instead of >
571 if ((math_number == BufferParams::LEFT && dimnl.wid >= x)
572 || (math_number == BufferParams::RIGHT
573 && dimnl.wid >= mi.base.textwidth - x - dim.wid)) {
574 extra_offset += dimnl.height();
575 } else if (dimnl.wid > max_nlwid)
576 max_nlwid = dimnl.wid;
578 mi.extrawidth += max_nlwid;
579 dim.des += extra_offset;
584 dim.asc += top_display_margin;
585 dim.des += bottom_display_margin;
588 // reserve some space for marker.
593 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
595 BufferView const * const bv = pi.base.bv;
596 if (previewState(bv)) {
597 Dimension const dim = dimension(*pi.base.bv);
598 if (previewTooSmall(dim))
600 return graphics::PreviewLoader::backgroundColor();
606 void InsetMathHull::drawMarkers(PainterInfo & pi, int x, int y) const
608 ColorCode pen_color = mouseHovered(pi.base.bv) || editing(pi.base.bv)?
609 Color_mathframe : Color_mathcorners;
610 // If the corners have the same color as the background, do not paint them.
611 if (lcolor.getX11HexName(Color_mathbg) == lcolor.getX11HexName(pen_color))
614 Inset::drawMarkers(pi, x, y);
615 Dimension const dim = dimension(*pi.base.bv);
616 int const t = x + dim.width() - 1;
617 int const a = y - dim.ascent();
618 pi.pain.line(x, a + 3, x, a, pen_color);
619 pi.pain.line(t, a + 3, t, a, pen_color);
620 pi.pain.line(x, a, x + 3, a, pen_color);
621 pi.pain.line(t - 3, a, t, a, pen_color);
625 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
627 Dimension const dim = dimension(*pi.base.bv);
628 if (previewTooSmall(dim)) {
629 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
630 dim.wid, dim.asc + dim.des, backgroundColor(pi));
634 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
635 dim.height() - 1, pi.backgroundColor(this));
639 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
641 BufferView const * const bv = pi.base.bv;
642 Dimension const dim = dimension(*bv);
644 if (type_ == hullRegexp)
645 pi.pain.rectangle(x + 2, y - dim.ascent() + 1,
646 dim.width() - 3, dim.height() - 2, Color_regexpframe);
648 if (previewState(bv)) {
649 // Do not draw change tracking cue if taken care of by RowPainter
651 Changer dummy = !canPaintChange(*bv) ? changeVar(pi.change, Change())
653 if (previewTooSmall(dim)) {
654 // we have an extra frame
655 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
657 // one pixel gap in front
658 // value was hardcoded to 1 pixel
659 int const gap = pi.base.bv->zoomedPixels(1) ;
660 preview_->draw(pi, x + gap, y);
665 // First draw the numbers
666 if (numberedType()) {
667 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
668 for (row_type row = 0; row < nrows(); ++row) {
669 int yy = y + rowinfo(row).offset[bv];
670 docstring const nl = nicelabel(row);
672 mathed_string_dim(pi.base.font, nl, dimnl);
673 if (math_number == BufferParams::LEFT) {
674 ColorCode const col = pi.selected_left
675 ? Color_selectiontext
676 : pi.base.font.color();
677 Changer dummy0 = pi.base.font.changeColor(col);
678 if (dimnl.wid > x - pi.leftx)
679 yy += rowinfo(row).descent + dimnl.asc;
680 pi.pain.fillRectangle(pi.leftx, yy - dimnl.asc,
681 dimnl.width(), dimnl.height(),
682 pi.selected_left ? Color_selection : pi.background_color);
683 pi.draw(pi.leftx, yy, nl);
685 ColorCode const col = pi.selected_right
686 ? Color_selectiontext
687 : pi.base.font.color();
688 Changer dummy0 = pi.base.font.changeColor(col);
689 if (dimnl.wid > pi.rightx - x - dim.wid)
690 yy += rowinfo(row).descent + dimnl.asc;
691 pi.pain.fillRectangle(pi.rightx - dimnl.wid, yy - dimnl.asc,
692 dimnl.width(), dimnl.height(),
693 pi.selected_right ? Color_selection : pi.background_color);
694 pi.draw(pi.rightx - dimnl.wid, yy, nl);
699 // Then the equations
700 ColorCode color = pi.selected ? Color_selectionmath : standardColor();
701 bool const really_change_color = pi.base.font.color() == Color_none;
702 Changer dummy0 = really_change_color ? pi.base.font.changeColor(color)
704 Changer dummy1 = pi.base.changeFontSet(standardFont());
705 Changer dummy2 = pi.base.font.changeStyle(display() ? DISPLAY_STYLE
707 InsetMathGrid::draw(pi, x + 1, y);
708 drawMarkers(pi, x, y);
710 // drawing change line
711 if (canPaintChange(*bv)) {
713 int const display_margin = display() ? pi.base.inPixels(Length(12, Length::PT)) : 0;
714 pi.change.paintCue(pi, x + 1, y + 1 - dim.asc + display_margin,
715 x + dim.wid, y + dim.des - display_margin);
720 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
723 InsetMathGrid::metricsT(mi, dim);
726 otexrowstream ots(os);
727 TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault);
729 dim.wid = os.str().size();
736 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
739 InsetMathGrid::drawT(pain, x, y);
742 otexrowstream ots(os);
743 TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault);
745 pain.draw(x, y, os.str().c_str());
750 static docstring latexString(InsetMathHull const & inset)
753 // This has to be static, because a preview snippet or a math
754 // macro containing math in text mode (such as $\text{$\phi$}$ or
755 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
756 // first time as a whole, and the second time only the inner math.
757 // In this last case inset.buffer() would be invalid.
758 static Encoding const * encoding = nullptr;
759 if (inset.isBufferValid())
760 encoding = &(inset.buffer().params().encoding());
761 otexrowstream ots(ls);
762 TeXMathStream wi(ots, false, true, TeXMathStream::wsPreview, encoding);
768 void InsetMathHull::initUnicodeMath() const
770 // Trigger classification of the unicode symbols in this inset
771 docstring const dummy = latexString(*this);
775 void InsetMathHull::addPreview(DocIterator const & inset_pos,
776 graphics::PreviewLoader & /*ploader*/) const
778 if (RenderPreview::previewMath()) {
779 preparePreview(inset_pos);
784 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
785 MacroNameSet & macros, MacroNameSet & defs) const
787 MacroNameSet::iterator const end = macros.end();
789 for (size_t i = 0; i < md.size(); ++i) {
790 InsetMathMacro const * mi = md[i].nucleus()->asMacro();
791 InsetMathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
792 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
793 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
794 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
795 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
797 // Look for macros in the arguments of this macro.
798 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
799 usedMacros(mi->cell(idx), pos, macros, defs);
800 // Make sure this is a macro defined in the document
801 // (as we also spot the macros in the symbols file)
802 // or that we have not already accounted for it.
803 docstring const name = mi->name();
804 if (macros.find(name) == end)
807 // Look for macros in the definition of this macro.
808 MathData ar(pos.buffer());
809 MacroData const * data =
810 pos.buffer()->getMacro(name, pos, true);
812 odocstringstream macro_def;
813 data->write(macro_def, true);
815 defs.insert(macro_def.str());
816 asArray(data->definition(), ar);
818 usedMacros(ar, pos, macros, defs);
820 MathData ar(pos.buffer());
821 asArray(mt->definition(), ar);
822 usedMacros(ar, pos, macros, defs);
824 if (!si->nuc().empty())
825 usedMacros(si->nuc(), pos, macros, defs);
827 usedMacros(si->down(), pos, macros, defs);
829 usedMacros(si->up(), pos, macros, defs);
830 } else if (fi || gi) {
831 idx_type nidx = fi ? fi->nargs() : gi->nargs();
832 for (idx_type idx = 0; idx < nidx; ++idx)
833 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
836 usedMacros(ni->cell(0), pos, macros, defs);
842 void InsetMathHull::preparePreview(DocIterator const & pos,
843 bool forexport) const
845 // there is no need to do all the macro stuff if we're not
846 // actually going to generate the preview.
847 if (!RenderPreview::previewMath() && !forexport)
850 Buffer const * buffer = pos.buffer();
852 // collect macros at this position
854 buffer->listMacroNames(macros);
856 // collect definitions only for the macros used in this inset
858 for (idx_type idx = 0; idx < nargs(); ++idx)
859 usedMacros(cell(idx), pos, macros, defs);
861 docstring macro_preamble;
862 for (auto const & defvar : defs)
863 macro_preamble.append(defvar);
865 // set the font series and size for this snippet
866 DocIterator dit = pos.getInnerText();
867 Paragraph const & par = dit.paragraph();
868 Font font = par.getFontSettings(buffer->params(), dit.pos());
869 font.fontInfo().realize(par.layout().font);
870 string const lsize = font.latexSize();
873 if (font.fontInfo().series() == BOLD_SERIES) {
874 setfont += from_ascii("\\textbf{");
877 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
878 setfont += from_ascii("\\" + lsize + '\n');
880 docstring const snippet = macro_preamble + setfont + latexString(*this) + endfont;
881 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
882 preview_->addPreview(snippet, *buffer, forexport);
886 void InsetMathHull::reloadPreview(DocIterator const & pos) const
889 preview_->startLoading(*pos.buffer());
893 void InsetMathHull::loadPreview(DocIterator const & pos) const
895 bool const forexport = true;
896 preparePreview(pos, forexport);
897 preview_->startLoading(*pos.buffer(), forexport);
901 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
903 if (RenderPreview::previewMath()) {
905 cur.screenUpdateFlags(Update::SinglePar);
911 docstring InsetMathHull::label(row_type row) const
913 LASSERT(row < nrows(), return docstring());
914 if (InsetLabel * il = label_[row])
915 return il->screenLabel();
920 void InsetMathHull::label(row_type row, docstring const & label)
922 //lyxerr << "setting label '" << label << "' for row " << row << endl;
926 label_[row] = dummy_pointer;
929 label_[row]->updateLabelAndRefs(label);
931 label_[row]->setParam("name", label);
935 InsetCommandParams p(LABEL_CODE);
937 label_[row] = new InsetLabel(buffer_, p);
939 label_[row]->setBuffer(buffer());
943 void InsetMathHull::numbered(row_type row, Numbered num)
945 numbered_[row] = num;
949 bool InsetMathHull::numbered(row_type row) const
951 return numbered_[row] == NUMBER;
955 bool InsetMathHull::ams() const
975 for (auto const & row : numbered_)
982 bool InsetMathHull::outerDisplay() const
1005 int InsetMathHull::rowFlags() const
1022 if (buffer().params().is_math_indent)
1023 return Display | AlignLeft;
1032 int InsetMathHull::indent(BufferView const & bv) const
1034 // FIXME: set this in the textclass. This value is what the article class uses.
1035 static Length default_indent(2.5, Length::EM);
1036 if (display() && buffer().params().is_math_indent) {
1037 Length const & len = buffer().params().getMathIndent();
1039 return bv.inPixels(default_indent);
1041 return bv.inPixels(len);
1043 return Inset::indent(bv);
1047 bool InsetMathHull::numberedType() const
1066 for (row_type row = 0; row < nrows(); ++row)
1073 void InsetMathHull::validate(LaTeXFeatures & features) const
1075 if (features.runparams().isLaTeX()) {
1077 features.require("amsmath");
1079 if (type_ == hullRegexp) {
1080 features.require("color");
1081 docstring frcol = from_utf8(lcolor.getLaTeXName(Color_regexpframe));
1082 docstring bgcol = from_ascii("white");
1083 features.addPreambleSnippet(
1084 "\\newcommand{\\regexp}[1]{\\fcolorbox{"
1086 + bgcol + "}{\\ensuremath{\\mathtt{#1}}}}");
1087 features.addPreambleSnippet(
1088 from_ascii("\\newcommand{\\endregexp}{}"));
1089 } else if (outerDisplay() && features.inDeletedInset()) {
1090 features.require("tikz");
1091 features.require("ct-tikz-object-sout");
1094 // Validation is necessary only if not using AMS math.
1095 // To be safe, we will always run mathedvalidate.
1096 //if (features.amsstyle)
1099 //features.binom = true;
1100 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
1101 // it would be better to do this elsewhere, but we can't validate in
1102 // InsetMathMatrix and we have no way, outside MathExtern, to know if
1103 // we even have any matrices.
1104 features.addCSSSnippet(
1105 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
1106 "table.matrix td{padding: 0.25px;}\n"
1107 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
1108 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
1110 InsetMathGrid::validate(features);
1114 CtObject InsetMathHull::getCtObject(OutputParams const & runparams) const
1116 CtObject res = CtObject::Normal;
1132 case hullMultline: {
1133 if (runparams.inulemcmd
1134 && (!runparams.local_font || runparams.local_font->fontInfo().strikeout() != FONT_ON))
1135 res = CtObject::UDisplayObject;
1137 res = CtObject::DisplayObject;
1145 void InsetMathHull::header_write(TeXMathStream & os) const
1147 bool n = numberedType();
1158 if (cell(0).empty())
1163 writeMathdisplayPreamble(os);
1167 os << "\\begin{equation" << star(n) << "}\n";
1177 writeMathdisplayPreamble(os);
1180 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1187 os << "\\begin{" << hullName(type_) << star(n) << '}'
1188 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1194 os << "\\begin{" << hullName(type_) << '}'
1195 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1205 os << "\\begin{unknown" << star(n) << "}\n";
1211 void InsetMathHull::footer_write(TeXMathStream & os) const
1213 bool n = numberedType();
1230 os << "\\end{equation" << star(n) << "}\n";
1233 writeMathdisplayPostamble(os);
1243 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1244 writeMathdisplayPostamble(os);
1251 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1257 os << "\\end{" << hullName(type_) << "}\n";
1261 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1262 os << "\\endregexp{}}";
1268 os << "\\end{unknown" << star(n) << "}\n";
1274 bool InsetMathHull::allowsTabularFeatures() const
1297 bool InsetMathHull::rowChangeOK() const
1300 type_ == hullEqnArray || type_ == hullAlign ||
1301 type_ == hullFlAlign || type_ == hullAlignAt ||
1302 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1303 type_ == hullGather || type_ == hullMultline;
1307 bool InsetMathHull::colChangeOK() const
1310 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1311 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1315 void InsetMathHull::addRow(row_type row)
1320 bool numbered = numberedType();
1321 // Move the number and raw pointer, do not call label() (bug 7511)
1322 InsetLabel * label = dummy_pointer;
1323 docstring number = empty_docstring();
1324 if (type_ == hullMultline) {
1325 if (row + 1 == nrows()) {
1326 numbered_[row] = NONUMBER;
1327 swap(label, label_[row]);
1328 swap(number, numbers_[row]);
1333 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1334 numbers_.insert(numbers_.begin() + row + 1, number);
1335 label_.insert(label_.begin() + row + 1, label);
1336 InsetMathGrid::addRow(row);
1340 void InsetMathHull::swapRow(row_type row)
1344 if (row + 1 == nrows())
1346 swap(numbered_[row], numbered_[row + 1]);
1347 swap(numbers_[row], numbers_[row + 1]);
1348 swap(label_[row], label_[row + 1]);
1349 InsetMathGrid::swapRow(row);
1353 void InsetMathHull::delRow(row_type row)
1355 if (nrows() <= 1 || !rowChangeOK())
1357 if (row + 1 == nrows() && type_ == hullMultline) {
1358 swap(numbered_[row - 1], numbered_[row]);
1359 swap(numbers_[row - 1], numbers_[row]);
1360 swap(label_[row - 1], label_[row]);
1361 InsetMathGrid::delRow(row);
1364 InsetMathGrid::delRow(row);
1365 // The last dummy row has no number info nor a label.
1366 // Test nrows() + 1 because we have already erased the row.
1367 if (row == nrows() + 1)
1369 numbered_.erase(numbered_.begin() + row);
1370 numbers_.erase(numbers_.begin() + row);
1372 label_.erase(label_.begin() + row);
1376 void InsetMathHull::addCol(col_type col)
1380 InsetMathGrid::addCol(col);
1384 void InsetMathHull::delCol(col_type col)
1386 if (ncols() <= 1 || !colChangeOK())
1388 InsetMathGrid::delCol(col);
1392 docstring InsetMathHull::nicelabel(row_type row) const
1394 if (!numbered(row)) {
1397 return '[' + label_[row]->screenLabel() + ']';
1399 docstring const & val = numbers_[row];
1401 return '(' + val + ')';
1402 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1406 void InsetMathHull::glueall(HullType type)
1408 MathData ar(buffer_);
1409 for (idx_type i = 0; i < nargs(); ++i)
1411 InsetLabel * label = nullptr;
1412 if (type == hullEquation) {
1413 // preserve first non-empty label
1414 for (row_type row = 0; row < nrows(); ++row) {
1416 label = label_[row];
1422 *this = InsetMathHull(buffer_, hullSimple);
1429 void InsetMathHull::splitTo2Cols()
1431 LASSERT(ncols() == 1, return);
1432 InsetMathGrid::addCol(1);
1433 for (row_type row = 0; row < nrows(); ++row) {
1434 idx_type const i = 2 * row;
1435 pos_type pos = firstRelOp(cell(i));
1436 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1437 cell(i).erase(pos, cell(i).size());
1442 void InsetMathHull::splitTo3Cols()
1444 LASSERT(ncols() < 3, return);
1447 InsetMathGrid::addCol(2);
1448 for (row_type row = 0; row < nrows(); ++row) {
1449 idx_type const i = 3 * row + 1;
1450 if (!cell(i).empty()) {
1451 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1452 cell(i).erase(1, cell(i).size());
1458 void InsetMathHull::changeCols(col_type cols)
1460 if (ncols() == cols)
1462 else if (ncols() < cols) {
1468 while (ncols() < cols)
1469 InsetMathGrid::addCol(ncols());
1475 for (row_type row = 0; row < nrows(); ++row) {
1476 idx_type const i = row * ncols();
1477 for (col_type col = cols; col < ncols(); ++col) {
1478 cell(i + cols - 1).append(cell(i + col));
1482 while (ncols() > cols) {
1483 InsetMathGrid::delCol(ncols() - 1);
1488 HullType InsetMathHull::getType() const
1494 void InsetMathHull::setType(HullType type)
1501 bool InsetMathHull::isMutable(HullType type)
1525 void InsetMathHull::mutate(HullType newtype)
1527 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1529 if (newtype == type_)
1532 // This guards the algorithm below it, which is designed with certain types
1534 if (!isMutable(newtype) || !isMutable(type_)) {
1535 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1536 << "' to '" << to_utf8(hullName(newtype))
1537 << "' not implemented" << endl;
1541 // we try to move along the chain
1542 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1544 // +-------------------------------------+
1545 // we use eqnarray as intermediate type for mutations that are not
1546 // directly supported because it handles labels and numbering for
1551 setType(hullSimple);
1557 if (newtype == hullNone) {
1561 setType(hullEquation);
1562 numbered(0, label_[0] != nullptr);
1571 setType(hullSimple);
1576 // split it "nicely" on the first relop
1578 setType(hullEqnArray);
1586 // split it "nicely"
1621 setType(hullEqnArray);
1630 for (row_type row = 0; row < nrows(); ++row)
1631 numbered(row, false);
1641 for (row_type row = 0; row < nrows(); ++row)
1642 numbered(row, false);
1649 setType(hullEqnArray);
1679 for (row_type row = 0; row < nrows(); ++row)
1680 numbered(row, false);
1684 // first we mutate to EqnArray
1686 setType(hullEqnArray);
1693 // we passed the guard so we should not be here
1694 LYXERR0("Mutation not implemented, but should have been.");
1695 LASSERT(false, return);
1701 void InsetMathHull::eol(TeXMathStream & os, row_type row, bool fragile, bool latex,
1702 bool last_eoln) const
1704 if (numberedType()) {
1705 bool const for_preview =
1706 (os.output() == TeXMathStream::wsPreview);
1708 // Use utf8 strings for previewed labels when possible
1709 bool use_utf8 = for_preview &&
1710 (buffer().params().useNonTeXFonts ||
1711 buffer().params().encoding().package() == Encoding::japanese);
1712 docstring const name = (latex && !use_utf8)
1713 ? escape(label_[row]->getParam("name"))
1714 : label_[row]->getParam("name");
1715 os << "\\label{" + name + '}';
1717 if (type_ != hullMultline) {
1718 if (numbered_[row] == NONUMBER)
1719 os << "\\nonumber ";
1720 else if (numbered_[row] == NOTAG)
1723 if (for_preview && !numbers_[row].empty()) {
1724 os << "\\global\\def\\theequation{" << numbers_[row] << "}\n";
1728 // Never add \\ on the last empty line of eqnarray and friends
1730 InsetMathGrid::eol(os, row, fragile, latex, last_eoln);
1733 void InsetMathHull::write(TeXMathStream & os) const
1735 ModeSpecifier specifier(os, MATH_MODE);
1737 InsetMathGrid::write(os);
1742 void InsetMathHull::normalize(NormalStream & os) const
1744 os << "[formula " << hullName(type_) << ' ';
1745 InsetMathGrid::normalize(os);
1750 void InsetMathHull::infoize(odocstream & os) const
1752 os << bformat(_("Type: %1$s"), hullName(type_));
1756 void InsetMathHull::check() const
1758 LATTEST(numbered_.size() == nrows());
1759 LATTEST(numbers_.size() == nrows());
1760 LATTEST(label_.size() == nrows());
1764 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1766 //FIXME: sort out whether we want std::string or docstring for those
1767 string const lang = func.getArg(0);
1768 docstring extra = from_utf8(func.getArg(1));
1770 extra = from_ascii("noextra");
1772 // replace selection with result of computation
1773 if (reduceSelectionToOneCell(cur)) {
1774 MathData ar(buffer_);
1775 asArray(grabAndEraseSelection(cur), ar);
1776 lyxerr << "use selection: " << ar << endl;
1777 cur.insert(pipeThroughExtern(lang, extra, ar));
1781 // only inline, display or eqnarray math is allowed
1782 switch (getType()) {
1788 frontend::Alert::warning(_("Bad math environment"),
1789 _("Computation cannot be performed for AMS "
1790 "math environments.\nChange the math "
1791 "formula type and try again."));
1795 MathData eq(buffer_);
1796 eq.push_back(MathAtom(new InsetMathChar(buffer_, '=')));
1798 // go to first item in line
1799 cur.idx() -= cur.idx() % ncols();
1802 if (getType() == hullSimple) {
1803 size_type pos = cur.cell().find_last(eq);
1804 MathData ar(buffer_);
1805 if (pos == cur.cell().size()) {
1807 lyxerr << "use whole cell: " << ar << endl;
1809 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1810 lyxerr << "use partial cell form pos: " << pos << endl;
1812 cur.cell().append(eq);
1813 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1814 cur.pos() = cur.lastpos();
1818 if (getType() == hullEquation) {
1819 lyxerr << "use equation inset" << endl;
1820 mutate(hullEqnArray);
1821 MathData & ar = cur.cell();
1822 lyxerr << "use cell: " << ar << endl;
1826 cur.cell() = pipeThroughExtern(lang, extra, ar);
1827 // move to end of line
1828 cur.pos() = cur.lastpos();
1833 lyxerr << "use eqnarray" << endl;
1834 cur.idx() += 2 - cur.idx() % ncols();
1836 MathData ar = cur.cell();
1837 lyxerr << "use cell: " << ar << endl;
1838 // FIXME: temporarily disabled
1844 cur.cell() = pipeThroughExtern(lang, extra, ar);
1845 cur.pos() = cur.lastpos();
1850 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1852 //lyxerr << "action: " << cmd.action() << endl;
1853 switch (cmd.action()) {
1855 case LFUN_FINISHED_BACKWARD:
1856 case LFUN_FINISHED_FORWARD:
1857 case LFUN_FINISHED_RIGHT:
1858 case LFUN_FINISHED_LEFT:
1859 //lyxerr << "action: " << cmd.action() << endl;
1860 InsetMathGrid::doDispatch(cur, cmd);
1863 case LFUN_PARAGRAPH_BREAK:
1864 // just swallow this
1867 case LFUN_NEWLINE_INSERT:
1868 // some magic for the common case
1869 if (type_ == hullSimple || type_ == hullEquation) {
1870 cur.recordUndoInset();
1872 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1873 mutate(align ? hullAlign : hullEqnArray);
1874 // mutate() may change labels and such.
1875 cur.forceBufferUpdate();
1876 cur.idx() = nrows() * ncols() - 1;
1877 cur.pos() = cur.lastpos();
1879 InsetMathGrid::doDispatch(cur, cmd);
1882 case LFUN_MATH_NUMBER_TOGGLE: {
1883 //lyxerr << "toggling all numbers" << endl;
1884 cur.recordUndoInset();
1885 bool old = numberedType();
1886 if (type_ == hullMultline) {
1887 row_type row = nrows() - 1;
1888 numbered(row, !old);
1889 if (old && label_[row]) {
1894 for (row_type row = 0; row < nrows(); ++row) {
1895 numbered(row, !old);
1896 if (old && label_[row]) {
1903 cur.message(old ? _("No number") : _("Number"));
1904 cur.forceBufferUpdate();
1908 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1909 cur.recordUndoInset();
1910 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1911 bool old = numbered(r);
1912 cur.message(old ? _("No number") : _("Number"));
1914 if (old && label_[r]) {
1918 cur.forceBufferUpdate();
1922 case LFUN_LABEL_INSERT: {
1923 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1924 docstring old_label = label(r);
1925 docstring const default_label = from_ascii("eq:");
1926 if (old_label.empty())
1927 old_label = default_label;
1929 InsetCommandParams p(LABEL_CODE);
1930 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1931 string const data = InsetCommand::params2string(p);
1933 if (cmd.argument().empty())
1934 cur.bv().showDialog("label", data);
1936 FuncRequest fr(LFUN_INSET_INSERT, data);
1942 case LFUN_LABEL_COPY_AS_REFERENCE: {
1944 if (cmd.argument().empty() && &cur.inset() == this)
1945 // if there is no argument and we're inside math, we retrieve
1946 // the row number from the cursor position.
1947 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1949 // if there is an argument, find the corresponding label, else
1950 // check whether there is at least one label.
1951 for (row = 0; row != nrows(); ++row)
1953 && (cmd.argument().empty() || label(row) == cmd.argument()))
1960 InsetCommandParams p(REF_CODE, "ref");
1961 p["reference"] = label(row);
1962 cap::clearSelection();
1963 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1967 case LFUN_WORD_DELETE_FORWARD:
1968 case LFUN_CHAR_DELETE_FORWARD:
1969 if (col(cur.idx()) + 1 == ncols()
1970 && cur.pos() == cur.lastpos()
1971 && !cur.selection()) {
1972 if (!label(row(cur.idx())).empty()) {
1973 cur.recordUndoInset();
1974 label(row(cur.idx()), docstring());
1975 } else if (numbered(row(cur.idx()))) {
1976 cur.recordUndoInset();
1977 numbered(row(cur.idx()), false);
1978 cur.forceBufferUpdate();
1980 InsetMathGrid::doDispatch(cur, cmd);
1984 InsetMathGrid::doDispatch(cur, cmd);
1989 case LFUN_INSET_INSERT: {
1990 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1991 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1992 string const name = cmd.getArg(0);
1993 if (name == "label") {
1994 InsetCommandParams p(LABEL_CODE);
1995 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1996 docstring str = p["name"];
1997 cur.recordUndoInset();
1998 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2002 docstring old = label(r);
2005 // The label will take care of the reference update.
2009 // Newly created inset so initialize it.
2010 label_[r]->initView();
2013 cur.forceBufferUpdate();
2016 InsetMathGrid::doDispatch(cur, cmd);
2020 case LFUN_MATH_EXTERN:
2021 cur.recordUndoInset();
2025 case LFUN_MATH_MUTATE: {
2026 cur.recordUndoInset();
2027 row_type row = cur.row();
2028 col_type col = cur.col();
2029 mutate(hullType(cmd.argument()));
2030 cur.idx() = row * ncols() + col;
2031 if (cur.idx() > cur.lastidx()) {
2032 cur.idx() = cur.lastidx();
2033 cur.pos() = cur.lastpos();
2035 if (cur.pos() > cur.lastpos())
2036 cur.pos() = cur.lastpos();
2038 cur.forceBufferUpdate();
2039 // FIXME: find some more clever handling of the selection,
2040 // i.e. preserve it.
2041 cur.clearSelection();
2042 //cur.dispatched(FINISHED);
2046 case LFUN_MATH_DISPLAY: {
2047 cur.recordUndoInset();
2048 mutate(type_ == hullSimple ? hullEquation : hullSimple);
2049 // if the cursor is in a cell that got merged, move it to
2050 // start of the hull inset.
2051 if (cur.idx() > 0) {
2055 if (cur.pos() > cur.lastpos())
2056 cur.pos() = cur.lastpos();
2061 case LFUN_TABULAR_FEATURE:
2062 if (!allowsTabularFeatures())
2065 InsetMathGrid::doDispatch(cur, cmd);
2069 InsetMathGrid::doDispatch(cur, cmd);
2077 bool allowDisplayMath(Cursor const & cur)
2079 LATTEST(cur.depth() > 1);
2080 Cursor tmpcur = cur;
2083 FuncRequest cmd(LFUN_MATH_DISPLAY);
2084 return tmpcur.getStatus(cmd, status) && status.enabled();
2090 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
2091 FuncStatus & status) const
2093 switch (cmd.action()) {
2094 case LFUN_FINISHED_BACKWARD:
2095 case LFUN_FINISHED_FORWARD:
2096 case LFUN_FINISHED_RIGHT:
2097 case LFUN_FINISHED_LEFT:
2100 case LFUN_NEWLINE_INSERT:
2101 case LFUN_MATH_EXTERN:
2103 status.setEnabled(true);
2106 // we never allow this in math, and we want to bind enter
2107 // to another actions in command-alternatives
2108 case LFUN_PARAGRAPH_BREAK:
2109 status.setEnabled(false);
2111 case LFUN_MATH_MUTATE: {
2112 HullType const ht = hullType(cmd.argument());
2113 status.setOnOff(type_ == ht);
2114 status.setEnabled(isMutable(ht) && isMutable(type_));
2116 if (ht != hullSimple && status.enabled())
2117 status.setEnabled(allowDisplayMath(cur));
2120 case LFUN_MATH_DISPLAY: {
2121 status.setEnabled(display() || allowDisplayMath(cur));
2122 status.setOnOff(display());
2126 case LFUN_MATH_NUMBER_TOGGLE:
2127 // FIXME: what is the right test, this or the one of
2129 status.setEnabled(display());
2130 status.setOnOff(numberedType());
2133 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
2134 // FIXME: what is the right test, this or the one of
2136 bool const enable = (type_ == hullMultline)
2137 ? (nrows() - 1 == cur.row())
2139 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2140 status.setEnabled(enable);
2141 status.setOnOff(enable && numbered(r));
2145 case LFUN_LABEL_INSERT:
2146 status.setEnabled(type_ != hullSimple);
2149 case LFUN_LABEL_COPY_AS_REFERENCE: {
2150 bool enabled = false;
2151 if (cmd.argument().empty() && &cur.inset() == this) {
2152 // if there is no argument and we're inside math, we retrieve
2153 // the row number from the cursor position.
2154 row_type row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2155 enabled = numberedType() && label_[row];
2157 // if there is an argument, find the corresponding label, else
2158 // check whether there is at least one label.
2159 for (row_type row = 0; row != nrows(); ++row) {
2161 (cmd.argument().empty() || label(row) == cmd.argument())) {
2167 status.setEnabled(enabled);
2171 case LFUN_INSET_INSERT:
2172 if (cmd.getArg(0) == "label") {
2173 status.setEnabled(type_ != hullSimple);
2176 return InsetMathGrid::getStatus(cur, cmd, status);
2178 case LFUN_TABULAR_FEATURE: {
2179 if (!allowsTabularFeatures())
2181 string s = cmd.getArg(0);
2183 && (s == "append-row"
2184 || s == "delete-row"
2185 || s == "copy-row")) {
2186 status.message(bformat(
2187 from_utf8(N_("Can't change number of rows in '%1$s'")),
2189 status.setEnabled(false);
2193 && (s == "append-column"
2194 || s == "delete-column"
2195 || s == "copy-column")) {
2196 status.message(bformat(
2197 from_utf8(N_("Can't change number of columns in '%1$s'")),
2199 status.setEnabled(false);
2202 if (s == "add-vline-left" || s == "add-vline-right") {
2203 status.message(bformat(
2204 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2206 status.setEnabled(false);
2209 if (s == "valign-top" || s == "valign-middle"
2210 || s == "valign-bottom" || s == "align-left"
2211 || s == "align-center" || s == "align-right") {
2212 status.setEnabled(false);
2215 return InsetMathGrid::getStatus(cur, cmd, status);
2219 return InsetMathGrid::getStatus(cur, cmd, status);
2224 int InsetMathHull::leftMargin() const
2226 return (getType() == hullSimple) ? 0 : InsetMathGrid::leftMargin();
2230 int InsetMathHull::rightMargin() const
2232 return (getType() == hullSimple) ? 0 : InsetMathGrid::rightMargin();
2236 int InsetMathHull::border() const
2238 return (getType() == hullSimple) ? 0 : InsetMathGrid::border();
2242 /////////////////////////////////////////////////////////////////////
2246 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2247 docstring const & font)
2249 // this whole function is a hack and won't work for incremental font
2252 if (cur.inset().asInsetMath()->name() == font)
2253 cur.handleFont(to_utf8(font));
2255 cur.handleNest(createInsetMath(font, cur.buffer()));
2261 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2266 font.fromString(to_utf8(arg), b);
2267 if (font.fontInfo().color() != Color_inherit) {
2268 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2274 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2276 bool const has_preview = previewState(&cur.bv());
2278 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
2279 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
2280 enter_front ? idxFirst(cur) : idxLast(cur);
2282 // The inset formula dimension is in general different from the
2283 // one of the instant preview image, so we have to indicate to the
2284 // BufferView that a metrics update is needed.
2285 cur.screenUpdateFlags(Update::SinglePar);
2290 /////////////////////////////////////////////////////////////////////
2293 void InsetMathHull::write(ostream & os) const
2295 odocstringstream oss;
2296 otexrowstream ots(oss);
2297 TeXMathStream wi(ots, false, false, TeXMathStream::wsDefault);
2300 os << to_utf8(oss.str());
2304 void InsetMathHull::read(Lexer & lex)
2307 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2308 operator=(*at->asHullInset());
2312 bool InsetMathHull::readQuiet(Lexer & lex)
2315 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2317 operator=(*at->asHullInset());
2322 int InsetMathHull::plaintext(odocstringstream & os,
2323 OutputParams const & op, size_t max_length) const
2325 // Try enabling this now that there is a flag as requested at #2275.
2326 if (buffer().isExporting() && display()) {
2330 TextPainter tpain(dim.width(), dim.height());
2331 drawT(tpain, 0, dim.ascent());
2333 // reset metrics cache to "real" values
2335 return tpain.textheight();
2338 odocstringstream oss;
2339 otexrowstream ots(oss);
2340 Encoding const * const enc = encodings.fromLyXName("utf8");
2342 TeXMathStream::OutputType ot;
2343 if (op.find_effective())
2344 ot = TeXMathStream::wsSearchAdv;
2346 ot = TeXMathStream::wsDefault;
2348 if (type_ == hullRegexp) {
2349 TeXMathStream wi(ots, false, true, ot, enc);
2353 TeXMathStream wi(ots, false, true, ot, enc);
2354 for (row_type r = 0; r < nrows(); ++r) {
2355 for (col_type c = 0; c < ncols(); ++c)
2356 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2357 // if it's for the TOC, we write just the first line
2358 // and do not include the newline.
2359 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2361 if (r < nrows() - 1)
2365 docstring const str = oss.str();
2371 void InsetMathHull::docbook(XMLStream & xs, OutputParams const & runparams) const {
2372 // Choose the tag around the MathML equation.
2375 if (getType() == hullSimple)
2376 name = from_ascii("inlineequation");
2378 doCR = true; // This is a block equation, always have <informalequation> on its own line.
2379 name = from_ascii("informalequation");
2382 // DocBook also has <equation>, but it comes with a title.
2383 // TODO: recognise \tag from amsmath? This would allow having <equation> with a proper title.
2387 bool mathmlNamespaceInline = buffer().params().docbook_mathml_prefix == BufferParams::NoPrefix;
2388 if (mathmlNamespaceInline)
2389 attr += "xmlns=\"http://www.w3.org/1998/Math/MathML\"";
2391 for (row_type i = 0; i < nrows(); ++i) {
2392 if (!label(i).empty()) {
2396 attr += "xml:id=\"" + xml::cleanID(label(i)) + "\"";
2402 if (!xs.isLastTagCR())
2405 xs << xml::StartTag(name, attr);
2408 // With DocBook 5, MathML must be within its own namespace (defined in Buffer.cpp::writeDocBookSource, except when
2409 // it should be inlined).
2410 // Output everything in a separate stream so that this does not interfere with the standard flow of DocBook tags.
2411 std::string mathmlNamespacePrefix;
2412 if (!mathmlNamespaceInline) {
2413 if (buffer().params().docbook_mathml_prefix == BufferParams::MPrefix)
2414 mathmlNamespacePrefix = "m";
2415 else if (buffer().params().docbook_mathml_prefix == BufferParams::MMLPrefix)
2416 mathmlNamespacePrefix = "mml";
2419 odocstringstream osmath;
2420 MathMLStream ms(osmath, mathmlNamespacePrefix);
2422 // Output the MathML subtree.
2423 // TeX transcription. Avoid MTag/ETag so that there are no extraneous spaces.
2424 ms << "<" << from_ascii("alt") << " role='tex'" << ">";
2425 // Workaround for db2latex: db2latex always includes equations with
2426 // \ensuremath{} or \begin{display}\end{display}
2427 // so we strip LyX' math environment
2428 odocstringstream ls;
2430 TeXMathStream wi(ols, false, false, TeXMathStream::wsDefault, runparams.encoding);
2431 InsetMathGrid::write(wi);
2432 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2433 ms << "</" << from_ascii("alt") << ">";
2435 // Actual transformation of the formula into MathML. This translation may fail (for example, due to custom macros).
2436 // The new output stream is required to deal with the errors: first write completely the formula into this
2437 // temporary stream; then, if it is possible without error, then copy it back to the "real" stream. Otherwise,
2438 // some incomplete tags might be put into the real stream.
2440 // First, generate the MathML expression. If there is an error in the generation, this block is not fully
2441 // executed, and the formula is not output to the DocBook stream.
2442 odocstringstream ostmp;
2443 MathMLStream mstmp(ostmp, ms.xmlns());
2446 // Choose the display style for the formula, to be output as an attribute near the formula root.
2447 std::string mathmlAttr;
2448 if (getType() == hullSimple)
2449 mathmlAttr = "display=\"inline\"";
2451 mathmlAttr = "display=\"block\"";
2453 // Then, output the formula.
2454 ms << MTag("math", mathmlAttr);
2456 osmath << ostmp.str(); // osmath is not a XMLStream, so no need for XMLStream::ESCAPE_NONE.
2458 } catch (MathExportException const &) {
2460 osmath << "<mathphrase>MathML export failed. Please report this as a bug to the LyX developers: "
2461 "https://www.lyx.org/trac.</mathphrase>";
2464 // Output the complete formula to the DocBook stream.
2465 xs << XMLStream::ESCAPE_NONE << osmath.str();
2467 xs << xml::EndTag(name);
2473 bool InsetMathHull::haveNumbers() const
2475 bool havenumbers = false;
2476 // inline formulas are never numbered (bug 7351 part 3)
2477 if (getType() == hullSimple)
2479 for (size_t i = 0; i != numbered_.size(); ++i) {
2490 // We need to do something about alignment here.
2492 // This duplicates code from InsetMathGrid, but
2493 // we need access here to number information,
2494 // and we simply do not have that in InsetMathGrid.
2495 void InsetMathHull::htmlize(HtmlStream & os) const
2497 bool const havenumbers = haveNumbers();
2498 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2501 os << cell(index(0, 0));
2505 os << MTag("table", "class='mathtable'");
2506 for (row_type row = 0; row < nrows(); ++row) {
2508 for (col_type col = 0; col < ncols(); ++col) {
2510 os << cell(index(row, col));
2515 docstring const & num = numbers_[row];
2517 os << '(' << num << ')';
2522 os << ETag("table");
2526 // this duplicates code from InsetMathGrid, but
2527 // we need access here to number information,
2528 // and we simply do not have that in InsetMathGrid.
2529 void InsetMathHull::mathmlize(MathMLStream & ms) const
2531 bool const havetable = haveNumbers() || nrows() > 1 || ncols() > 1;
2533 // Simplest case: single row, single column, no numbering.
2535 ms << cell(index(0, 0));
2539 // More complex case: wrap elements in a table.
2540 if (getType() == hullSimple) {
2541 ms << MTag("mtable");
2542 } else if (getType() >= hullAlign && getType() <= hullXXAlignAt) {
2543 // hullAlign, hullAlignAt, hullXAlignAt, hullXXAlignAt
2545 for (col_type col = 0; col < ncols(); ++col) {
2546 alignment += (col % 2) ? "left " : "right ";
2548 ms << MTag("mtable", "displaystyle='true' columnalign='" + alignment + "'");
2550 ms << MTag("mtable", "displaystyle='true'");
2553 for (row_type row = 0; row < nrows(); ++row) {
2554 // No Wed browser supports mlabeledtr in 2023, even though it has been introduced in
2555 // MathML 2 (2003). Moreover, it is not supported in MathML 4 Core.
2558 for (col_type col = 0; col < ncols(); ++col) {
2560 << cell(index(row, col))
2565 if (haveNumbers()) {
2567 docstring const & num = numbers_[row];
2569 ms << MTagInline("mtext") << '(' << num << ')' << ETagInline("mtext");
2576 ms << ETag("mtable");
2580 docstring InsetMathHull::mathAsLatex() const
2582 bool const havenumbers = haveNumbers();
2583 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2586 odocstringstream ls;
2587 otexrowstream ots(ls);
2588 TeXMathStream os(ots, false, true, TeXMathStream::wsPreview);
2589 ModeSpecifier specifier(os, MATH_MODE);
2590 MathEnsurer ensurer(os, false);
2592 os << cell(index(0, 0));
2596 odocstringstream ods;
2599 xs << xml::StartTag("table", "class='mathtable'");
2600 for (row_type row = 0; row < nrows(); ++row) {
2601 xs << xml::StartTag("tr");
2602 for (col_type col = 0; col < ncols(); ++col) {
2603 xs << xml::StartTag("td", "class='math'");
2605 odocstringstream ls;
2606 otexrowstream ots(ls);
2607 TeXMathStream os(ots, false, true, TeXMathStream::wsPreview);
2608 ModeSpecifier specifier(os, MATH_MODE);
2609 MathEnsurer ensurer(os, false);
2611 os << cell(index(0, 0));
2612 // ls.str() contains a raw LaTeX string, which might require some encoding before being valid XML.
2615 xs << xml::EndTag("td");
2618 xs << xml::StartTag("td");
2619 docstring const & num = numbers_[row];
2621 xs << '(' << num << ')';
2623 xs << xml::EndTag("td");
2625 xs << xml::EndTag("tr");
2627 xs << xml::EndTag("table");
2633 docstring InsetMathHull::xhtml(XMLStream & xs, OutputParams const & op) const
2635 BufferParams::MathOutput const mathtype =
2636 buffer().masterBuffer()->params().html_math_output;
2638 bool success = false;
2640 // we output all the labels just at the beginning of the equation.
2641 // this should be fine.
2642 for (size_t i = 0; i != label_.size(); ++i) {
2643 InsetLabel const * const il = label_[i];
2649 // FIXME Eventually we would like to do this inset by inset.
2650 if (mathtype == BufferParams::MathML) {
2651 odocstringstream os;
2652 MathMLStream ms(os);
2656 } catch (MathExportException const &) {}
2658 string const name_space_declaration = "xmlns='http://www.w3.org/1998/Math/MathML'";
2659 if (getType() == hullSimple)
2660 xs << xml::StartTag("math", name_space_declaration, true);
2662 if (!xs.isLastTagCR())
2664 xs << xml::StartTag("math", name_space_declaration + " display='block'", true);
2667 xs << XMLStream::ESCAPE_NONE
2670 if (!xs.isLastTagCR())
2672 xs << xml::EndTag("math") << xml::CR();
2674 // In case of failure, generate an image.
2675 } else if (mathtype == BufferParams::HTML) {
2676 odocstringstream os;
2681 } catch (MathExportException const &) {}
2683 string const tag = (getType() == hullSimple) ? "span" : "div";
2684 xs << xml::StartTag(tag, "class='formula'", true)
2685 << XMLStream::ESCAPE_NONE
2687 << xml::EndTag(tag);
2689 // In case of failure, generate an image.
2692 // what we actually want is this:
2694 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2696 // || mathtype == BufferParams::Images
2698 // but what follows is equivalent, since we'll enter only if either (a) we
2699 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2700 // aren't doing LaTeX.
2702 // so this is for Images.
2703 if (!success && mathtype != BufferParams::LaTeX) {
2704 graphics::PreviewImage const * pimage = nullptr;
2706 loadPreview(docit_);
2707 pimage = preview_->getPreviewImage(buffer());
2708 // FIXME Do we always have png?
2711 if (pimage || op.dryrun) {
2712 string const filename = pimage ? pimage->filename().onlyFileName()
2713 : "previewimage.png";
2715 // if we are not in the master buffer, then we need to see that the
2716 // generated image is copied there; otherwise, preview fails.
2717 Buffer const * mbuf = buffer().masterBuffer();
2718 if (mbuf != &buffer()) {
2719 string mbtmp = mbuf->temppath();
2720 FileName const mbufimg(support::addName(mbtmp, filename));
2721 pimage->filename().copyTo(mbufimg);
2723 // add the file to the list of files to be exported
2724 op.exportdata->addExternalFile("xhtml", pimage->filename());
2727 string const tag = (getType() == hullSimple) ? "span" : "div";
2729 << xml::StartTag(tag, "style = \"text-align: center;\"")
2730 << xml::CompTag("img", "src=\"" + filename + R"(" alt="Mathematical Equation")")
2737 // so we'll pass this test if we've failed everything else, or
2738 // if mathtype was LaTeX, since we won't have entered any of the
2740 if (!success /* || mathtype != BufferParams::LaTeX */) {
2741 // Unfortunately, we cannot use latexString() because we do not want
2742 // $...$ or whatever.
2743 // The returned value already has the correct escaping for HTML.
2744 docstring const latex = mathAsLatex();
2746 // class='math' allows for use of jsMath
2747 // http://www.math.union.edu/~dpvc/jsMath/
2749 // probably should allow for some kind of customization here
2750 string const tag = (getType() == hullSimple) ? "span" : "div";
2751 xs << xml::StartTag(tag, "class='math'")
2752 << XMLStream::ESCAPE_NONE << latex // Don't escape anything: latex might contain XML.
2760 void InsetMathHull::toString(odocstream & os) const
2762 odocstringstream ods;
2763 plaintext(ods, OutputParams(nullptr));
2768 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2770 odocstringstream ods;
2771 OutputParams op(nullptr);
2773 // FIXME: this results in spilling TeX into the LyXHTML output since the
2774 // outliner is used to generate the LyXHTML list of figures/etc.
2780 string InsetMathHull::contextMenuName() const
2782 return "context-math";
2786 void InsetMathHull::recordLocation(DocIterator const & di)
2792 bool InsetMathHull::canPaintChange(BufferView const &) const
2794 // We let RowPainter do it seamlessly for inline insets