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 if (previewState(mi.base.bv)) {
527 preview_->metrics(mi, dim);
528 if (previewTooSmall(dim)) {
529 // preview image is too small
530 dim.wid += 2 * ERROR_FRAME_WIDTH;
531 dim.asc += 2 * ERROR_FRAME_WIDTH;
533 // insert a gap in front of the formula
534 // value was hardcoded to 1 pixel
535 dim.wid += mi.base.bv->zoomedPixels(1) ;
537 dim.asc += top_display_margin;
538 dim.des += bottom_display_margin;
545 Changer dummy1 = mi.base.changeFontSet(standardFont());
546 Changer dummy2 = mi.base.font.changeStyle(display() ? DISPLAY_STYLE
549 // let the cells adjust themselves
550 InsetMathGrid::metrics(mi, dim);
553 // Check whether the numbering interferes with the equations
554 if (numberedType()) {
555 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
556 int extra_offset = 0;
557 for (row_type row = 0; row < nrows(); ++row) {
558 rowinfo(row).offset[mi.base.bv] += extra_offset;
559 docstring const nl = nicelabel(row);
563 mathed_string_dim(mi.base.font, nl, dimnl);
564 int const ind = indent(*mi.base.bv);
565 int const x = ind ? ind : (mi.base.textwidth - dim.wid) / 2;
566 // for some reason metrics does not trigger at the
567 // same point as draw, and therefore we use >= instead of >
568 if ((math_number == BufferParams::LEFT && dimnl.wid >= x)
569 || (math_number == BufferParams::RIGHT
570 && dimnl.wid >= mi.base.textwidth - x - dim.wid)) {
571 extra_offset += dimnl.height();
574 dim.des += extra_offset;
579 dim.asc += top_display_margin;
580 dim.des += bottom_display_margin;
583 // reserve some space for marker.
588 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
590 BufferView const * const bv = pi.base.bv;
591 if (previewState(bv)) {
592 Dimension const dim = dimension(*pi.base.bv);
593 if (previewTooSmall(dim))
595 return graphics::PreviewLoader::backgroundColor();
601 void InsetMathHull::drawMarkers(PainterInfo & pi, int x, int y) const
603 ColorCode pen_color = mouseHovered(pi.base.bv) || editing(pi.base.bv)?
604 Color_mathframe : Color_mathcorners;
605 // If the corners have the same color as the background, do not paint them.
606 if (lcolor.getX11HexName(Color_mathbg) == lcolor.getX11HexName(pen_color))
609 Inset::drawMarkers(pi, x, y);
610 Dimension const dim = dimension(*pi.base.bv);
611 int const t = x + dim.width() - 1;
612 int const a = y - dim.ascent();
613 pi.pain.line(x, a + 3, x, a, pen_color);
614 pi.pain.line(t, a + 3, t, a, pen_color);
615 pi.pain.line(x, a, x + 3, a, pen_color);
616 pi.pain.line(t - 3, a, t, a, pen_color);
620 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
622 Dimension const dim = dimension(*pi.base.bv);
623 if (previewTooSmall(dim)) {
624 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
625 dim.wid, dim.asc + dim.des, backgroundColor(pi));
629 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
630 dim.height() - 1, pi.backgroundColor(this));
634 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
636 BufferView const * const bv = pi.base.bv;
637 Dimension const dim = dimension(*bv);
639 if (type_ == hullRegexp)
640 pi.pain.rectangle(x + 2, y - dim.ascent() + 1,
641 dim.width() - 3, dim.height() - 2, Color_regexpframe);
643 if (previewState(bv)) {
644 // Do not draw change tracking cue if taken care of by RowPainter
646 Changer dummy = !canPaintChange(*bv) ? changeVar(pi.change, Change())
648 if (previewTooSmall(dim)) {
649 // we have an extra frame
650 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
652 // one pixel gap in front
653 // value was hardcoded to 1 pixel
654 int const gap = pi.base.bv->zoomedPixels(1) ;
655 preview_->draw(pi, x + gap, y);
660 // First draw the numbers
661 if (numberedType()) {
662 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
663 for (row_type row = 0; row < nrows(); ++row) {
664 int yy = y + rowinfo(row).offset[bv];
665 docstring const nl = nicelabel(row);
667 mathed_string_dim(pi.base.font, nl, dimnl);
668 if (math_number == BufferParams::LEFT) {
669 ColorCode const col = pi.selected_left
670 ? Color_selectiontext
671 : pi.base.font.color();
672 Changer dummy0 = pi.base.font.changeColor(col);
673 if (dimnl.wid > x - pi.leftx)
674 yy += rowinfo(row).descent + dimnl.asc;
675 pi.pain.fillRectangle(pi.leftx, yy - dimnl.asc,
676 dimnl.width(), dimnl.height(),
677 pi.selected_left ? Color_selection : pi.background_color);
678 pi.draw(pi.leftx, yy, nl);
680 ColorCode const col = pi.selected_right
681 ? Color_selectiontext
682 : pi.base.font.color();
683 Changer dummy0 = pi.base.font.changeColor(col);
684 if (dimnl.wid > pi.rightx - x - dim.wid)
685 yy += rowinfo(row).descent + dimnl.asc;
686 pi.pain.fillRectangle(pi.rightx - dimnl.wid, yy - dimnl.asc,
687 dimnl.width(), dimnl.height(),
688 pi.selected_right ? Color_selection : pi.background_color);
689 pi.draw(pi.rightx - dimnl.wid, yy, nl);
694 // Then the equations
695 ColorCode color = pi.selected ? Color_selectionmath : standardColor();
696 bool const really_change_color = pi.base.font.color() == Color_none;
697 Changer dummy0 = really_change_color ? pi.base.font.changeColor(color)
699 Changer dummy1 = pi.base.changeFontSet(standardFont());
700 Changer dummy2 = pi.base.font.changeStyle(display() ? DISPLAY_STYLE
702 InsetMathGrid::draw(pi, x + 1, y);
703 drawMarkers(pi, x, y);
705 // drawing change line
706 if (canPaintChange(*bv)) {
708 int const display_margin = display() ? pi.base.inPixels(Length(12, Length::PT)) : 0;
709 pi.change.paintCue(pi, x + 1, y + 1 - dim.asc + display_margin,
710 x + dim.wid, y + dim.des - display_margin);
715 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
718 InsetMathGrid::metricsT(mi, dim);
721 otexrowstream ots(os);
722 TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault);
724 dim.wid = os.str().size();
731 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
734 InsetMathGrid::drawT(pain, x, y);
737 otexrowstream ots(os);
738 TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault);
740 pain.draw(x, y, os.str().c_str());
745 static docstring latexString(InsetMathHull const & inset)
748 // This has to be static, because a preview snippet or a math
749 // macro containing math in text mode (such as $\text{$\phi$}$ or
750 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
751 // first time as a whole, and the second time only the inner math.
752 // In this last case inset.buffer() would be invalid.
753 static Encoding const * encoding = nullptr;
754 if (inset.isBufferValid())
755 encoding = &(inset.buffer().params().encoding());
756 otexrowstream ots(ls);
757 TeXMathStream wi(ots, false, true, TeXMathStream::wsPreview, encoding);
763 void InsetMathHull::initUnicodeMath() const
765 // Trigger classification of the unicode symbols in this inset
766 docstring const dummy = latexString(*this);
770 void InsetMathHull::addPreview(DocIterator const & inset_pos,
771 graphics::PreviewLoader & /*ploader*/) const
773 if (RenderPreview::previewMath()) {
774 preparePreview(inset_pos);
779 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
780 MacroNameSet & macros, MacroNameSet & defs) const
782 MacroNameSet::iterator const end = macros.end();
784 for (size_t i = 0; i < md.size(); ++i) {
785 InsetMathMacro const * mi = md[i].nucleus()->asMacro();
786 InsetMathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
787 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
788 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
789 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
790 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
792 // Look for macros in the arguments of this macro.
793 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
794 usedMacros(mi->cell(idx), pos, macros, defs);
795 // Make sure this is a macro defined in the document
796 // (as we also spot the macros in the symbols file)
797 // or that we have not already accounted for it.
798 docstring const name = mi->name();
799 if (macros.find(name) == end)
802 // Look for macros in the definition of this macro.
803 MathData ar(pos.buffer());
804 MacroData const * data =
805 pos.buffer()->getMacro(name, pos, true);
807 odocstringstream macro_def;
808 data->write(macro_def, true);
810 defs.insert(macro_def.str());
811 asArray(data->definition(), ar);
813 usedMacros(ar, pos, macros, defs);
815 MathData ar(pos.buffer());
816 asArray(mt->definition(), ar);
817 usedMacros(ar, pos, macros, defs);
819 if (!si->nuc().empty())
820 usedMacros(si->nuc(), pos, macros, defs);
822 usedMacros(si->down(), pos, macros, defs);
824 usedMacros(si->up(), pos, macros, defs);
825 } else if (fi || gi) {
826 idx_type nidx = fi ? fi->nargs() : gi->nargs();
827 for (idx_type idx = 0; idx < nidx; ++idx)
828 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
831 usedMacros(ni->cell(0), pos, macros, defs);
837 void InsetMathHull::preparePreview(DocIterator const & pos,
838 bool forexport) const
840 // there is no need to do all the macro stuff if we're not
841 // actually going to generate the preview.
842 if (!RenderPreview::previewMath() && !forexport)
845 Buffer const * buffer = pos.buffer();
847 // collect macros at this position
849 buffer->listMacroNames(macros);
851 // collect definitions only for the macros used in this inset
853 for (idx_type idx = 0; idx < nargs(); ++idx)
854 usedMacros(cell(idx), pos, macros, defs);
856 docstring macro_preamble;
857 for (auto const & defvar : defs)
858 macro_preamble.append(defvar);
860 // set the font series and size for this snippet
861 DocIterator dit = pos.getInnerText();
862 Paragraph const & par = dit.paragraph();
863 Font font = par.getFontSettings(buffer->params(), dit.pos());
864 font.fontInfo().realize(par.layout().font);
865 string const lsize = font.latexSize();
868 if (font.fontInfo().series() == BOLD_SERIES) {
869 setfont += from_ascii("\\textbf{");
872 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
873 setfont += from_ascii("\\" + lsize + '\n');
875 docstring const snippet = macro_preamble + setfont + latexString(*this) + endfont;
876 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
877 preview_->addPreview(snippet, *buffer, forexport);
881 void InsetMathHull::reloadPreview(DocIterator const & pos) const
884 preview_->startLoading(*pos.buffer());
888 void InsetMathHull::loadPreview(DocIterator const & pos) const
890 bool const forexport = true;
891 preparePreview(pos, forexport);
892 preview_->startLoading(*pos.buffer(), forexport);
896 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
898 if (RenderPreview::previewMath()) {
900 cur.screenUpdateFlags(Update::Force);
906 docstring InsetMathHull::label(row_type row) const
908 LASSERT(row < nrows(), return docstring());
909 if (InsetLabel * il = label_[row])
910 return il->screenLabel();
915 void InsetMathHull::label(row_type row, docstring const & label)
917 //lyxerr << "setting label '" << label << "' for row " << row << endl;
921 label_[row] = dummy_pointer;
924 label_[row]->updateLabelAndRefs(label);
926 label_[row]->setParam("name", label);
930 InsetCommandParams p(LABEL_CODE);
932 label_[row] = new InsetLabel(buffer_, p);
934 label_[row]->setBuffer(buffer());
938 void InsetMathHull::numbered(row_type row, Numbered num)
940 numbered_[row] = num;
944 bool InsetMathHull::numbered(row_type row) const
946 return numbered_[row] == NUMBER;
950 bool InsetMathHull::ams() const
970 for (auto const & row : numbered_)
977 bool InsetMathHull::outerDisplay() const
1000 int InsetMathHull::rowFlags() const
1017 if (buffer().params().is_math_indent)
1018 return Display | AlignLeft;
1027 int InsetMathHull::indent(BufferView const & bv) const
1029 // FIXME: set this in the textclass. This value is what the article class uses.
1030 static Length default_indent(2.5, Length::EM);
1031 if (display() && buffer().params().is_math_indent) {
1032 Length const & len = buffer().params().getMathIndent();
1034 return bv.inPixels(default_indent);
1036 return bv.inPixels(len);
1038 return Inset::indent(bv);
1042 bool InsetMathHull::numberedType() const
1061 for (row_type row = 0; row < nrows(); ++row)
1068 void InsetMathHull::validate(LaTeXFeatures & features) const
1070 if (features.runparams().isLaTeX()) {
1072 features.require("amsmath");
1074 if (type_ == hullRegexp) {
1075 features.require("color");
1076 docstring frcol = from_utf8(lcolor.getLaTeXName(Color_regexpframe));
1077 docstring bgcol = from_ascii("white");
1078 features.addPreambleSnippet(
1079 "\\newcommand{\\regexp}[1]{\\fcolorbox{"
1081 + bgcol + "}{\\ensuremath{\\mathtt{#1}}}}");
1082 features.addPreambleSnippet(
1083 from_ascii("\\newcommand{\\endregexp}{}"));
1084 } else if (outerDisplay() && features.inDeletedInset()) {
1085 features.require("tikz");
1086 features.require("ct-tikz-object-sout");
1089 // Validation is necessary only if not using AMS math.
1090 // To be safe, we will always run mathedvalidate.
1091 //if (features.amsstyle)
1094 //features.binom = true;
1095 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
1096 // it would be better to do this elsewhere, but we can't validate in
1097 // InsetMathMatrix and we have no way, outside MathExtern, to know if
1098 // we even have any matrices.
1099 features.addCSSSnippet(
1100 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
1101 "table.matrix td{padding: 0.25px;}\n"
1102 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
1103 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
1105 InsetMathGrid::validate(features);
1109 CtObject InsetMathHull::getCtObject(OutputParams const & runparams) const
1111 CtObject res = CtObject::Normal;
1127 case hullMultline: {
1128 if (runparams.inulemcmd
1129 && (!runparams.local_font || runparams.local_font->fontInfo().strikeout() != FONT_ON))
1130 res = CtObject::UDisplayObject;
1132 res = CtObject::DisplayObject;
1140 void InsetMathHull::header_write(TeXMathStream & os) const
1142 bool n = numberedType();
1153 if (cell(0).empty())
1158 writeMathdisplayPreamble(os);
1162 os << "\\begin{equation" << star(n) << "}\n";
1172 writeMathdisplayPreamble(os);
1175 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1182 os << "\\begin{" << hullName(type_) << star(n) << '}'
1183 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1189 os << "\\begin{" << hullName(type_) << '}'
1190 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1200 os << "\\begin{unknown" << star(n) << "}\n";
1206 void InsetMathHull::footer_write(TeXMathStream & os) const
1208 bool n = numberedType();
1225 os << "\\end{equation" << star(n) << "}\n";
1228 writeMathdisplayPostamble(os);
1238 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1239 writeMathdisplayPostamble(os);
1246 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1252 os << "\\end{" << hullName(type_) << "}\n";
1256 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1257 os << "\\endregexp{}}";
1263 os << "\\end{unknown" << star(n) << "}\n";
1269 bool InsetMathHull::allowsTabularFeatures() const
1292 bool InsetMathHull::rowChangeOK() const
1295 type_ == hullEqnArray || type_ == hullAlign ||
1296 type_ == hullFlAlign || type_ == hullAlignAt ||
1297 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1298 type_ == hullGather || type_ == hullMultline;
1302 bool InsetMathHull::colChangeOK() const
1305 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1306 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1310 void InsetMathHull::addRow(row_type row)
1315 bool numbered = numberedType();
1316 // Move the number and raw pointer, do not call label() (bug 7511)
1317 InsetLabel * label = dummy_pointer;
1318 docstring number = empty_docstring();
1319 if (type_ == hullMultline) {
1320 if (row + 1 == nrows()) {
1321 numbered_[row] = NONUMBER;
1322 swap(label, label_[row]);
1323 swap(number, numbers_[row]);
1328 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1329 numbers_.insert(numbers_.begin() + row + 1, number);
1330 label_.insert(label_.begin() + row + 1, label);
1331 InsetMathGrid::addRow(row);
1335 void InsetMathHull::swapRow(row_type row)
1339 if (row + 1 == nrows())
1341 swap(numbered_[row], numbered_[row + 1]);
1342 swap(numbers_[row], numbers_[row + 1]);
1343 swap(label_[row], label_[row + 1]);
1344 InsetMathGrid::swapRow(row);
1348 void InsetMathHull::delRow(row_type row)
1350 if (nrows() <= 1 || !rowChangeOK())
1352 if (row + 1 == nrows() && type_ == hullMultline) {
1353 swap(numbered_[row - 1], numbered_[row]);
1354 swap(numbers_[row - 1], numbers_[row]);
1355 swap(label_[row - 1], label_[row]);
1356 InsetMathGrid::delRow(row);
1359 InsetMathGrid::delRow(row);
1360 // The last dummy row has no number info nor a label.
1361 // Test nrows() + 1 because we have already erased the row.
1362 if (row == nrows() + 1)
1364 numbered_.erase(numbered_.begin() + row);
1365 numbers_.erase(numbers_.begin() + row);
1367 label_.erase(label_.begin() + row);
1371 void InsetMathHull::addCol(col_type col)
1375 InsetMathGrid::addCol(col);
1379 void InsetMathHull::delCol(col_type col)
1381 if (ncols() <= 1 || !colChangeOK())
1383 InsetMathGrid::delCol(col);
1387 docstring InsetMathHull::nicelabel(row_type row) const
1389 if (!numbered(row)) {
1392 return '[' + label_[row]->screenLabel() + ']';
1394 docstring const & val = numbers_[row];
1396 return '(' + val + ')';
1397 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1401 void InsetMathHull::glueall(HullType type)
1404 for (idx_type i = 0; i < nargs(); ++i)
1406 InsetLabel * label = nullptr;
1407 if (type == hullEquation) {
1408 // preserve first non-empty label
1409 for (row_type row = 0; row < nrows(); ++row) {
1411 label = label_[row];
1417 *this = InsetMathHull(buffer_, hullSimple);
1424 void InsetMathHull::splitTo2Cols()
1426 LASSERT(ncols() == 1, return);
1427 InsetMathGrid::addCol(1);
1428 for (row_type row = 0; row < nrows(); ++row) {
1429 idx_type const i = 2 * row;
1430 pos_type pos = firstRelOp(cell(i));
1431 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1432 cell(i).erase(pos, cell(i).size());
1437 void InsetMathHull::splitTo3Cols()
1439 LASSERT(ncols() < 3, return);
1442 InsetMathGrid::addCol(2);
1443 for (row_type row = 0; row < nrows(); ++row) {
1444 idx_type const i = 3 * row + 1;
1445 if (!cell(i).empty()) {
1446 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1447 cell(i).erase(1, cell(i).size());
1453 void InsetMathHull::changeCols(col_type cols)
1455 if (ncols() == cols)
1457 else if (ncols() < cols) {
1463 while (ncols() < cols)
1464 InsetMathGrid::addCol(ncols());
1470 for (row_type row = 0; row < nrows(); ++row) {
1471 idx_type const i = row * ncols();
1472 for (col_type col = cols; col < ncols(); ++col) {
1473 cell(i + cols - 1).append(cell(i + col));
1477 while (ncols() > cols) {
1478 InsetMathGrid::delCol(ncols() - 1);
1483 HullType InsetMathHull::getType() const
1489 void InsetMathHull::setType(HullType type)
1496 bool InsetMathHull::isMutable(HullType type)
1520 void InsetMathHull::mutate(HullType newtype)
1522 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1524 if (newtype == type_)
1527 // This guards the algorithm below it, which is designed with certain types
1529 if (!isMutable(newtype) || !isMutable(type_)) {
1530 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1531 << "' to '" << to_utf8(hullName(newtype))
1532 << "' not implemented" << endl;
1536 // we try to move along the chain
1537 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1539 // +-------------------------------------+
1540 // we use eqnarray as intermediate type for mutations that are not
1541 // directly supported because it handles labels and numbering for
1546 setType(hullSimple);
1552 if (newtype == hullNone) {
1556 setType(hullEquation);
1557 numbered(0, label_[0] != nullptr);
1566 setType(hullSimple);
1571 // split it "nicely" on the first relop
1573 setType(hullEqnArray);
1581 // split it "nicely"
1616 setType(hullEqnArray);
1625 for (row_type row = 0; row < nrows(); ++row)
1626 numbered(row, false);
1636 for (row_type row = 0; row < nrows(); ++row)
1637 numbered(row, false);
1644 setType(hullEqnArray);
1674 for (row_type row = 0; row < nrows(); ++row)
1675 numbered(row, false);
1679 // first we mutate to EqnArray
1681 setType(hullEqnArray);
1688 // we passed the guard so we should not be here
1689 LYXERR0("Mutation not implemented, but should have been.");
1690 LASSERT(false, return);
1696 void InsetMathHull::eol(TeXMathStream & os, row_type row, bool fragile, bool latex,
1697 bool last_eoln) const
1699 if (numberedType()) {
1700 bool const for_preview =
1701 (os.output() == TeXMathStream::wsPreview);
1703 // Use utf8 strings for previewed labels when possible
1704 bool use_utf8 = for_preview &&
1705 (buffer().params().useNonTeXFonts ||
1706 buffer().params().encoding().package() == Encoding::japanese);
1707 docstring const name = (latex && !use_utf8)
1708 ? escape(label_[row]->getParam("name"))
1709 : label_[row]->getParam("name");
1710 os << "\\label{" + name + '}';
1712 if (type_ != hullMultline) {
1713 if (numbered_[row] == NONUMBER)
1714 os << "\\nonumber ";
1715 else if (numbered_[row] == NOTAG)
1718 if (for_preview && !numbers_[row].empty()) {
1719 os << "\\global\\def\\theequation{" << numbers_[row] << "}\n";
1723 // Never add \\ on the last empty line of eqnarray and friends
1725 InsetMathGrid::eol(os, row, fragile, latex, last_eoln);
1728 void InsetMathHull::write(TeXMathStream & os) const
1730 ModeSpecifier specifier(os, MATH_MODE);
1732 InsetMathGrid::write(os);
1737 void InsetMathHull::normalize(NormalStream & os) const
1739 os << "[formula " << hullName(type_) << ' ';
1740 InsetMathGrid::normalize(os);
1745 void InsetMathHull::infoize(odocstream & os) const
1747 os << bformat(_("Type: %1$s"), hullName(type_));
1751 void InsetMathHull::check() const
1753 LATTEST(numbered_.size() == nrows());
1754 LATTEST(numbers_.size() == nrows());
1755 LATTEST(label_.size() == nrows());
1759 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1761 //FIXME: sort out whether we want std::string or docstring for those
1762 string const lang = func.getArg(0);
1763 docstring extra = from_utf8(func.getArg(1));
1765 extra = from_ascii("noextra");
1767 // replace selection with result of computation
1768 if (reduceSelectionToOneCell(cur)) {
1770 asArray(grabAndEraseSelection(cur), ar);
1771 lyxerr << "use selection: " << ar << endl;
1772 cur.insert(pipeThroughExtern(lang, extra, ar));
1776 // only inline, display or eqnarray math is allowed
1777 switch (getType()) {
1783 frontend::Alert::warning(_("Bad math environment"),
1784 _("Computation cannot be performed for AMS "
1785 "math environments.\nChange the math "
1786 "formula type and try again."));
1791 eq.push_back(MathAtom(new InsetMathChar('=')));
1793 // go to first item in line
1794 cur.idx() -= cur.idx() % ncols();
1797 if (getType() == hullSimple) {
1798 size_type pos = cur.cell().find_last(eq);
1800 if (pos == cur.cell().size()) {
1802 lyxerr << "use whole cell: " << ar << endl;
1804 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1805 lyxerr << "use partial cell form pos: " << pos << endl;
1807 cur.cell().append(eq);
1808 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1809 cur.pos() = cur.lastpos();
1813 if (getType() == hullEquation) {
1814 lyxerr << "use equation inset" << endl;
1815 mutate(hullEqnArray);
1816 MathData & ar = cur.cell();
1817 lyxerr << "use cell: " << ar << endl;
1821 cur.cell() = pipeThroughExtern(lang, extra, ar);
1822 // move to end of line
1823 cur.pos() = cur.lastpos();
1828 lyxerr << "use eqnarray" << endl;
1829 cur.idx() += 2 - cur.idx() % ncols();
1831 MathData ar = cur.cell();
1832 lyxerr << "use cell: " << ar << endl;
1833 // FIXME: temporarily disabled
1839 cur.cell() = pipeThroughExtern(lang, extra, ar);
1840 cur.pos() = cur.lastpos();
1845 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1847 //lyxerr << "action: " << cmd.action() << endl;
1848 switch (cmd.action()) {
1850 case LFUN_FINISHED_BACKWARD:
1851 case LFUN_FINISHED_FORWARD:
1852 case LFUN_FINISHED_RIGHT:
1853 case LFUN_FINISHED_LEFT:
1854 //lyxerr << "action: " << cmd.action() << endl;
1855 InsetMathGrid::doDispatch(cur, cmd);
1858 case LFUN_PARAGRAPH_BREAK:
1859 // just swallow this
1862 case LFUN_NEWLINE_INSERT:
1863 // some magic for the common case
1864 if (type_ == hullSimple || type_ == hullEquation) {
1865 cur.recordUndoInset();
1867 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1868 mutate(align ? hullAlign : hullEqnArray);
1869 // mutate() may change labels and such.
1870 cur.forceBufferUpdate();
1871 cur.idx() = nrows() * ncols() - 1;
1872 cur.pos() = cur.lastpos();
1874 InsetMathGrid::doDispatch(cur, cmd);
1877 case LFUN_MATH_NUMBER_TOGGLE: {
1878 //lyxerr << "toggling all numbers" << endl;
1879 cur.recordUndoInset();
1880 bool old = numberedType();
1881 if (type_ == hullMultline) {
1882 row_type row = nrows() - 1;
1883 numbered(row, !old);
1884 if (old && label_[row]) {
1889 for (row_type row = 0; row < nrows(); ++row) {
1890 numbered(row, !old);
1891 if (old && label_[row]) {
1898 cur.message(old ? _("No number") : _("Number"));
1899 cur.forceBufferUpdate();
1903 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1904 cur.recordUndoInset();
1905 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1906 bool old = numbered(r);
1907 cur.message(old ? _("No number") : _("Number"));
1909 if (old && label_[r]) {
1913 cur.forceBufferUpdate();
1917 case LFUN_LABEL_INSERT: {
1918 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1919 docstring old_label = label(r);
1920 docstring const default_label = from_ascii("eq:");
1921 if (old_label.empty())
1922 old_label = default_label;
1924 InsetCommandParams p(LABEL_CODE);
1925 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1926 string const data = InsetCommand::params2string(p);
1928 if (cmd.argument().empty())
1929 cur.bv().showDialog("label", data);
1931 FuncRequest fr(LFUN_INSET_INSERT, data);
1937 case LFUN_LABEL_COPY_AS_REFERENCE: {
1939 if (cmd.argument().empty() && &cur.inset() == this)
1940 // if there is no argument and we're inside math, we retrieve
1941 // the row number from the cursor position.
1942 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1944 // if there is an argument, find the corresponding label, else
1945 // check whether there is at least one label.
1946 for (row = 0; row != nrows(); ++row)
1948 && (cmd.argument().empty() || label(row) == cmd.argument()))
1955 InsetCommandParams p(REF_CODE, "ref");
1956 p["reference"] = label(row);
1957 cap::clearSelection();
1958 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1962 case LFUN_WORD_DELETE_FORWARD:
1963 case LFUN_CHAR_DELETE_FORWARD:
1964 if (col(cur.idx()) + 1 == ncols()
1965 && cur.pos() == cur.lastpos()
1966 && !cur.selection()) {
1967 if (!label(row(cur.idx())).empty()) {
1968 cur.recordUndoInset();
1969 label(row(cur.idx()), docstring());
1970 } else if (numbered(row(cur.idx()))) {
1971 cur.recordUndoInset();
1972 numbered(row(cur.idx()), false);
1973 cur.forceBufferUpdate();
1975 InsetMathGrid::doDispatch(cur, cmd);
1979 InsetMathGrid::doDispatch(cur, cmd);
1984 case LFUN_INSET_INSERT: {
1985 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1986 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1987 string const name = cmd.getArg(0);
1988 if (name == "label") {
1989 InsetCommandParams p(LABEL_CODE);
1990 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1991 docstring str = p["name"];
1992 cur.recordUndoInset();
1993 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1997 docstring old = label(r);
2000 // The label will take care of the reference update.
2004 // Newly created inset so initialize it.
2005 label_[r]->initView();
2008 cur.forceBufferUpdate();
2011 InsetMathGrid::doDispatch(cur, cmd);
2015 case LFUN_MATH_EXTERN:
2016 cur.recordUndoInset();
2020 case LFUN_MATH_MUTATE: {
2021 cur.recordUndoInset();
2022 row_type row = cur.row();
2023 col_type col = cur.col();
2024 mutate(hullType(cmd.argument()));
2025 cur.idx() = row * ncols() + col;
2026 if (cur.idx() > cur.lastidx()) {
2027 cur.idx() = cur.lastidx();
2028 cur.pos() = cur.lastpos();
2030 if (cur.pos() > cur.lastpos())
2031 cur.pos() = cur.lastpos();
2033 cur.forceBufferUpdate();
2034 // FIXME: find some more clever handling of the selection,
2035 // i.e. preserve it.
2036 cur.clearSelection();
2037 //cur.dispatched(FINISHED);
2041 case LFUN_MATH_DISPLAY: {
2042 cur.recordUndoInset();
2043 mutate(type_ == hullSimple ? hullEquation : hullSimple);
2044 // if the cursor is in a cell that got merged, move it to
2045 // start of the hull inset.
2046 if (cur.idx() > 0) {
2050 if (cur.pos() > cur.lastpos())
2051 cur.pos() = cur.lastpos();
2056 case LFUN_TABULAR_FEATURE:
2057 if (!allowsTabularFeatures())
2060 InsetMathGrid::doDispatch(cur, cmd);
2064 InsetMathGrid::doDispatch(cur, cmd);
2072 bool allowDisplayMath(Cursor const & cur)
2074 LATTEST(cur.depth() > 1);
2075 Cursor tmpcur = cur;
2078 FuncRequest cmd(LFUN_MATH_DISPLAY);
2079 return tmpcur.getStatus(cmd, status) && status.enabled();
2085 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
2086 FuncStatus & status) const
2088 switch (cmd.action()) {
2089 case LFUN_FINISHED_BACKWARD:
2090 case LFUN_FINISHED_FORWARD:
2091 case LFUN_FINISHED_RIGHT:
2092 case LFUN_FINISHED_LEFT:
2095 case LFUN_NEWLINE_INSERT:
2096 case LFUN_MATH_EXTERN:
2098 status.setEnabled(true);
2101 // we never allow this in math, and we want to bind enter
2102 // to another actions in command-alternatives
2103 case LFUN_PARAGRAPH_BREAK:
2104 status.setEnabled(false);
2106 case LFUN_MATH_MUTATE: {
2107 HullType const ht = hullType(cmd.argument());
2108 status.setOnOff(type_ == ht);
2109 status.setEnabled(isMutable(ht) && isMutable(type_));
2111 if (ht != hullSimple && status.enabled())
2112 status.setEnabled(allowDisplayMath(cur));
2115 case LFUN_MATH_DISPLAY: {
2116 status.setEnabled(display() || allowDisplayMath(cur));
2117 status.setOnOff(display());
2121 case LFUN_MATH_NUMBER_TOGGLE:
2122 // FIXME: what is the right test, this or the one of
2124 status.setEnabled(display());
2125 status.setOnOff(numberedType());
2128 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
2129 // FIXME: what is the right test, this or the one of
2131 bool const enable = (type_ == hullMultline)
2132 ? (nrows() - 1 == cur.row())
2134 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2135 status.setEnabled(enable);
2136 status.setOnOff(enable && numbered(r));
2140 case LFUN_LABEL_INSERT:
2141 status.setEnabled(type_ != hullSimple);
2144 case LFUN_LABEL_COPY_AS_REFERENCE: {
2145 bool enabled = false;
2146 if (cmd.argument().empty() && &cur.inset() == this) {
2147 // if there is no argument and we're inside math, we retrieve
2148 // the row number from the cursor position.
2149 row_type row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2150 enabled = numberedType() && label_[row];
2152 // if there is an argument, find the corresponding label, else
2153 // check whether there is at least one label.
2154 for (row_type row = 0; row != nrows(); ++row) {
2156 (cmd.argument().empty() || label(row) == cmd.argument())) {
2162 status.setEnabled(enabled);
2166 case LFUN_INSET_INSERT:
2167 if (cmd.getArg(0) == "label") {
2168 status.setEnabled(type_ != hullSimple);
2171 return InsetMathGrid::getStatus(cur, cmd, status);
2173 case LFUN_TABULAR_FEATURE: {
2174 if (!allowsTabularFeatures())
2176 string s = cmd.getArg(0);
2178 && (s == "append-row"
2179 || s == "delete-row"
2180 || s == "copy-row")) {
2181 status.message(bformat(
2182 from_utf8(N_("Can't change number of rows in '%1$s'")),
2184 status.setEnabled(false);
2188 && (s == "append-column"
2189 || s == "delete-column"
2190 || s == "copy-column")) {
2191 status.message(bformat(
2192 from_utf8(N_("Can't change number of columns in '%1$s'")),
2194 status.setEnabled(false);
2197 if (s == "add-vline-left" || s == "add-vline-right") {
2198 status.message(bformat(
2199 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2201 status.setEnabled(false);
2204 if (s == "valign-top" || s == "valign-middle"
2205 || s == "valign-bottom" || s == "align-left"
2206 || s == "align-center" || s == "align-right") {
2207 status.setEnabled(false);
2210 return InsetMathGrid::getStatus(cur, cmd, status);
2214 return InsetMathGrid::getStatus(cur, cmd, status);
2219 int InsetMathHull::leftMargin() const
2221 return (getType() == hullSimple) ? 0 : InsetMathGrid::leftMargin();
2225 int InsetMathHull::rightMargin() const
2227 return (getType() == hullSimple) ? 0 : InsetMathGrid::rightMargin();
2231 int InsetMathHull::border() const
2233 return (getType() == hullSimple) ? 0 : InsetMathGrid::border();
2237 /////////////////////////////////////////////////////////////////////
2241 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2242 docstring const & font)
2244 // this whole function is a hack and won't work for incremental font
2247 if (cur.inset().asInsetMath()->name() == font)
2248 cur.handleFont(to_utf8(font));
2250 cur.handleNest(createInsetMath(font, cur.buffer()));
2256 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2261 font.fromString(to_utf8(arg), b);
2262 if (font.fontInfo().color() != Color_inherit) {
2263 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2269 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2272 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
2273 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
2274 enter_front ? idxFirst(cur) : idxLast(cur);
2275 // The inset formula dimension is not necessarily the same as the
2276 // one of the instant preview image, so we have to indicate to the
2277 // BufferView that a metrics update is needed.
2278 cur.screenUpdateFlags(Update::Force);
2282 /////////////////////////////////////////////////////////////////////
2285 void InsetMathHull::write(ostream & os) const
2287 odocstringstream oss;
2288 otexrowstream ots(oss);
2289 TeXMathStream wi(ots, false, false, TeXMathStream::wsDefault);
2292 os << to_utf8(oss.str());
2296 void InsetMathHull::read(Lexer & lex)
2299 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2300 operator=(*at->asHullInset());
2304 bool InsetMathHull::readQuiet(Lexer & lex)
2307 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2309 operator=(*at->asHullInset());
2314 int InsetMathHull::plaintext(odocstringstream & os,
2315 OutputParams const & op, size_t max_length) const
2317 // Try enabling this now that there is a flag as requested at #2275.
2318 if (buffer().isExporting() && display()) {
2322 TextPainter tpain(dim.width(), dim.height());
2323 drawT(tpain, 0, dim.ascent());
2325 // reset metrics cache to "real" values
2327 return tpain.textheight();
2330 odocstringstream oss;
2331 otexrowstream ots(oss);
2332 Encoding const * const enc = encodings.fromLyXName("utf8");
2334 TeXMathStream::OutputType ot;
2335 if (op.find_effective())
2336 ot = TeXMathStream::wsSearchAdv;
2338 ot = TeXMathStream::wsDefault;
2340 if (type_ == hullRegexp) {
2341 TeXMathStream wi(ots, false, true, ot, enc);
2345 TeXMathStream wi(ots, false, true, ot, enc);
2346 for (row_type r = 0; r < nrows(); ++r) {
2347 for (col_type c = 0; c < ncols(); ++c)
2348 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2349 // if it's for the TOC, we write just the first line
2350 // and do not include the newline.
2351 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2353 if (r < nrows() - 1)
2357 docstring const str = oss.str();
2363 void InsetMathHull::docbook(XMLStream & xs, OutputParams const & runparams) const {
2364 // Choose the tag around the MathML equation.
2367 if (getType() == hullSimple)
2368 name = from_ascii("inlineequation");
2370 doCR = true; // This is a block equation, always have <informalequation> on its own line.
2371 name = from_ascii("informalequation");
2374 // DocBook also has <equation>, but it comes with a title.
2375 // TODO: recognise \tag from amsmath? This would allow having <equation> with a proper title.
2379 bool mathmlNamespaceInline = buffer().params().docbook_mathml_prefix == BufferParams::NoPrefix;
2380 if (mathmlNamespaceInline)
2381 attr += "xmlns=\"http://www.w3.org/1998/Math/MathML\"";
2383 for (row_type i = 0; i < nrows(); ++i) {
2384 if (!label(i).empty()) {
2388 attr += "xml:id=\"" + xml::cleanID(label(i)) + "\"";
2394 if (!xs.isLastTagCR())
2397 xs << xml::StartTag(name, attr);
2400 // With DocBook 5, MathML must be within its own namespace (defined in Buffer.cpp::writeDocBookSource, except when
2401 // it should be inlined).
2402 // Output everything in a separate stream so that this does not interfere with the standard flow of DocBook tags.
2403 std::string mathmlNamespacePrefix;
2404 if (!mathmlNamespaceInline) {
2405 if (buffer().params().docbook_mathml_prefix == BufferParams::MPrefix)
2406 mathmlNamespacePrefix = "m";
2407 else if (buffer().params().docbook_mathml_prefix == BufferParams::MMLPrefix)
2408 mathmlNamespacePrefix = "mml";
2411 odocstringstream osmath;
2412 MathMLStream ms(osmath, mathmlNamespacePrefix);
2414 // Output the MathML subtree.
2415 // TeX transcription. Avoid MTag/ETag so that there are no extraneous spaces.
2416 ms << "<" << from_ascii("alt") << " role='tex'" << ">";
2417 // Workaround for db2latex: db2latex always includes equations with
2418 // \ensuremath{} or \begin{display}\end{display}
2419 // so we strip LyX' math environment
2420 odocstringstream ls;
2422 TeXMathStream wi(ols, false, false, TeXMathStream::wsDefault, runparams.encoding);
2423 InsetMathGrid::write(wi);
2424 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2425 ms << "</" << from_ascii("alt") << ">";
2427 // Actual transformation of the formula into MathML. This translation may fail (for example, due to custom macros).
2428 // The new output stream is required to deal with the errors: first write completely the formula into this
2429 // temporary stream; then, if it is possible without error, then copy it back to the "real" stream. Otherwise,
2430 // some incomplete tags might be put into the real stream.
2432 // First, generate the MathML expression. If there is an error in the generation, this block is not fully
2433 // executed, and the formula is not output to the DocBook stream.
2434 odocstringstream ostmp;
2435 MathMLStream mstmp(ostmp, ms.xmlns());
2438 // Choose the display style for the formula, to be output as an attribute near the formula root.
2439 std::string mathmlAttr;
2440 if (getType() == hullSimple)
2441 mathmlAttr = "display=\"inline\"";
2443 mathmlAttr = "display=\"block\"";
2445 // Then, output the formula.
2446 ms << MTag("math", mathmlAttr);
2448 osmath << ostmp.str(); // osmath is not a XMLStream, so no need for XMLStream::ESCAPE_NONE.
2450 } catch (MathExportException const &) {
2452 osmath << "<mathphrase>MathML export failed. Please report this as a bug to the LyX developers: "
2453 "https://www.lyx.org/trac.</mathphrase>";
2456 // Output the complete formula to the DocBook stream.
2457 xs << XMLStream::ESCAPE_NONE << osmath.str();
2459 xs << xml::EndTag(name);
2465 bool InsetMathHull::haveNumbers() const
2467 bool havenumbers = false;
2468 // inline formulas are never numbered (bug 7351 part 3)
2469 if (getType() == hullSimple)
2471 for (size_t i = 0; i != numbered_.size(); ++i) {
2482 // We need to do something about alignment here.
2484 // This duplicates code from InsetMathGrid, but
2485 // we need access here to number information,
2486 // and we simply do not have that in InsetMathGrid.
2487 void InsetMathHull::htmlize(HtmlStream & os) const
2489 bool const havenumbers = haveNumbers();
2490 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2493 os << cell(index(0, 0));
2497 os << MTag("table", "class='mathtable'");
2498 for (row_type row = 0; row < nrows(); ++row) {
2500 for (col_type col = 0; col < ncols(); ++col) {
2502 os << cell(index(row, col));
2507 docstring const & num = numbers_[row];
2509 os << '(' << num << ')';
2514 os << ETag("table");
2518 // this duplicates code from InsetMathGrid, but
2519 // we need access here to number information,
2520 // and we simply do not have that in InsetMathGrid.
2521 void InsetMathHull::mathmlize(MathMLStream & ms) const
2523 bool const havetable = haveNumbers() || nrows() > 1 || ncols() > 1;
2525 // Simplest case: single row, single column, no numbering.
2527 ms << cell(index(0, 0));
2531 // More complex case: wrap elements in a table.
2532 if (getType() == hullSimple) {
2533 ms << MTag("mtable");
2534 } else if (getType() >= hullAlign && getType() <= hullXXAlignAt) {
2535 // hullAlign, hullAlignAt, hullXAlignAt, hullXXAlignAt
2537 for (col_type col = 0; col < ncols(); ++col) {
2538 alignment += (col % 2) ? "left " : "right ";
2540 ms << MTag("mtable", "displaystyle='true' columnalign='" + alignment + "'");
2542 ms << MTag("mtable", "displaystyle='true'");
2545 for (row_type row = 0; row < nrows(); ++row) {
2546 // No Wed browser supports mlabeledtr in 2023, even though it has been introduced in
2547 // MathML 2 (2003). Moreover, it is not supported in MathML 4 Core.
2550 for (col_type col = 0; col < ncols(); ++col) {
2552 << cell(index(row, col))
2557 if (haveNumbers()) {
2559 docstring const & num = numbers_[row];
2561 ms << MTagInline("mtext") << '(' << num << ')' << ETagInline("mtext");
2568 ms << ETag("mtable");
2572 docstring InsetMathHull::mathAsLatex() const
2574 bool const havenumbers = haveNumbers();
2575 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2578 odocstringstream ls;
2579 otexrowstream ots(ls);
2580 TeXMathStream os(ots, false, true, TeXMathStream::wsPreview);
2581 ModeSpecifier specifier(os, MATH_MODE);
2582 MathEnsurer ensurer(os, false);
2584 os << cell(index(0, 0));
2588 odocstringstream ods;
2591 xs << xml::StartTag("table", "class='mathtable'");
2592 for (row_type row = 0; row < nrows(); ++row) {
2593 xs << xml::StartTag("tr");
2594 for (col_type col = 0; col < ncols(); ++col) {
2595 xs << xml::StartTag("td", "class='math'");
2597 odocstringstream ls;
2598 otexrowstream ots(ls);
2599 TeXMathStream os(ots, false, true, TeXMathStream::wsPreview);
2600 ModeSpecifier specifier(os, MATH_MODE);
2601 MathEnsurer ensurer(os, false);
2603 os << cell(index(0, 0));
2604 // ls.str() contains a raw LaTeX string, which might require some encoding before being valid XML.
2607 xs << xml::EndTag("td");
2610 xs << xml::StartTag("td");
2611 docstring const & num = numbers_[row];
2613 xs << '(' << num << ')';
2615 xs << xml::EndTag("td");
2617 xs << xml::EndTag("tr");
2619 xs << xml::EndTag("table");
2625 docstring InsetMathHull::xhtml(XMLStream & xs, OutputParams const & op) const
2627 BufferParams::MathOutput const mathtype =
2628 buffer().masterBuffer()->params().html_math_output;
2630 bool success = false;
2632 // we output all the labels just at the beginning of the equation.
2633 // this should be fine.
2634 for (size_t i = 0; i != label_.size(); ++i) {
2635 InsetLabel const * const il = label_[i];
2641 // FIXME Eventually we would like to do this inset by inset.
2642 if (mathtype == BufferParams::MathML) {
2643 odocstringstream os;
2644 MathMLStream ms(os);
2648 } catch (MathExportException const &) {}
2650 string const name_space_declaration = "xmlns='http://www.w3.org/1998/Math/MathML'";
2651 if (getType() == hullSimple)
2652 xs << xml::StartTag("math", name_space_declaration, true);
2654 if (!xs.isLastTagCR())
2656 xs << xml::StartTag("math", name_space_declaration + " display='block'", true);
2659 xs << XMLStream::ESCAPE_NONE
2662 if (!xs.isLastTagCR())
2664 xs << xml::EndTag("math") << xml::CR();
2666 // In case of failure, generate an image.
2667 } else if (mathtype == BufferParams::HTML) {
2668 odocstringstream os;
2673 } catch (MathExportException const &) {}
2675 string const tag = (getType() == hullSimple) ? "span" : "div";
2676 xs << xml::StartTag(tag, "class='formula'", true)
2677 << XMLStream::ESCAPE_NONE
2679 << xml::EndTag(tag);
2681 // In case of failure, generate an image.
2684 // what we actually want is this:
2686 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2688 // || mathtype == BufferParams::Images
2690 // but what follows is equivalent, since we'll enter only if either (a) we
2691 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2692 // aren't doing LaTeX.
2694 // so this is for Images.
2695 if (!success && mathtype != BufferParams::LaTeX) {
2696 graphics::PreviewImage const * pimage = nullptr;
2698 loadPreview(docit_);
2699 pimage = preview_->getPreviewImage(buffer());
2700 // FIXME Do we always have png?
2703 if (pimage || op.dryrun) {
2704 string const filename = pimage ? pimage->filename().onlyFileName()
2705 : "previewimage.png";
2707 // if we are not in the master buffer, then we need to see that the
2708 // generated image is copied there; otherwise, preview fails.
2709 Buffer const * mbuf = buffer().masterBuffer();
2710 if (mbuf != &buffer()) {
2711 string mbtmp = mbuf->temppath();
2712 FileName const mbufimg(support::addName(mbtmp, filename));
2713 pimage->filename().copyTo(mbufimg);
2715 // add the file to the list of files to be exported
2716 op.exportdata->addExternalFile("xhtml", pimage->filename());
2719 string const tag = (getType() == hullSimple) ? "span" : "div";
2721 << xml::StartTag(tag, "style = \"text-align: center;\"")
2722 << xml::CompTag("img", "src=\"" + filename + R"(" alt="Mathematical Equation")")
2729 // so we'll pass this test if we've failed everything else, or
2730 // if mathtype was LaTeX, since we won't have entered any of the
2732 if (!success /* || mathtype != BufferParams::LaTeX */) {
2733 // Unfortunately, we cannot use latexString() because we do not want
2734 // $...$ or whatever.
2735 // The returned value already has the correct escaping for HTML.
2736 docstring const latex = mathAsLatex();
2738 // class='math' allows for use of jsMath
2739 // http://www.math.union.edu/~dpvc/jsMath/
2741 // probably should allow for some kind of customization here
2742 string const tag = (getType() == hullSimple) ? "span" : "div";
2743 xs << xml::StartTag(tag, "class='math'")
2744 << XMLStream::ESCAPE_NONE << latex // Don't escape anything: latex might contain XML.
2752 void InsetMathHull::toString(odocstream & os) const
2754 odocstringstream ods;
2755 plaintext(ods, OutputParams(nullptr));
2760 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2762 odocstringstream ods;
2763 OutputParams op(nullptr);
2765 // FIXME: this results in spilling TeX into the LyXHTML output since the
2766 // outliner is used to generate the LyXHTML list of figures/etc.
2772 string InsetMathHull::contextMenuName() const
2774 return "context-math";
2778 void InsetMathHull::recordLocation(DocIterator const & di)
2784 bool InsetMathHull::canPaintChange(BufferView const &) const
2786 // We let RowPainter do it seamlessly for inline insets