2 * \file InsetMathHull.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 #include "InsetMathHull.h"
14 #include "InsetMathChar.h"
15 #include "InsetMathColor.h"
16 #include "InsetMathFrac.h"
17 #include "InsetMathNest.h"
18 #include "InsetMathScript.h"
19 #include "MathExtern.h"
20 #include "MathFactory.h"
21 #include "MathStream.h"
22 #include "MathSupport.h"
25 #include "BufferParams.h"
26 #include "BufferView.h"
29 #include "CutAndPaste.h"
32 #include "FuncRequest.h"
33 #include "FuncStatus.h"
35 #include "LaTeXFeatures.h"
37 #include "MacroTable.h"
38 #include "InsetMathMacro.h"
39 #include "InsetMathMacroTemplate.h"
40 #include "MetricsInfo.h"
41 #include "Paragraph.h"
42 #include "ParIterator.h"
45 #include "TextClass.h"
46 #include "TextPainter.h"
47 #include "TocBackend.h"
49 #include "insets/InsetLabel.h"
50 #include "insets/InsetRef.h"
51 #include "insets/RenderPreview.h"
53 #include "graphics/PreviewImage.h"
54 #include "graphics/PreviewLoader.h"
56 #include "frontends/alert.h"
57 #include "frontends/FontMetrics.h"
58 #include "frontends/Painter.h"
60 #include "support/convert.h"
61 #include "support/debug.h"
62 #include "support/gettext.h"
63 #include "support/filetools.h"
64 #include "support/lassert.h"
65 #include "support/lstrings.h"
66 #include "support/Changer.h"
71 using namespace lyx::support;
75 using cap::grabAndEraseSelection;
76 using cap::reduceSelectionToOneCell;
80 int getCols(HullType type)
105 // returns position of first relation operator in the array
106 // used for "intelligent splitting"
107 size_t firstRelOp(MathData const & ar)
109 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
110 if ((*it)->mathClass() == MC_REL)
111 return it - ar.begin();
116 char const * star(bool numbered)
118 return numbered ? "" : "*";
122 // writes a preamble for underlined or struck out math display
123 void writeMathdisplayPreamble(TeXMathStream & os)
125 if (os.strikeoutMath())
128 if (os.ulemCmd() == TeXMathStream::UNDERLINE)
129 os << "\\raisebox{-\\belowdisplayshortskip}{"
130 "\\parbox[b]{\\linewidth}{";
131 else if (os.ulemCmd() == TeXMathStream::STRIKEOUT)
132 os << "\\parbox{\\linewidth}{";
136 // writes a postamble for underlined or struck out math display
137 void writeMathdisplayPostamble(TeXMathStream & os)
139 if (os.strikeoutMath())
142 if (os.ulemCmd() == TeXMathStream::UNDERLINE)
144 else if (os.ulemCmd() == TeXMathStream::STRIKEOUT)
151 static InsetLabel * dummy_pointer = nullptr;
153 InsetMathHull::InsetMathHull(Buffer * buf)
154 : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, NONUMBER),
155 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
156 preview_(new RenderPreview(this))
158 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
159 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
160 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
161 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
168 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
169 : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, NONUMBER),
170 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
171 preview_(new RenderPreview(this))
179 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
185 InsetMathHull::~InsetMathHull()
187 for (auto & i : label_)
192 Inset * InsetMathHull::clone() const
194 return new InsetMathHull(*this);
198 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
202 InsetMathGrid::operator=(other);
204 numbered_ = other.numbered_;
205 numbers_ = other.numbers_;
206 buffer_ = other.buffer_;
207 for (auto & i : label_)
209 label_ = other.label_;
210 for (size_t i = 0; i != label_.size(); ++i) {
212 label_[i] = new InsetLabel(*label_[i]);
214 preview_.reset(new RenderPreview(*other.preview_, this));
220 void InsetMathHull::setBuffer(Buffer & buffer)
222 InsetMathGrid::setBuffer(buffer);
224 for (size_t i = 0; i != label_.size(); ++i) {
226 label_[i]->setBuffer(buffer);
231 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
234 //FIXME: buffer_ should be set at creation for this inset! Problem is
235 // This inset is created at too many places (see Parser::parse1() in
240 // if any of the equations are numbered, then we want to save the values
241 // of some of the counters.
243 BufferParams const & bp = buffer_->params();
244 string const & lang = it->getParLanguage(bp)->code();
246 buffer_->masterBuffer()->params().documentClass().counters();
248 // this has to be done separately
249 docstring const eqstr = from_ascii("equation");
250 if (cnts.hasCounter(eqstr)) {
251 for (size_t i = 0; i != label_.size(); ++i) {
252 docstring const oldnumber = numbers_[i];
254 Paragraph const & par = it.paragraph();
255 if (!par.isDeleted(it.pos())) {
256 cnts.step(eqstr, utype);
257 numbers_[i] = cnts.theCounter(eqstr, lang);
259 numbers_[i] = from_ascii("#");
261 numbers_[i] = empty_docstring();
262 // If the numbering has changed, trigger a new preview
263 if (oldnumber != numbers_[i] && RenderPreview::previewMath()) {
264 // Do we need to remove it first?
265 //preview_->removePreview(*buffer_);
273 for (size_t i = 0; i != label_.size(); ++i) {
275 label_[i]->updateBuffer(it, utype, deleted);
278 InsetMathGrid::updateBuffer(it, utype, deleted);
282 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active,
283 UpdateType utype, TocBackend & backend) const
286 //FIXME: buffer_ should be set at creation for this inset! Problem is
287 // This inset is created at too many places (see Parser::parse1() in
292 // compute first and last item
293 row_type first = nrows();
294 for (row_type row = 0; row != nrows(); ++row)
299 if (first == nrows())
302 row_type last = nrows() - 1;
303 for (; last != 0; --last)
307 TocBuilder & b = backend.builder("equation");
308 // add equation numbers
309 b.pushItem(pit, docstring(), output_active);
311 b.argumentItem(bformat(from_ascii("(%1$s-%2$s)"),
312 numbers_[first], numbers_[last]));
313 for (row_type row = 0; row != nrows(); ++row) {
317 label_[row]->setPrettyCounter(_("Equation ") + numbers_[row]);
318 label_[row]->addToToc(pit, output_active, utype, backend);
320 docstring label = nicelabel(row);
322 // this is the only equation
323 b.argumentItem(label);
325 // insert as sub-items
326 b.pushItem(pit, label, output_active);
334 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
336 if (previewState(&cur.bv())) {
340 return InsetMathNest::editXY(cur, x, y);
344 InsetMath::mode_type InsetMathHull::currentMode() const
348 return UNDECIDED_MODE;
350 // definitely math mode ...
370 // FIXME: InsetMathGrid should be changed to let the real column alignment be
371 // given by a virtual method like displayColAlign, because the values produced
372 // by defaultColAlign can be invalidated by lfuns such as add-column. For the
373 // moment the values produced by defaultColAlign are not used, notably because
374 // alignment is not implemented in the LyXHTML output.
375 char InsetMathHull::defaultColAlign(col_type col)
377 return colAlign(type_, col);
381 char InsetMathHull::displayColAlign(idx_type idx) const
385 row_type const r = row(idx);
388 if (r == nrows() - 1)
399 return colAlign(type_, col(idx));
403 return InsetMathGrid::displayColAlign(idx);
407 int InsetMathHull::displayColSpace(col_type col) const
409 return colSpace(type_, col);
413 // FIXME: same comment as for defaultColAlign applies.
414 int InsetMathHull::defaultColSpace(col_type col)
416 return colSpace(type_, col);
420 string InsetMathHull::standardFont() const
426 return "lyxnochange";
433 ColorCode InsetMathHull::standardColor() const
438 return Color_foreground;
446 bool InsetMathHull::previewState(const BufferView *const bv) const
448 if (!editing(bv) && RenderPreview::previewMath()
449 && type_ != hullRegexp)
451 graphics::PreviewImage const * pimage =
452 preview_->getPreviewImage(bv->buffer());
453 return pimage && pimage->image();
460 const int ERROR_FRAME_WIDTH = 2;
462 bool previewTooSmall(Dimension const & dim)
464 return dim.width() <= 10 && dim.height() <= 10;
469 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
471 /* Compute \(above|below)displayskip
472 true value in LaTeX is 10pt plus 2pt minus 5pt (in normal size at 10pt)
473 But we use a fixed number of pixels and scale them with zoom.
475 int const bottom_display_margin = mi.base.bv->zoomedPixels(6);
476 int top_display_margin = bottom_display_margin;
477 // at start of paragraph, add an empty line
479 top_display_margin += theFontMetrics(mi.base.font).maxHeight() + 2;
481 int const ind = indent(*mi.base.bv);
484 if (previewState(mi.base.bv)) {
485 preview_->metrics(mi, dim);
486 if (previewTooSmall(dim)) {
487 // preview image is too small
488 dim.wid += 2 * ERROR_FRAME_WIDTH;
489 dim.asc += 2 * ERROR_FRAME_WIDTH;
491 // insert a gap in front of the formula
492 // value was hardcoded to 1 pixel
493 dim.wid += mi.base.bv->zoomedPixels(1) ;
495 dim.asc += top_display_margin;
496 dim.des += bottom_display_margin;
503 Changer dummy1 = mi.base.changeFontSet(standardFont());
504 Changer dummy2 = mi.base.font.changeStyle(display() ? DISPLAY_STYLE
507 // let the cells adjust themselves
508 InsetMathGrid::metrics(mi, dim);
511 // Check whether the numbering interferes with the equations
512 if (numberedType()) {
513 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
514 int extra_offset = 0;
516 for (row_type row = 0; row < nrows(); ++row) {
517 rowinfo(row).offset[mi.base.bv] += extra_offset;
518 docstring const nl = nicelabel(row);
522 mathed_string_dim(mi.base.font, nl, dimnl);
523 int const x = ind ? ind : (mi.base.textwidth - dim.wid) / 2;
524 // for some reason metrics does not trigger at the
525 // same point as draw, and therefore we use >= instead of >
526 if ((math_number == BufferParams::LEFT && dimnl.wid >= x)
527 || (math_number == BufferParams::RIGHT
528 && dimnl.wid >= mi.base.textwidth - x - dim.wid)) {
529 extra_offset += dimnl.height();
530 } else if (dimnl.wid > max_nlwid)
531 max_nlwid = dimnl.wid;
533 mi.extrawidth += max_nlwid;
534 dim.des += extra_offset;
539 dim.asc += top_display_margin;
540 dim.des += bottom_display_margin;
543 // reserve some space for marker.
548 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
550 BufferView const * const bv = pi.base.bv;
551 if (previewState(bv)) {
552 Dimension const dim = dimension(*pi.base.bv);
553 if (previewTooSmall(dim))
555 return graphics::PreviewLoader::backgroundColor();
561 void InsetMathHull::drawMarkers(PainterInfo & pi, int x, int y) const
563 ColorCode pen_color = mouseHovered(pi.base.bv) || editing(pi.base.bv)?
564 Color_mathframe : Color_mathcorners;
565 // If the corners have the same color as the background, do not paint them.
566 if (lcolor.getX11HexName(Color_mathbg) == lcolor.getX11HexName(pen_color))
569 Inset::drawMarkers(pi, x, y);
570 Dimension const dim = dimension(*pi.base.bv);
571 int const t = x + dim.width() - 1;
572 int const a = y - dim.ascent();
573 pi.pain.line(x, a + 3, x, a, pen_color);
574 pi.pain.line(t, a + 3, t, a, pen_color);
575 pi.pain.line(x, a, x + 3, a, pen_color);
576 pi.pain.line(t - 3, a, t, a, pen_color);
580 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
582 Dimension const dim = dimension(*pi.base.bv);
583 if (previewTooSmall(dim)) {
584 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
585 dim.wid, dim.asc + dim.des, backgroundColor(pi));
589 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
590 dim.height() - 1, pi.backgroundColor(this));
594 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
596 BufferView const * const bv = pi.base.bv;
597 Dimension const dim = dimension(*bv);
599 if (type_ == hullRegexp)
600 pi.pain.rectangle(x + 2, y - dim.ascent() + 1,
601 dim.width() - 3, dim.height() - 2, Color_regexpframe);
603 if (previewState(bv)) {
604 // Do not draw change tracking cue if taken care of by RowPainter
606 Changer dummy = !canPaintChange(*bv) ? changeVar(pi.change, Change())
608 if (previewTooSmall(dim)) {
609 // we have an extra frame
610 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
612 // one pixel gap in front
613 // value was hardcoded to 1 pixel
614 int const gap = pi.base.bv->zoomedPixels(1) ;
615 preview_->draw(pi, x + gap, y);
620 // First draw the numbers
621 if (numberedType()) {
622 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
623 for (row_type row = 0; row < nrows(); ++row) {
624 int yy = y + rowinfo(row).offset[bv];
625 docstring const nl = nicelabel(row);
627 mathed_string_dim(pi.base.font, nl, dimnl);
628 if (math_number == BufferParams::LEFT) {
629 ColorCode const col = pi.selected_left
630 ? Color_selectiontext
631 : pi.base.font.color();
632 Changer dummy0 = pi.base.font.changeColor(col);
633 if (dimnl.wid > x - pi.leftx)
634 yy += rowinfo(row).descent + dimnl.asc;
635 pi.pain.fillRectangle(pi.leftx, yy - dimnl.asc,
636 dimnl.width(), dimnl.height(),
637 pi.selected_left ? Color_selection : pi.background_color);
638 pi.draw(pi.leftx, yy, nl);
640 ColorCode const col = pi.selected_right
641 ? Color_selectiontext
642 : pi.base.font.color();
643 Changer dummy0 = pi.base.font.changeColor(col);
644 if (dimnl.wid > pi.rightx - x - dim.wid)
645 yy += rowinfo(row).descent + dimnl.asc;
646 pi.pain.fillRectangle(pi.rightx - dimnl.wid, yy - dimnl.asc,
647 dimnl.width(), dimnl.height(),
648 pi.selected_right ? Color_selection : pi.background_color);
649 pi.draw(pi.rightx - dimnl.wid, yy, nl);
654 // Then the equations
655 ColorCode color = pi.selected && lyxrc.use_system_colors
656 ? Color_selectiontext : standardColor();
657 bool const really_change_color = pi.base.font.color() == Color_none;
658 Changer dummy0 = really_change_color ? pi.base.font.changeColor(color)
660 Changer dummy1 = pi.base.changeFontSet(standardFont());
661 Changer dummy2 = pi.base.font.changeStyle(display() ? DISPLAY_STYLE
663 InsetMathGrid::draw(pi, x + 1, y);
664 drawMarkers(pi, x, y);
666 // drawing change line
667 if (canPaintChange(*bv)) {
669 int const display_margin = display() ? pi.base.inPixels(Length(12, Length::PT)) : 0;
670 pi.change.paintCue(pi, x + 1, y + 1 - dim.asc + display_margin,
671 x + dim.wid, y + dim.des - display_margin);
676 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
679 InsetMathGrid::metricsT(mi, dim);
682 otexrowstream ots(os);
683 TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault);
685 dim.wid = os.str().size();
692 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
695 InsetMathGrid::drawT(pain, x, y);
698 otexrowstream ots(os);
699 TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault);
701 pain.draw(x, y, os.str().c_str());
706 static docstring latexString(InsetMathHull const & inset)
709 // This has to be static, because a preview snippet or a math
710 // macro containing math in text mode (such as $\text{$\phi$}$ or
711 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
712 // first time as a whole, and the second time only the inner math.
713 // In this last case inset.buffer() would be invalid.
714 static Encoding const * encoding = nullptr;
715 if (inset.isBufferValid())
716 encoding = &(inset.buffer().params().encoding());
717 otexrowstream ots(ls);
718 TeXMathStream wi(ots, false, true, TeXMathStream::wsPreview, encoding);
724 void InsetMathHull::initUnicodeMath() const
726 // Trigger classification of the unicode symbols in this inset
727 docstring const dummy = latexString(*this);
731 void InsetMathHull::addPreview(DocIterator const & inset_pos,
732 graphics::PreviewLoader & /*ploader*/) const
734 if (RenderPreview::previewMath()) {
735 preparePreview(inset_pos);
740 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
741 MacroNameSet & macros, MacroNameSet & defs) const
743 MacroNameSet::iterator const end = macros.end();
745 for (size_t i = 0; i < md.size(); ++i) {
746 InsetMathMacro const * mi = md[i].nucleus()->asMacro();
747 InsetMathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
748 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
749 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
750 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
751 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
753 // Look for macros in the arguments of this macro.
754 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
755 usedMacros(mi->cell(idx), pos, macros, defs);
756 // Make sure this is a macro defined in the document
757 // (as we also spot the macros in the symbols file)
758 // or that we have not already accounted for it.
759 docstring const name = mi->name();
760 if (macros.find(name) == end)
763 // Look for macros in the definition of this macro.
764 MathData ar(pos.buffer());
765 MacroData const * data =
766 pos.buffer()->getMacro(name, pos, true);
768 odocstringstream macro_def;
769 data->write(macro_def, true);
771 defs.insert(macro_def.str());
772 asArray(data->definition(), ar);
774 usedMacros(ar, pos, macros, defs);
776 MathData ar(pos.buffer());
777 asArray(mt->definition(), ar);
778 usedMacros(ar, pos, macros, defs);
780 if (!si->nuc().empty())
781 usedMacros(si->nuc(), pos, macros, defs);
783 usedMacros(si->down(), pos, macros, defs);
785 usedMacros(si->up(), pos, macros, defs);
786 } else if (fi || gi) {
787 idx_type nidx = fi ? fi->nargs() : gi->nargs();
788 for (idx_type idx = 0; idx < nidx; ++idx)
789 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
792 usedMacros(ni->cell(0), pos, macros, defs);
798 void InsetMathHull::preparePreview(DocIterator const & pos,
799 bool forexport) const
801 // there is no need to do all the macro stuff if we're not
802 // actually going to generate the preview.
803 if (!RenderPreview::previewMath() && !forexport)
806 Buffer const * buffer = pos.buffer();
808 // collect macros at this position
810 buffer->listMacroNames(macros);
812 // collect definitions only for the macros used in this inset
814 for (idx_type idx = 0; idx < nargs(); ++idx)
815 usedMacros(cell(idx), pos, macros, defs);
817 docstring macro_preamble;
818 for (auto const & defvar : defs)
819 macro_preamble.append(defvar);
821 // set the font series and size for this snippet
822 DocIterator dit = pos.getInnerText();
823 Paragraph const & par = dit.paragraph();
824 Font font = par.getFontSettings(buffer->params(), dit.pos());
825 font.fontInfo().realize(par.layout().font);
826 string const lsize = font.latexSize();
829 if (font.fontInfo().series() == BOLD_SERIES) {
830 setfont += from_ascii("\\textbf{");
833 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
834 setfont += from_ascii("\\" + lsize + '\n');
836 docstring const snippet = macro_preamble + setfont + latexString(*this) + endfont;
837 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
838 preview_->addPreview(snippet, *buffer, forexport);
842 void InsetMathHull::reloadPreview(DocIterator const & pos) const
845 preview_->startLoading(*pos.buffer());
849 void InsetMathHull::loadPreview(DocIterator const & pos) const
851 bool const forexport = true;
852 preparePreview(pos, forexport);
853 preview_->startLoading(*pos.buffer(), forexport);
857 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
859 if (RenderPreview::previewMath()) {
861 cur.screenUpdateFlags(Update::Force);
867 docstring InsetMathHull::label(row_type row) const
869 LASSERT(row < nrows(), return docstring());
870 if (InsetLabel * il = label_[row])
871 return il->screenLabel();
876 void InsetMathHull::label(row_type row, docstring const & label)
878 //lyxerr << "setting label '" << label << "' for row " << row << endl;
882 label_[row] = dummy_pointer;
885 label_[row]->updateLabelAndRefs(label);
887 label_[row]->setParam("name", label);
891 InsetCommandParams p(LABEL_CODE);
893 label_[row] = new InsetLabel(buffer_, p);
895 label_[row]->setBuffer(buffer());
899 void InsetMathHull::numbered(row_type row, Numbered num)
901 numbered_[row] = num;
905 bool InsetMathHull::numbered(row_type row) const
907 return numbered_[row] == NUMBER;
911 bool InsetMathHull::ams() const
931 for (auto const & row : numbered_)
938 bool InsetMathHull::outerDisplay() const
961 int InsetMathHull::rowFlags() const
978 if (buffer().params().is_math_indent)
979 return Display | AlignLeft;
988 int InsetMathHull::indent(BufferView const & bv) const
990 // FIXME: set this in the textclass. This value is what the article class uses.
991 static Length default_indent(2.5, Length::EM);
992 if (display() && buffer().params().is_math_indent) {
993 Length const & len = buffer().params().getMathIndent();
995 return bv.inPixels(default_indent);
997 return bv.inPixels(len);
999 return Inset::indent(bv);
1003 bool InsetMathHull::numberedType() const
1022 for (row_type row = 0; row < nrows(); ++row)
1029 void InsetMathHull::validate(LaTeXFeatures & features) const
1031 if (features.runparams().isLaTeX()) {
1033 features.require("amsmath");
1035 if (type_ == hullRegexp) {
1036 features.require("color");
1037 docstring frcol = from_utf8(lcolor.getLaTeXName(Color_regexpframe));
1038 docstring bgcol = from_ascii("white");
1039 features.addPreambleSnippet(
1040 "\\newcommand{\\regexp}[1]{\\fcolorbox{"
1042 + bgcol + "}{\\ensuremath{\\mathtt{#1}}}}");
1043 features.addPreambleSnippet(
1044 from_ascii("\\newcommand{\\endregexp}{}"));
1045 } else if (outerDisplay() && features.inDeletedInset()) {
1046 features.require("tikz");
1047 features.require("ct-tikz-object-sout");
1050 // Validation is necessary only if not using AMS math.
1051 // To be safe, we will always run mathedvalidate.
1052 //if (features.amsstyle)
1055 //features.binom = true;
1056 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
1057 // it would be better to do this elsewhere, but we can't validate in
1058 // InsetMathMatrix and we have no way, outside MathExtern, to know if
1059 // we even have any matrices.
1060 features.addCSSSnippet(
1061 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
1062 "table.matrix td{padding: 0.25px;}\n"
1063 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
1064 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
1066 InsetMathGrid::validate(features);
1070 CtObject InsetMathHull::getCtObject(OutputParams const & runparams) const
1072 CtObject res = CtObject::Normal;
1088 case hullMultline: {
1089 if (runparams.inulemcmd
1090 && (!runparams.local_font || runparams.local_font->fontInfo().strikeout() != FONT_ON))
1091 res = CtObject::UDisplayObject;
1093 res = CtObject::DisplayObject;
1101 void InsetMathHull::header_write(TeXMathStream & os) const
1103 bool n = numberedType();
1114 if (cell(0).empty())
1119 writeMathdisplayPreamble(os);
1123 os << "\\begin{equation" << star(n) << "}\n";
1133 writeMathdisplayPreamble(os);
1136 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1143 os << "\\begin{" << hullName(type_) << star(n) << '}'
1144 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1150 os << "\\begin{" << hullName(type_) << '}'
1151 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1161 os << "\\begin{unknown" << star(n) << "}\n";
1167 void InsetMathHull::footer_write(TeXMathStream & os) const
1169 bool n = numberedType();
1186 os << "\\end{equation" << star(n) << "}\n";
1189 writeMathdisplayPostamble(os);
1199 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1200 writeMathdisplayPostamble(os);
1207 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1213 os << "\\end{" << hullName(type_) << "}\n";
1217 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1218 os << "\\endregexp{}}";
1224 os << "\\end{unknown" << star(n) << "}\n";
1230 bool InsetMathHull::allowsTabularFeatures() const
1253 bool InsetMathHull::rowChangeOK() const
1256 type_ == hullEqnArray || type_ == hullAlign ||
1257 type_ == hullFlAlign || type_ == hullAlignAt ||
1258 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1259 type_ == hullGather || type_ == hullMultline;
1263 bool InsetMathHull::colChangeOK() const
1266 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1267 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1271 void InsetMathHull::addRow(row_type row)
1276 bool numbered = numberedType();
1277 // Move the number and raw pointer, do not call label() (bug 7511)
1278 InsetLabel * label = dummy_pointer;
1279 docstring number = empty_docstring();
1280 if (type_ == hullMultline) {
1281 if (row + 1 == nrows()) {
1282 numbered_[row] = NONUMBER;
1283 swap(label, label_[row]);
1284 swap(number, numbers_[row]);
1289 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1290 numbers_.insert(numbers_.begin() + row + 1, number);
1291 label_.insert(label_.begin() + row + 1, label);
1292 InsetMathGrid::addRow(row);
1296 void InsetMathHull::swapRow(row_type row)
1300 if (row + 1 == nrows())
1302 swap(numbered_[row], numbered_[row + 1]);
1303 swap(numbers_[row], numbers_[row + 1]);
1304 swap(label_[row], label_[row + 1]);
1305 InsetMathGrid::swapRow(row);
1309 void InsetMathHull::delRow(row_type row)
1311 if (nrows() <= 1 || !rowChangeOK())
1313 if (row + 1 == nrows() && type_ == hullMultline) {
1314 swap(numbered_[row - 1], numbered_[row]);
1315 swap(numbers_[row - 1], numbers_[row]);
1316 swap(label_[row - 1], label_[row]);
1317 InsetMathGrid::delRow(row);
1320 InsetMathGrid::delRow(row);
1321 // The last dummy row has no number info nor a label.
1322 // Test nrows() + 1 because we have already erased the row.
1323 if (row == nrows() + 1)
1325 numbered_.erase(numbered_.begin() + row);
1326 numbers_.erase(numbers_.begin() + row);
1328 label_.erase(label_.begin() + row);
1332 void InsetMathHull::addCol(col_type col)
1336 InsetMathGrid::addCol(col);
1340 void InsetMathHull::delCol(col_type col)
1342 if (ncols() <= 1 || !colChangeOK())
1344 InsetMathGrid::delCol(col);
1348 docstring InsetMathHull::nicelabel(row_type row) const
1350 if (!numbered(row)) {
1353 return '[' + label_[row]->screenLabel() + ']';
1355 docstring const & val = numbers_[row];
1357 return '(' + val + ')';
1358 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1362 void InsetMathHull::glueall(HullType type)
1365 for (idx_type i = 0; i < nargs(); ++i)
1367 InsetLabel * label = nullptr;
1368 if (type == hullEquation) {
1369 // preserve first non-empty label
1370 for (row_type row = 0; row < nrows(); ++row) {
1372 label = label_[row];
1378 *this = InsetMathHull(buffer_, hullSimple);
1385 void InsetMathHull::splitTo2Cols()
1387 LASSERT(ncols() == 1, return);
1388 InsetMathGrid::addCol(1);
1389 for (row_type row = 0; row < nrows(); ++row) {
1390 idx_type const i = 2 * row;
1391 pos_type pos = firstRelOp(cell(i));
1392 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1393 cell(i).erase(pos, cell(i).size());
1398 void InsetMathHull::splitTo3Cols()
1400 LASSERT(ncols() < 3, return);
1403 InsetMathGrid::addCol(2);
1404 for (row_type row = 0; row < nrows(); ++row) {
1405 idx_type const i = 3 * row + 1;
1406 if (!cell(i).empty()) {
1407 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1408 cell(i).erase(1, cell(i).size());
1414 void InsetMathHull::changeCols(col_type cols)
1416 if (ncols() == cols)
1418 else if (ncols() < cols) {
1424 while (ncols() < cols)
1425 InsetMathGrid::addCol(ncols());
1431 for (row_type row = 0; row < nrows(); ++row) {
1432 idx_type const i = row * ncols();
1433 for (col_type col = cols; col < ncols(); ++col) {
1434 cell(i + cols - 1).append(cell(i + col));
1438 while (ncols() > cols) {
1439 InsetMathGrid::delCol(ncols() - 1);
1444 HullType InsetMathHull::getType() const
1450 void InsetMathHull::setType(HullType type)
1457 bool InsetMathHull::isMutable(HullType type)
1481 void InsetMathHull::mutate(HullType newtype)
1483 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1485 if (newtype == type_)
1488 // This guards the algorithm below it, which is designed with certain types
1490 if (!isMutable(newtype) || !isMutable(type_)) {
1491 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1492 << "' to '" << to_utf8(hullName(newtype))
1493 << "' not implemented" << endl;
1497 // we try to move along the chain
1498 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1500 // +-------------------------------------+
1501 // we use eqnarray as intermediate type for mutations that are not
1502 // directly supported because it handles labels and numbering for
1507 setType(hullSimple);
1513 if (newtype == hullNone) {
1517 setType(hullEquation);
1518 numbered(0, label_[0] != nullptr);
1527 setType(hullSimple);
1532 // split it "nicely" on the first relop
1534 setType(hullEqnArray);
1542 // split it "nicely"
1577 setType(hullEqnArray);
1586 for (row_type row = 0; row < nrows(); ++row)
1587 numbered(row, false);
1597 for (row_type row = 0; row < nrows(); ++row)
1598 numbered(row, false);
1605 setType(hullEqnArray);
1635 for (row_type row = 0; row < nrows(); ++row)
1636 numbered(row, false);
1640 // first we mutate to EqnArray
1642 setType(hullEqnArray);
1649 // we passed the guard so we should not be here
1650 LYXERR0("Mutation not implemented, but should have been.");
1651 LASSERT(false, return);
1657 void InsetMathHull::eol(TeXMathStream & os, row_type row, bool fragile, bool latex,
1658 bool last_eoln) const
1660 if (numberedType()) {
1662 docstring const name =
1663 latex ? escape(label_[row]->getParam("name"))
1664 : label_[row]->getParam("name");
1665 os << "\\label{" + name + '}';
1667 if (type_ != hullMultline) {
1668 if (numbered_[row] == NONUMBER)
1669 os << "\\nonumber ";
1670 else if (numbered_[row] == NOTAG)
1673 if (os.output() == TeXMathStream::wsPreview && !numbers_[row].empty()) {
1674 os << "\\global\\def\\theequation{" << numbers_[row] << "}\n";
1678 // Never add \\ on the last empty line of eqnarray and friends
1680 InsetMathGrid::eol(os, row, fragile, latex, last_eoln);
1683 void InsetMathHull::write(TeXMathStream & os) const
1685 ModeSpecifier specifier(os, MATH_MODE);
1687 InsetMathGrid::write(os);
1692 void InsetMathHull::normalize(NormalStream & os) const
1694 os << "[formula " << hullName(type_) << ' ';
1695 InsetMathGrid::normalize(os);
1700 void InsetMathHull::infoize(odocstream & os) const
1702 os << bformat(_("Type: %1$s"), hullName(type_));
1706 void InsetMathHull::check() const
1708 LATTEST(numbered_.size() == nrows());
1709 LATTEST(numbers_.size() == nrows());
1710 LATTEST(label_.size() == nrows());
1714 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1716 //FIXME: sort out whether we want std::string or docstring for those
1717 string const lang = func.getArg(0);
1718 docstring extra = from_utf8(func.getArg(1));
1720 extra = from_ascii("noextra");
1722 // replace selection with result of computation
1723 if (reduceSelectionToOneCell(cur)) {
1725 asArray(grabAndEraseSelection(cur), ar);
1726 lyxerr << "use selection: " << ar << endl;
1727 cur.insert(pipeThroughExtern(lang, extra, ar));
1731 // only inline, display or eqnarray math is allowed
1732 switch (getType()) {
1738 frontend::Alert::warning(_("Bad math environment"),
1739 _("Computation cannot be performed for AMS "
1740 "math environments.\nChange the math "
1741 "formula type and try again."));
1746 eq.push_back(MathAtom(new InsetMathChar('=')));
1748 // go to first item in line
1749 cur.idx() -= cur.idx() % ncols();
1752 if (getType() == hullSimple) {
1753 size_type pos = cur.cell().find_last(eq);
1755 if (pos == cur.cell().size()) {
1757 lyxerr << "use whole cell: " << ar << endl;
1759 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1760 lyxerr << "use partial cell form pos: " << pos << endl;
1762 cur.cell().append(eq);
1763 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1764 cur.pos() = cur.lastpos();
1768 if (getType() == hullEquation) {
1769 lyxerr << "use equation inset" << endl;
1770 mutate(hullEqnArray);
1771 MathData & ar = cur.cell();
1772 lyxerr << "use cell: " << ar << endl;
1776 cur.cell() = pipeThroughExtern(lang, extra, ar);
1777 // move to end of line
1778 cur.pos() = cur.lastpos();
1783 lyxerr << "use eqnarray" << endl;
1784 cur.idx() += 2 - cur.idx() % ncols();
1786 MathData ar = cur.cell();
1787 lyxerr << "use cell: " << ar << endl;
1788 // FIXME: temporarily disabled
1794 cur.cell() = pipeThroughExtern(lang, extra, ar);
1795 cur.pos() = cur.lastpos();
1800 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1802 //lyxerr << "action: " << cmd.action() << endl;
1803 switch (cmd.action()) {
1805 case LFUN_FINISHED_BACKWARD:
1806 case LFUN_FINISHED_FORWARD:
1807 case LFUN_FINISHED_RIGHT:
1808 case LFUN_FINISHED_LEFT:
1809 //lyxerr << "action: " << cmd.action() << endl;
1810 InsetMathGrid::doDispatch(cur, cmd);
1813 case LFUN_PARAGRAPH_BREAK:
1814 // just swallow this
1817 case LFUN_NEWLINE_INSERT:
1818 // some magic for the common case
1819 if (type_ == hullSimple || type_ == hullEquation) {
1820 cur.recordUndoInset();
1822 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1823 mutate(align ? hullAlign : hullEqnArray);
1824 // mutate() may change labels and such.
1825 cur.forceBufferUpdate();
1826 cur.idx() = nrows() * ncols() - 1;
1827 cur.pos() = cur.lastpos();
1829 InsetMathGrid::doDispatch(cur, cmd);
1832 case LFUN_MATH_NUMBER_TOGGLE: {
1833 //lyxerr << "toggling all numbers" << endl;
1834 cur.recordUndoInset();
1835 bool old = numberedType();
1836 if (type_ == hullMultline) {
1837 row_type row = nrows() - 1;
1838 numbered(row, !old);
1839 if (old && label_[row]) {
1844 for (row_type row = 0; row < nrows(); ++row) {
1845 numbered(row, !old);
1846 if (old && label_[row]) {
1853 cur.message(old ? _("No number") : _("Number"));
1854 cur.forceBufferUpdate();
1858 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1859 cur.recordUndoInset();
1860 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1861 bool old = numbered(r);
1862 cur.message(old ? _("No number") : _("Number"));
1864 if (old && label_[r]) {
1868 cur.forceBufferUpdate();
1872 case LFUN_LABEL_INSERT: {
1873 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1874 docstring old_label = label(r);
1875 docstring const default_label = from_ascii("eq:");
1876 if (old_label.empty())
1877 old_label = default_label;
1879 InsetCommandParams p(LABEL_CODE);
1880 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1881 string const data = InsetCommand::params2string(p);
1883 if (cmd.argument().empty())
1884 cur.bv().showDialog("label", data);
1886 FuncRequest fr(LFUN_INSET_INSERT, data);
1892 case LFUN_LABEL_COPY_AS_REFERENCE: {
1894 if (cmd.argument().empty() && &cur.inset() == this)
1895 // if there is no argument and we're inside math, we retrieve
1896 // the row number from the cursor position.
1897 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1899 // if there is an argument, find the corresponding label, else
1900 // check whether there is at least one label.
1901 for (row = 0; row != nrows(); ++row)
1903 && (cmd.argument().empty() || label(row) == cmd.argument()))
1910 InsetCommandParams p(REF_CODE, "ref");
1911 p["reference"] = label(row);
1912 cap::clearSelection();
1913 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1917 case LFUN_WORD_DELETE_FORWARD:
1918 case LFUN_CHAR_DELETE_FORWARD:
1919 if (col(cur.idx()) + 1 == ncols()
1920 && cur.pos() == cur.lastpos()
1921 && !cur.selection()) {
1922 if (!label(row(cur.idx())).empty()) {
1923 cur.recordUndoInset();
1924 label(row(cur.idx()), docstring());
1925 } else if (numbered(row(cur.idx()))) {
1926 cur.recordUndoInset();
1927 numbered(row(cur.idx()), false);
1928 cur.forceBufferUpdate();
1930 InsetMathGrid::doDispatch(cur, cmd);
1934 InsetMathGrid::doDispatch(cur, cmd);
1939 case LFUN_INSET_INSERT: {
1940 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1941 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1942 string const name = cmd.getArg(0);
1943 if (name == "label") {
1944 InsetCommandParams p(LABEL_CODE);
1945 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1946 docstring str = p["name"];
1947 cur.recordUndoInset();
1948 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1952 docstring old = label(r);
1955 // The label will take care of the reference update.
1959 // Newly created inset so initialize it.
1960 label_[r]->initView();
1963 cur.forceBufferUpdate();
1966 InsetMathGrid::doDispatch(cur, cmd);
1970 case LFUN_MATH_EXTERN:
1971 cur.recordUndoInset();
1975 case LFUN_MATH_MUTATE: {
1976 cur.recordUndoInset();
1977 row_type row = cur.row();
1978 col_type col = cur.col();
1979 mutate(hullType(cmd.argument()));
1980 cur.idx() = row * ncols() + col;
1981 if (cur.idx() > cur.lastidx()) {
1982 cur.idx() = cur.lastidx();
1983 cur.pos() = cur.lastpos();
1985 if (cur.pos() > cur.lastpos())
1986 cur.pos() = cur.lastpos();
1988 cur.forceBufferUpdate();
1989 // FIXME: find some more clever handling of the selection,
1990 // i.e. preserve it.
1991 cur.clearSelection();
1992 //cur.dispatched(FINISHED);
1996 case LFUN_MATH_DISPLAY: {
1997 cur.recordUndoInset();
1998 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1999 // if the cursor is in a cell that got merged, move it to
2000 // start of the hull inset.
2001 if (cur.idx() > 0) {
2005 if (cur.pos() > cur.lastpos())
2006 cur.pos() = cur.lastpos();
2011 case LFUN_TABULAR_FEATURE:
2012 if (!allowsTabularFeatures())
2015 InsetMathGrid::doDispatch(cur, cmd);
2019 InsetMathGrid::doDispatch(cur, cmd);
2027 bool allowDisplayMath(Cursor const & cur)
2029 LATTEST(cur.depth() > 1);
2030 Cursor tmpcur = cur;
2033 FuncRequest cmd(LFUN_MATH_DISPLAY);
2034 return tmpcur.getStatus(cmd, status) && status.enabled();
2040 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
2041 FuncStatus & status) const
2043 switch (cmd.action()) {
2044 case LFUN_FINISHED_BACKWARD:
2045 case LFUN_FINISHED_FORWARD:
2046 case LFUN_FINISHED_RIGHT:
2047 case LFUN_FINISHED_LEFT:
2050 case LFUN_NEWLINE_INSERT:
2051 case LFUN_MATH_EXTERN:
2053 status.setEnabled(true);
2056 // we never allow this in math, and we want to bind enter
2057 // to another actions in command-alternatives
2058 case LFUN_PARAGRAPH_BREAK:
2059 status.setEnabled(false);
2061 case LFUN_MATH_MUTATE: {
2062 HullType const ht = hullType(cmd.argument());
2063 status.setOnOff(type_ == ht);
2064 status.setEnabled(isMutable(ht) && isMutable(type_));
2066 if (ht != hullSimple && status.enabled())
2067 status.setEnabled(allowDisplayMath(cur));
2070 case LFUN_MATH_DISPLAY: {
2071 status.setEnabled(display() || allowDisplayMath(cur));
2072 status.setOnOff(display());
2076 case LFUN_MATH_NUMBER_TOGGLE:
2077 // FIXME: what is the right test, this or the one of
2079 status.setEnabled(display());
2080 status.setOnOff(numberedType());
2083 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
2084 // FIXME: what is the right test, this or the one of
2086 bool const enable = (type_ == hullMultline)
2087 ? (nrows() - 1 == cur.row())
2089 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2090 status.setEnabled(enable);
2091 status.setOnOff(enable && numbered(r));
2095 case LFUN_LABEL_INSERT:
2096 status.setEnabled(type_ != hullSimple);
2099 case LFUN_LABEL_COPY_AS_REFERENCE: {
2100 bool enabled = false;
2101 if (cmd.argument().empty() && &cur.inset() == this) {
2102 // if there is no argument and we're inside math, we retrieve
2103 // the row number from the cursor position.
2104 row_type row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2105 enabled = numberedType() && label_[row];
2107 // if there is an argument, find the corresponding label, else
2108 // check whether there is at least one label.
2109 for (row_type row = 0; row != nrows(); ++row) {
2111 (cmd.argument().empty() || label(row) == cmd.argument())) {
2117 status.setEnabled(enabled);
2121 case LFUN_INSET_INSERT:
2122 if (cmd.getArg(0) == "label") {
2123 status.setEnabled(type_ != hullSimple);
2126 return InsetMathGrid::getStatus(cur, cmd, status);
2128 case LFUN_TABULAR_FEATURE: {
2129 if (!allowsTabularFeatures())
2131 string s = cmd.getArg(0);
2133 && (s == "append-row"
2134 || s == "delete-row"
2135 || s == "copy-row")) {
2136 status.message(bformat(
2137 from_utf8(N_("Can't change number of rows in '%1$s'")),
2139 status.setEnabled(false);
2143 && (s == "append-column"
2144 || s == "delete-column"
2145 || s == "copy-column")) {
2146 status.message(bformat(
2147 from_utf8(N_("Can't change number of columns in '%1$s'")),
2149 status.setEnabled(false);
2152 if (s == "add-vline-left" || s == "add-vline-right") {
2153 status.message(bformat(
2154 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2156 status.setEnabled(false);
2159 if (s == "valign-top" || s == "valign-middle"
2160 || s == "valign-bottom" || s == "align-left"
2161 || s == "align-center" || s == "align-right") {
2162 status.setEnabled(false);
2165 return InsetMathGrid::getStatus(cur, cmd, status);
2169 return InsetMathGrid::getStatus(cur, cmd, status);
2174 int InsetMathHull::leftMargin() const
2176 return (getType() == hullSimple) ? 0 : InsetMathGrid::leftMargin();
2180 int InsetMathHull::rightMargin() const
2182 return (getType() == hullSimple) ? 0 : InsetMathGrid::rightMargin();
2186 int InsetMathHull::border() const
2188 return (getType() == hullSimple) ? 0 : InsetMathGrid::border();
2192 /////////////////////////////////////////////////////////////////////
2196 // simply scrap this function if you want
2197 void InsetMathHull::mutateToText()
2200 // translate to latex
2202 latex(os, false, false);
2203 string str = os.str();
2206 Text * lt = view_->cursor().innerText();
2207 string::const_iterator cit = str.begin();
2208 string::const_iterator end = str.end();
2209 for (; cit != end; ++cit)
2210 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2213 //dispatch(LFUN_ESCAPE);
2218 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2219 docstring const & font)
2221 // this whole function is a hack and won't work for incremental font
2224 if (cur.inset().asInsetMath()->name() == font)
2225 cur.handleFont(to_utf8(font));
2227 cur.handleNest(createInsetMath(font, cur.buffer()));
2233 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2238 font.fromString(to_utf8(arg), b);
2239 if (font.fontInfo().color() != Color_inherit) {
2240 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2246 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2249 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
2250 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
2251 enter_front ? idxFirst(cur) : idxLast(cur);
2252 // The inset formula dimension is not necessarily the same as the
2253 // one of the instant preview image, so we have to indicate to the
2254 // BufferView that a metrics update is needed.
2255 cur.screenUpdateFlags(Update::Force);
2259 /////////////////////////////////////////////////////////////////////
2263 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2266 // FIXME: completely broken
2267 static InsetMathHull * lastformula = 0;
2268 static CursorBase current = DocIterator(ibegin(nucleus()));
2270 static string laststr;
2272 if (lastformula != this || laststr != str) {
2273 //lyxerr << "reset lastformula to " << this << endl;
2276 current = ibegin(nucleus());
2278 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2282 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2284 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2285 CursorSlice & top = it.back();
2286 MathData const & a = top.asInsetMath()->cell(top.idx_);
2287 if (a.matchpart(ar, top.pos_)) {
2288 bv->cursor().setSelection(it, ar.size());
2290 top.pos_ += ar.size();
2296 //lyxerr << "not found!" << endl;
2303 void InsetMathHull::write(ostream & os) const
2305 odocstringstream oss;
2306 otexrowstream ots(oss);
2307 TeXMathStream wi(ots, false, false, TeXMathStream::wsDefault);
2310 os << to_utf8(oss.str());
2314 void InsetMathHull::read(Lexer & lex)
2317 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2318 operator=(*at->asHullInset());
2322 bool InsetMathHull::readQuiet(Lexer & lex)
2325 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2327 operator=(*at->asHullInset());
2332 int InsetMathHull::plaintext(odocstringstream & os,
2333 OutputParams const & op, size_t max_length) const
2335 // Try enabling this now that there is a flag as requested at #2275.
2336 if (buffer().isExporting() && display()) {
2340 TextPainter tpain(dim.width(), dim.height());
2341 drawT(tpain, 0, dim.ascent());
2343 // reset metrics cache to "real" values
2345 return tpain.textheight();
2348 odocstringstream oss;
2349 otexrowstream ots(oss);
2350 Encoding const * const enc = encodings.fromLyXName("utf8");
2352 TeXMathStream::OutputType ot;
2353 if (op.find_effective())
2354 ot = TeXMathStream::wsSearchAdv;
2356 ot = TeXMathStream::wsDefault;
2358 if (type_ == hullRegexp) {
2359 TeXMathStream wi(ots, false, true, ot, enc);
2363 TeXMathStream wi(ots, false, true, ot, enc);
2364 for (row_type r = 0; r < nrows(); ++r) {
2365 for (col_type c = 0; c < ncols(); ++c)
2366 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2367 // if it's for the TOC, we write just the first line
2368 // and do not include the newline.
2369 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2371 if (r < nrows() - 1)
2375 docstring const str = oss.str();
2381 void InsetMathHull::docbook(XMLStream & xs, OutputParams const & runparams) const {
2382 // Choose the tag around the MathML equation.
2385 if (getType() == hullSimple)
2386 name = from_ascii("inlineequation");
2388 doCR = true; // This is a block equation, always have <informalequation> on its own line.
2389 name = from_ascii("informalequation");
2392 // DocBook also has <equation>, but it comes with a title.
2393 // TODO: recognise \tag from amsmath? This would allow having <equation> with a proper title.
2397 bool mathmlNamespaceInline = buffer().params().docbook_mathml_prefix == BufferParams::NoPrefix;
2398 if (mathmlNamespaceInline)
2399 attr += "xmlns=\"http://www.w3.org/1998/Math/MathML\"";
2401 for (row_type i = 0; i < nrows(); ++i) {
2402 if (!label(i).empty()) {
2406 attr += "xml:id=\"" + xml::cleanID(label(i)) + "\"";
2412 if (!xs.isLastTagCR())
2415 xs << xml::StartTag(name, attr);
2418 // With DocBook 5, MathML must be within its own namespace (defined in Buffer.cpp::writeDocBookSource, except when
2419 // it should be inlined).
2420 // Output everything in a separate stream so that this does not interfere with the standard flow of DocBook tags.
2421 std::string mathmlNamespacePrefix;
2422 if (!mathmlNamespaceInline) {
2423 if (buffer().params().docbook_mathml_prefix == BufferParams::MPrefix)
2424 mathmlNamespacePrefix = "m";
2425 else if (buffer().params().docbook_mathml_prefix == BufferParams::MMLPrefix)
2426 mathmlNamespacePrefix = "mml";
2429 odocstringstream osmath;
2430 MathMLStream ms(osmath, mathmlNamespacePrefix);
2432 // Output the MathML subtree.
2433 // TeX transcription. Avoid MTag/ETag so that there are no extraneous spaces.
2434 ms << "<" << from_ascii("alt") << " role='tex'" << ">";
2435 // Workaround for db2latex: db2latex always includes equations with
2436 // \ensuremath{} or \begin{display}\end{display}
2437 // so we strip LyX' math environment
2438 odocstringstream ls;
2440 TeXMathStream wi(ols, false, false, TeXMathStream::wsDefault, runparams.encoding);
2441 InsetMathGrid::write(wi);
2442 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2443 ms << "</" << from_ascii("alt") << ">";
2445 // Actual transformation of the formula into MathML. This translation may fail (for example, due to custom macros).
2446 // The new output stream is required to deal with the errors: first write completely the formula into this
2447 // temporary stream; then, if it is possible without error, then copy it back to the "real" stream. Otherwise,
2448 // some incomplete tags might be put into the real stream.
2450 // First, generate the MathML expression. If there is an error in the generation, this block is not fully
2451 // executed, and the formula is not output to the DocBook stream.
2452 odocstringstream ostmp;
2453 MathMLStream mstmp(ostmp, ms.xmlns());
2456 // Choose the display style for the formula, to be output as an attribute near the formula root.
2457 std::string mathmlAttr;
2458 if (getType() == hullSimple)
2459 mathmlAttr = "display=\"inline\"";
2461 mathmlAttr = "display=\"block\"";
2463 // Then, output the formula.
2464 ms << MTag("math", mathmlAttr);
2466 osmath << ostmp.str(); // osmath is not a XMLStream, so no need for XMLStream::ESCAPE_NONE.
2468 } catch (MathExportException const &) {
2470 osmath << "<mathphrase>MathML export failed. Please report this as a bug to the LyX developers: "
2471 "https://www.lyx.org/trac.</mathphrase>";
2474 // Output the complete formula to the DocBook stream.
2475 xs << XMLStream::ESCAPE_NONE << osmath.str();
2477 xs << xml::EndTag(name);
2483 bool InsetMathHull::haveNumbers() const
2485 bool havenumbers = false;
2486 // inline formulas are never numbered (bug 7351 part 3)
2487 if (getType() == hullSimple)
2489 for (size_t i = 0; i != numbered_.size(); ++i) {
2500 // We need to do something about alignment here.
2502 // This duplicates code from InsetMathGrid, but
2503 // we need access here to number information,
2504 // and we simply do not have that in InsetMathGrid.
2505 void InsetMathHull::htmlize(HtmlStream & os) const
2507 bool const havenumbers = haveNumbers();
2508 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2511 os << cell(index(0, 0));
2515 os << MTag("table", "class='mathtable'");
2516 for (row_type row = 0; row < nrows(); ++row) {
2518 for (col_type col = 0; col < ncols(); ++col) {
2520 os << cell(index(row, col));
2525 docstring const & num = numbers_[row];
2527 os << '(' << num << ')';
2532 os << ETag("table");
2536 // this duplicates code from InsetMathGrid, but
2537 // we need access here to number information,
2538 // and we simply do not have that in InsetMathGrid.
2539 void InsetMathHull::mathmlize(MathMLStream & ms) const
2541 bool const havetable = haveNumbers() || nrows() > 1 || ncols() > 1;
2543 // Simplest case: single row, single column, no numbering.
2545 ms << cell(index(0, 0));
2549 // More complex case: wrap elements in a table.
2550 if (getType() == hullSimple) {
2551 ms << MTag("mtable");
2552 } else if (getType() >= hullAlign && getType() <= hullXXAlignAt) {
2553 // hullAlign, hullAlignAt, hullXAlignAt, hullXXAlignAt
2555 for (col_type col = 0; col < ncols(); ++col) {
2556 alignment += (col % 2) ? "left " : "right ";
2558 ms << MTag("mtable", "displaystyle='true' columnalign='" + alignment + "'");
2560 ms << MTag("mtable", "displaystyle='true'");
2563 for (row_type row = 0; row < nrows(); ++row) {
2564 // No Wed browser supports mlabeledtr in 2023, even though it has been introduced in
2565 // MathML 2 (2003). Moreover, it is not supported in MathML 4 Core.
2568 for (col_type col = 0; col < ncols(); ++col) {
2570 << cell(index(row, col))
2575 if (haveNumbers()) {
2577 docstring const & num = numbers_[row];
2579 ms << MTagInline("mtext") << '(' << num << ')' << ETagInline("mtext");
2586 ms << ETag("mtable");
2590 void InsetMathHull::mathAsLatex(TeXMathStream & os) const
2592 MathEnsurer ensurer(os, false);
2593 bool const havenumbers = haveNumbers();
2594 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2597 os << cell(index(0, 0));
2601 os << "<table class='mathtable'>";
2602 for (row_type row = 0; row < nrows(); ++row) {
2604 for (col_type col = 0; col < ncols(); ++col) {
2605 os << "<td class='math'>";
2606 os << cell(index(row, col));
2611 docstring const & num = numbers_[row];
2613 os << '(' << num << ')';
2622 docstring InsetMathHull::xhtml(XMLStream & xs, OutputParams const & op) const
2624 BufferParams::MathOutput const mathtype =
2625 buffer().masterBuffer()->params().html_math_output;
2627 bool success = false;
2629 // we output all the labels just at the beginning of the equation.
2630 // this should be fine.
2631 for (size_t i = 0; i != label_.size(); ++i) {
2632 InsetLabel const * const il = label_[i];
2638 // FIXME Eventually we would like to do this inset by inset.
2639 if (mathtype == BufferParams::MathML) {
2640 odocstringstream os;
2641 MathMLStream ms(os);
2645 } catch (MathExportException const &) {}
2647 string const name_space_declaration = "xmlns='http://www.w3.org/1998/Math/MathML'";
2648 if (getType() == hullSimple)
2649 xs << xml::StartTag("math", name_space_declaration, true);
2651 if (!xs.isLastTagCR())
2653 xs << xml::StartTag("math", name_space_declaration + " display='block'", true);
2656 xs << XMLStream::ESCAPE_NONE
2659 if (!xs.isLastTagCR())
2661 xs << xml::EndTag("math") << xml::CR();
2663 // In case of failure, generate an image.
2664 } else if (mathtype == BufferParams::HTML) {
2665 odocstringstream os;
2670 } catch (MathExportException const &) {}
2672 string const tag = (getType() == hullSimple) ? "span" : "div";
2673 xs << xml::StartTag(tag, "class='formula'", true)
2674 << XMLStream::ESCAPE_NONE
2676 << xml::EndTag(tag);
2678 // In case of failure, generate an image.
2681 // what we actually want is this:
2683 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2685 // || mathtype == BufferParams::Images
2687 // but what follows is equivalent, since we'll enter only if either (a) we
2688 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2689 // aren't doing LaTeX.
2691 // so this is for Images.
2692 if (!success && mathtype != BufferParams::LaTeX) {
2693 graphics::PreviewImage const * pimage = nullptr;
2695 loadPreview(docit_);
2696 pimage = preview_->getPreviewImage(buffer());
2697 // FIXME Do we always have png?
2700 if (pimage || op.dryrun) {
2701 string const filename = pimage ? pimage->filename().onlyFileName()
2702 : "previewimage.png";
2704 // if we are not in the master buffer, then we need to see that the
2705 // generated image is copied there; otherwise, preview fails.
2706 Buffer const * mbuf = buffer().masterBuffer();
2707 if (mbuf != &buffer()) {
2708 string mbtmp = mbuf->temppath();
2709 FileName const mbufimg(support::addName(mbtmp, filename));
2710 pimage->filename().copyTo(mbufimg);
2712 // add the file to the list of files to be exported
2713 op.exportdata->addExternalFile("xhtml", pimage->filename());
2716 string const tag = (getType() == hullSimple) ? "span" : "div";
2718 << xml::StartTag(tag, "style = \"text-align: center;\"")
2719 << xml::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2726 // so we'll pass this test if we've failed everything else, or
2727 // if mathtype was LaTeX, since we won't have entered any of the
2729 if (!success /* || mathtype != BufferParams::LaTeX */) {
2730 // Unfortunately, we cannot use latexString() because we do not want
2731 // $...$ or whatever.
2732 odocstringstream ls;
2733 otexrowstream ots(ls);
2734 TeXMathStream wi(ots, false, true, TeXMathStream::wsPreview);
2735 ModeSpecifier specifier(wi, MATH_MODE);
2737 docstring const latex = ls.str();
2739 // class='math' allows for use of jsMath
2740 // http://www.math.union.edu/~dpvc/jsMath/
2742 // probably should allow for some kind of customization here
2743 string const tag = (getType() == hullSimple) ? "span" : "div";
2744 xs << xml::StartTag(tag, "class='math'")
2753 void InsetMathHull::toString(odocstream & os) const
2755 odocstringstream ods;
2756 plaintext(ods, OutputParams(nullptr));
2761 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2763 odocstringstream ods;
2764 OutputParams op(nullptr);
2766 // FIXME: this results in spilling TeX into the LyXHTML output since the
2767 // outliner is used to generate the LyXHTML list of figures/etc.
2773 string InsetMathHull::contextMenuName() const
2775 return "context-math";
2779 void InsetMathHull::recordLocation(DocIterator const & di)
2785 bool InsetMathHull::canPaintChange(BufferView const &) const
2787 // We let RowPainter do it seamlessly for inline insets