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 = 0;
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 // FIXME This should really be controlled by the TOC level, or
232 // something of the sort.
234 const char * counters_to_save[] = {"section", "chapter"};
235 unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
239 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
242 //FIXME: buffer_ should be set at creation for this inset! Problem is
243 // This inset is created at too many places (see Parser::parse1() in
248 // if any of the equations are numbered, then we want to save the values
249 // of some of the counters.
251 BufferParams const & bp = buffer_->params();
252 string const & lang = it->getParLanguage(bp)->code();
254 buffer_->masterBuffer()->params().documentClass().counters();
256 // this has to be done separately
257 docstring const eqstr = from_ascii("equation");
258 if (cnts.hasCounter(eqstr)) {
259 for (size_t i = 0; i != label_.size(); ++i) {
260 docstring const oldnumber = numbers_[i];
262 Paragraph const & par = it.paragraph();
263 if (!par.isDeleted(it.pos())) {
264 cnts.step(eqstr, utype);
265 numbers_[i] = cnts.theCounter(eqstr, lang);
267 numbers_[i] = from_ascii("#");
269 numbers_[i] = empty_docstring();
270 // If the numbering has changed, trigger a new preview
271 if (oldnumber != numbers_[i] && RenderPreview::previewMath()) {
272 // Do we need to remove it first?
273 //preview_->removePreview(*buffer_);
281 for (size_t i = 0; i != label_.size(); ++i) {
283 label_[i]->updateBuffer(it, utype, deleted);
286 InsetMathGrid::updateBuffer(it, utype, deleted);
290 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active,
291 UpdateType utype, TocBackend & backend) const
294 //FIXME: buffer_ should be set at creation for this inset! Problem is
295 // This inset is created at too many places (see Parser::parse1() in
300 TocBuilder & b = backend.builder("equation");
301 // compute first and last item
302 row_type first = nrows();
303 for (row_type row = 0; row != nrows(); ++row)
308 if (first == nrows())
311 row_type last = nrows() - 1;
312 for (; last != 0; --last)
315 // add equation numbers
316 b.pushItem(pit, docstring(), output_active);
318 b.argumentItem(bformat(from_ascii("(%1$s-%2$s)"),
319 numbers_[first], numbers_[last]));
320 for (row_type row = 0; row != nrows(); ++row) {
324 label_[row]->addToToc(pit, output_active, utype, backend);
325 docstring label = nicelabel(row);
327 // this is the only equation
328 b.argumentItem(label);
330 // insert as sub-items
331 b.pushItem(pit, label, output_active);
339 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
341 if (previewState(&cur.bv())) {
345 return InsetMathNest::editXY(cur, x, y);
349 InsetMath::mode_type InsetMathHull::currentMode() const
353 return UNDECIDED_MODE;
355 // definitely math mode ...
375 // FIXME: InsetMathGrid should be changed to let the real column alignment be
376 // given by a virtual method like displayColAlign, because the values produced
377 // by defaultColAlign can be invalidated by lfuns such as add-column. For the
378 // moment the values produced by defaultColAlign are not used, notably because
379 // alignment is not implemented in the LyXHTML output.
380 char InsetMathHull::defaultColAlign(col_type col)
382 return colAlign(type_, col);
386 char InsetMathHull::displayColAlign(idx_type idx) const
390 row_type const r = row(idx);
393 if (r == nrows() - 1)
404 return colAlign(type_, col(idx));
408 return InsetMathGrid::displayColAlign(idx);
412 int InsetMathHull::displayColSpace(col_type col) const
414 return colSpace(type_, col);
418 // FIXME: same comment as for defaultColAlign applies.
419 int InsetMathHull::defaultColSpace(col_type col)
421 return colSpace(type_, col);
425 string InsetMathHull::standardFont() const
431 return "lyxnochange";
438 ColorCode InsetMathHull::standardColor() const
443 return Color_foreground;
451 bool InsetMathHull::previewState(const BufferView *const bv) const
453 if (!editing(bv) && RenderPreview::previewMath()
454 && type_ != hullRegexp)
456 graphics::PreviewImage const * pimage =
457 preview_->getPreviewImage(bv->buffer());
458 return pimage && pimage->image();
465 const int ERROR_FRAME_WIDTH = 2;
467 bool previewTooSmall(Dimension const & dim)
469 return dim.width() <= 10 && dim.height() <= 10;
474 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
476 /* Compute \(above|below)displayskip
477 true value in LaTeX is 10pt plus 2pt minus 5pt (in normal size at 10pt)
478 But we use a fixed number of pixels and scale them with zoom.
480 int const bottom_display_margin = mi.base.bv->zoomedPixels(6);
481 int top_display_margin = bottom_display_margin;
482 // at start of paragraph, add an empty line
484 top_display_margin += theFontMetrics(mi.base.font).maxHeight() + 2;
486 if (previewState(mi.base.bv)) {
487 preview_->metrics(mi, dim);
488 if (previewTooSmall(dim)) {
489 // preview image is too small
490 dim.wid += 2 * ERROR_FRAME_WIDTH;
491 dim.asc += 2 * ERROR_FRAME_WIDTH;
493 // insert a gap in front of the formula
494 // value was hardcoded to 1 pixel
495 dim.wid += mi.base.bv->zoomedPixels(1) ;
497 dim.asc += top_display_margin;
498 dim.des += bottom_display_margin;
505 Changer dummy1 = mi.base.changeFontSet(standardFont());
506 Changer dummy2 = mi.base.font.changeStyle(display() ? DISPLAY_STYLE
509 // let the cells adjust themselves
510 InsetMathGrid::metrics(mi, dim);
513 // Check whether the numbering interferes with the equations
514 if (numberedType()) {
515 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
516 int extra_offset = 0;
517 for (row_type row = 0; row < nrows(); ++row) {
518 rowinfo(row).offset[mi.base.bv] += extra_offset;
519 docstring const nl = nicelabel(row);
523 mathed_string_dim(mi.base.font, nl, dimnl);
524 int const ind = indent(*mi.base.bv);
525 int const x = ind ? ind : (mi.base.textwidth - dim.wid) / 2;
526 // for some reason metrics does not trigger at the
527 // same point as draw, and therefore we use >= instead of >
528 if ((math_number == BufferParams::LEFT && dimnl.wid >= x)
529 || (math_number == BufferParams::RIGHT
530 && dimnl.wid >= mi.base.textwidth - x - dim.wid)) {
531 extra_offset += dimnl.height();
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 = 0;
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 = 0;
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 numbered(nrows() - 1, !old);
1839 for (row_type row = 0; row < nrows(); ++row)
1840 numbered(row, !old);
1842 cur.message(old ? _("No number") : _("Number"));
1843 cur.forceBufferUpdate();
1847 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1848 cur.recordUndoInset();
1849 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1850 bool old = numbered(r);
1851 cur.message(old ? _("No number") : _("Number"));
1853 cur.forceBufferUpdate();
1857 case LFUN_LABEL_INSERT: {
1858 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1859 docstring old_label = label(r);
1860 docstring const default_label = from_ascii("eq:");
1861 if (old_label.empty())
1862 old_label = default_label;
1864 InsetCommandParams p(LABEL_CODE);
1865 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1866 string const data = InsetCommand::params2string(p);
1868 if (cmd.argument().empty())
1869 cur.bv().showDialog("label", data);
1871 FuncRequest fr(LFUN_INSET_INSERT, data);
1877 case LFUN_LABEL_COPY_AS_REFERENCE: {
1879 if (cmd.argument().empty() && &cur.inset() == this)
1880 // if there is no argument and we're inside math, we retrieve
1881 // the row number from the cursor position.
1882 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1884 // if there is an argument, find the corresponding label, else
1885 // check whether there is at least one label.
1886 for (row = 0; row != nrows(); ++row)
1888 && (cmd.argument().empty() || label(row) == cmd.argument()))
1895 InsetCommandParams p(REF_CODE, "ref");
1896 p["reference"] = label(row);
1897 cap::clearSelection();
1898 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1902 case LFUN_WORD_DELETE_FORWARD:
1903 case LFUN_CHAR_DELETE_FORWARD:
1904 if (col(cur.idx()) + 1 == ncols()
1905 && cur.pos() == cur.lastpos()
1906 && !cur.selection()) {
1907 if (!label(row(cur.idx())).empty()) {
1908 cur.recordUndoInset();
1909 label(row(cur.idx()), docstring());
1910 } else if (numbered(row(cur.idx()))) {
1911 cur.recordUndoInset();
1912 numbered(row(cur.idx()), false);
1913 cur.forceBufferUpdate();
1915 InsetMathGrid::doDispatch(cur, cmd);
1919 InsetMathGrid::doDispatch(cur, cmd);
1924 case LFUN_INSET_INSERT: {
1925 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1926 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1927 string const name = cmd.getArg(0);
1928 if (name == "label") {
1929 InsetCommandParams p(LABEL_CODE);
1930 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1931 docstring str = p["name"];
1932 cur.recordUndoInset();
1933 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1937 docstring old = label(r);
1940 // The label will take care of the reference update.
1944 // Newly created inset so initialize it.
1945 label_[r]->initView();
1948 cur.forceBufferUpdate();
1951 InsetMathGrid::doDispatch(cur, cmd);
1955 case LFUN_MATH_EXTERN:
1956 cur.recordUndoInset();
1960 case LFUN_MATH_MUTATE: {
1961 cur.recordUndoInset();
1962 row_type row = cur.row();
1963 col_type col = cur.col();
1964 mutate(hullType(cmd.argument()));
1965 cur.idx() = row * ncols() + col;
1966 if (cur.idx() > cur.lastidx()) {
1967 cur.idx() = cur.lastidx();
1968 cur.pos() = cur.lastpos();
1970 if (cur.pos() > cur.lastpos())
1971 cur.pos() = cur.lastpos();
1973 cur.forceBufferUpdate();
1974 // FIXME: find some more clever handling of the selection,
1975 // i.e. preserve it.
1976 cur.clearSelection();
1977 //cur.dispatched(FINISHED);
1981 case LFUN_MATH_DISPLAY: {
1982 cur.recordUndoInset();
1983 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1984 // if the cursor is in a cell that got merged, move it to
1985 // start of the hull inset.
1986 if (cur.idx() > 0) {
1990 if (cur.pos() > cur.lastpos())
1991 cur.pos() = cur.lastpos();
1996 case LFUN_TABULAR_FEATURE:
1997 if (!allowsTabularFeatures())
2000 InsetMathGrid::doDispatch(cur, cmd);
2004 InsetMathGrid::doDispatch(cur, cmd);
2012 bool allowDisplayMath(Cursor const & cur)
2014 LATTEST(cur.depth() > 1);
2015 Cursor tmpcur = cur;
2018 FuncRequest cmd(LFUN_MATH_DISPLAY);
2019 return tmpcur.getStatus(cmd, status) && status.enabled();
2025 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
2026 FuncStatus & status) const
2028 switch (cmd.action()) {
2029 case LFUN_FINISHED_BACKWARD:
2030 case LFUN_FINISHED_FORWARD:
2031 case LFUN_FINISHED_RIGHT:
2032 case LFUN_FINISHED_LEFT:
2035 case LFUN_NEWLINE_INSERT:
2036 case LFUN_MATH_EXTERN:
2038 status.setEnabled(true);
2041 // we never allow this in math, and we want to bind enter
2042 // to another actions in command-alternatives
2043 case LFUN_PARAGRAPH_BREAK:
2044 status.setEnabled(false);
2046 case LFUN_MATH_MUTATE: {
2047 HullType const ht = hullType(cmd.argument());
2048 status.setOnOff(type_ == ht);
2049 status.setEnabled(isMutable(ht) && isMutable(type_));
2051 if (ht != hullSimple && status.enabled())
2052 status.setEnabled(allowDisplayMath(cur));
2055 case LFUN_MATH_DISPLAY: {
2056 status.setEnabled(display() || allowDisplayMath(cur));
2057 status.setOnOff(display());
2061 case LFUN_MATH_NUMBER_TOGGLE:
2062 // FIXME: what is the right test, this or the one of
2064 status.setEnabled(display());
2065 status.setOnOff(numberedType());
2068 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
2069 // FIXME: what is the right test, this or the one of
2071 bool const enable = (type_ == hullMultline)
2072 ? (nrows() - 1 == cur.row())
2074 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2075 status.setEnabled(enable);
2076 status.setOnOff(enable && numbered(r));
2080 case LFUN_LABEL_INSERT:
2081 status.setEnabled(type_ != hullSimple);
2084 case LFUN_LABEL_COPY_AS_REFERENCE: {
2085 bool enabled = false;
2086 if (cmd.argument().empty() && &cur.inset() == this) {
2087 // if there is no argument and we're inside math, we retrieve
2088 // the row number from the cursor position.
2089 row_type row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2090 enabled = numberedType() && label_[row];
2092 // if there is an argument, find the corresponding label, else
2093 // check whether there is at least one label.
2094 for (row_type row = 0; row != nrows(); ++row) {
2096 (cmd.argument().empty() || label(row) == cmd.argument())) {
2102 status.setEnabled(enabled);
2106 case LFUN_INSET_INSERT:
2107 if (cmd.getArg(0) == "label") {
2108 status.setEnabled(type_ != hullSimple);
2111 return InsetMathGrid::getStatus(cur, cmd, status);
2113 case LFUN_TABULAR_FEATURE: {
2114 if (!allowsTabularFeatures())
2116 string s = cmd.getArg(0);
2118 && (s == "append-row"
2119 || s == "delete-row"
2120 || s == "copy-row")) {
2121 status.message(bformat(
2122 from_utf8(N_("Can't change number of rows in '%1$s'")),
2124 status.setEnabled(false);
2128 && (s == "append-column"
2129 || s == "delete-column"
2130 || s == "copy-column")) {
2131 status.message(bformat(
2132 from_utf8(N_("Can't change number of columns in '%1$s'")),
2134 status.setEnabled(false);
2137 if (s == "add-vline-left" || s == "add-vline-right") {
2138 status.message(bformat(
2139 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2141 status.setEnabled(false);
2144 if (s == "valign-top" || s == "valign-middle"
2145 || s == "valign-bottom" || s == "align-left"
2146 || s == "align-center" || s == "align-right") {
2147 status.setEnabled(false);
2150 return InsetMathGrid::getStatus(cur, cmd, status);
2154 return InsetMathGrid::getStatus(cur, cmd, status);
2159 int InsetMathHull::leftMargin() const
2161 return (getType() == hullSimple) ? 0 : InsetMathGrid::leftMargin();
2165 int InsetMathHull::rightMargin() const
2167 return (getType() == hullSimple) ? 0 : InsetMathGrid::rightMargin();
2171 int InsetMathHull::border() const
2173 return (getType() == hullSimple) ? 0 : InsetMathGrid::border();
2177 /////////////////////////////////////////////////////////////////////
2181 // simply scrap this function if you want
2182 void InsetMathHull::mutateToText()
2185 // translate to latex
2187 latex(os, false, false);
2188 string str = os.str();
2191 Text * lt = view_->cursor().innerText();
2192 string::const_iterator cit = str.begin();
2193 string::const_iterator end = str.end();
2194 for (; cit != end; ++cit)
2195 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2198 //dispatch(LFUN_ESCAPE);
2203 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2204 docstring const & font)
2206 // this whole function is a hack and won't work for incremental font
2209 if (cur.inset().asInsetMath()->name() == font)
2210 cur.handleFont(to_utf8(font));
2212 cur.handleNest(createInsetMath(font, cur.buffer()));
2218 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2223 font.fromString(to_utf8(arg), b);
2224 if (font.fontInfo().color() != Color_inherit) {
2225 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2231 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2234 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
2235 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
2236 enter_front ? idxFirst(cur) : idxLast(cur);
2237 // The inset formula dimension is not necessarily the same as the
2238 // one of the instant preview image, so we have to indicate to the
2239 // BufferView that a metrics update is needed.
2240 cur.screenUpdateFlags(Update::Force);
2244 /////////////////////////////////////////////////////////////////////
2248 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2251 // FIXME: completely broken
2252 static InsetMathHull * lastformula = 0;
2253 static CursorBase current = DocIterator(ibegin(nucleus()));
2255 static string laststr;
2257 if (lastformula != this || laststr != str) {
2258 //lyxerr << "reset lastformula to " << this << endl;
2261 current = ibegin(nucleus());
2263 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2267 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2269 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2270 CursorSlice & top = it.back();
2271 MathData const & a = top.asInsetMath()->cell(top.idx_);
2272 if (a.matchpart(ar, top.pos_)) {
2273 bv->cursor().setSelection(it, ar.size());
2275 top.pos_ += ar.size();
2281 //lyxerr << "not found!" << endl;
2288 void InsetMathHull::write(ostream & os) const
2290 odocstringstream oss;
2291 otexrowstream ots(oss);
2292 TeXMathStream wi(ots, false, false, TeXMathStream::wsDefault);
2295 os << to_utf8(oss.str());
2299 void InsetMathHull::read(Lexer & lex)
2302 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2303 operator=(*at->asHullInset());
2307 bool InsetMathHull::readQuiet(Lexer & lex)
2310 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2312 operator=(*at->asHullInset());
2317 int InsetMathHull::plaintext(odocstringstream & os,
2318 OutputParams const & op, size_t max_length) const
2320 // Try enabling this now that there is a flag as requested at #2275.
2321 if (buffer().isExporting() && display()) {
2325 TextPainter tpain(dim.width(), dim.height());
2326 drawT(tpain, 0, dim.ascent());
2328 // reset metrics cache to "real" values
2330 return tpain.textheight();
2333 odocstringstream oss;
2334 otexrowstream ots(oss);
2335 Encoding const * const enc = encodings.fromLyXName("utf8");
2337 TeXMathStream::OutputType ot;
2338 if (op.find_effective())
2339 ot = TeXMathStream::wsSearchAdv;
2341 ot = TeXMathStream::wsDefault;
2343 if (type_ == hullRegexp) {
2344 TeXMathStream wi(ots, false, true, ot, enc);
2348 TeXMathStream wi(ots, false, true, ot, enc);
2349 for (row_type r = 0; r < nrows(); ++r) {
2350 for (col_type c = 0; c < ncols(); ++c)
2351 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2352 // if it's for the TOC, we write just the first line
2353 // and do not include the newline.
2354 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2356 if (r < nrows() - 1)
2360 docstring const str = oss.str();
2366 void InsetMathHull::docbook(XMLStream & xs, OutputParams const & runparams) const {
2367 // Choose the tag around the MathML equation.
2370 if (getType() == hullSimple)
2371 name = from_ascii("inlineequation");
2373 doCR = true; // This is a block equation, always have <informalequation> on its own line.
2374 name = from_ascii("informalequation");
2377 // DocBook also has <equation>, but it comes with a title.
2378 // TODO: recognise \tag from amsmath? This would allow having <equation> with a proper title.
2382 bool mathmlNamespaceInline = buffer().params().docbook_mathml_prefix == BufferParams::NoPrefix;
2383 if (mathmlNamespaceInline)
2384 attr += "xmlns=\"http://www.w3.org/1998/Math/MathML\"";
2386 for (row_type i = 0; i < nrows(); ++i) {
2387 if (!label(i).empty()) {
2391 attr += "xml:id=\"" + xml::cleanID(label(i)) + "\"";
2397 if (!xs.isLastTagCR())
2400 xs << xml::StartTag(name, attr);
2403 // With DocBook 5, MathML must be within its own namespace (defined in Buffer.cpp::writeDocBookSource, except when
2404 // it should be inlined).
2405 // Output everything in a separate stream so that this does not interfere with the standard flow of DocBook tags.
2406 std::string mathmlNamespacePrefix;
2407 if (!mathmlNamespaceInline) {
2408 if (buffer().params().docbook_mathml_prefix == BufferParams::MPrefix)
2409 mathmlNamespacePrefix = "m";
2410 else if (buffer().params().docbook_mathml_prefix == BufferParams::MMLPrefix)
2411 mathmlNamespacePrefix = "mml";
2414 odocstringstream osmath;
2415 MathMLStream ms(osmath, mathmlNamespacePrefix, true);
2417 // Output the MathML subtree.
2418 // TeX transcription. Avoid MTag/ETag so that there are no extraneous spaces.
2419 ms << "<" << from_ascii("alt") << " role='tex'" << ">";
2420 // Workaround for db2latex: db2latex always includes equations with
2421 // \ensuremath{} or \begin{display}\end{display}
2422 // so we strip LyX' math environment
2423 odocstringstream ls;
2425 TeXMathStream wi(ols, false, false, TeXMathStream::wsDefault, runparams.encoding);
2426 InsetMathGrid::write(wi);
2427 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2428 ms << "</" << from_ascii("alt") << ">";
2430 // Actual transformation of the formula into MathML. This translation may fail (for example, due to custom macros).
2431 // The new output stream is required to deal with the errors: first write completely the formula into this
2432 // temporary stream; then, if it is possible without error, then copy it back to the "real" stream. Otherwise,
2433 // some incomplete tags might be put into the real stream.
2435 // First, generate the MathML expression. If there is an error in the generation, this block is not fully
2436 // executed, and the formula is not output to the DocBook stream.
2437 odocstringstream ostmp;
2438 MathMLStream mstmp(ostmp, ms.xmlns(), ms.xmlMode());
2441 // Choose the display style for the formula, to be output as an attribute near the formula root.
2442 std::string mathmlAttr;
2443 if (getType() == hullSimple)
2444 mathmlAttr = "display=\"inline\"";
2446 mathmlAttr = "display=\"block\"";
2448 // Then, output the formula.
2449 ms << MTag("math", mathmlAttr);
2451 osmath << ostmp.str(); // osmath is not a XMLStream, so no need for XMLStream::ESCAPE_NONE.
2453 } catch (MathExportException const &) {
2455 osmath << "<mathphrase>MathML export failed. Please report this as a bug to the LyX developers: "
2456 "https://www.lyx.org/trac.</mathphrase>";
2459 // Output the complete formula to the DocBook stream.
2460 xs << XMLStream::ESCAPE_NONE << osmath.str();
2462 xs << xml::EndTag(name);
2468 bool InsetMathHull::haveNumbers() const
2470 bool havenumbers = false;
2471 // inline formulas are never numbered (bug 7351 part 3)
2472 if (getType() == hullSimple)
2474 for (size_t i = 0; i != numbered_.size(); ++i) {
2485 // We need to do something about alignment here.
2487 // This duplicates code from InsetMathGrid, but
2488 // we need access here to number information,
2489 // and we simply do not have that in InsetMathGrid.
2490 void InsetMathHull::htmlize(HtmlStream & os) const
2492 bool const havenumbers = haveNumbers();
2493 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2496 os << cell(index(0, 0));
2500 os << MTag("table", "class='mathtable'");
2501 for (row_type row = 0; row < nrows(); ++row) {
2503 for (col_type col = 0; col < ncols(); ++col) {
2505 os << cell(index(row, col));
2510 docstring const & num = numbers_[row];
2512 os << '(' << num << ')';
2517 os << ETag("table");
2521 // this duplicates code from InsetMathGrid, but
2522 // we need access here to number information,
2523 // and we simply do not have that in InsetMathGrid.
2524 void InsetMathHull::mathmlize(MathMLStream & ms) const
2526 bool const havetable = haveNumbers() || nrows() > 1 || ncols() > 1;
2529 if (getType() == hullSimple) {
2530 ms << MTag("mtable");
2531 } else if (getType() >= hullAlign && getType() <= hullXXAlignAt) {
2533 for (col_type col = 0; col < ncols(); ++col) {
2534 alignment += (col % 2) ? "left " : "right ";
2536 ms << MTag("mtable", "displaystyle='true' columnalign='" + alignment + "'");
2538 ms << MTag("mtable", "displaystyle='true'");
2542 char const * const celltag = havetable ? "mtd" : "mrow";
2543 // FIXME There does not seem to be wide support at the moment
2544 // for mlabeledtr, so we have to use just mtr for now.
2545 // char const * const rowtag = haveNumbers() ? "mlabeledtr" : "mtr";
2546 char const * const rowtag = "mtr";
2547 for (row_type row = 0; row < nrows(); ++row) {
2550 for (col_type col = 0; col < ncols(); ++col) {
2552 << cell(index(row, col))
2556 if (haveNumbers()) {
2558 docstring const & num = numbers_[row];
2560 ms << MTagInline("mtext") << '(' << num << ')' << ETagInline("mtext");
2567 ms << ETag("mtable");
2571 void InsetMathHull::mathAsLatex(TeXMathStream & os) const
2573 MathEnsurer ensurer(os, false);
2574 bool havenumbers = haveNumbers();
2575 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2578 os << cell(index(0, 0));
2582 os << "<table class='mathtable'>";
2583 for (row_type row = 0; row < nrows(); ++row) {
2585 for (col_type col = 0; col < ncols(); ++col) {
2586 os << "<td class='math'>";
2587 os << cell(index(row, col));
2592 docstring const & num = numbers_[row];
2594 os << '(' << num << ')';
2603 docstring InsetMathHull::xhtml(XMLStream & xs, OutputParams const & op) const
2605 BufferParams::MathOutput const mathtype =
2606 buffer().masterBuffer()->params().html_math_output;
2608 bool success = false;
2610 // we output all the labels just at the beginning of the equation.
2611 // this should be fine.
2612 for (size_t i = 0; i != label_.size(); ++i) {
2613 InsetLabel const * const il = label_[i];
2619 // FIXME Eventually we would like to do this inset by inset.
2620 if (mathtype == BufferParams::MathML) {
2621 odocstringstream os;
2622 MathMLStream ms(os);
2626 } catch (MathExportException const &) {}
2628 if (getType() == hullSimple)
2629 xs << xml::StartTag("math",
2630 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2632 xs << xml::StartTag("math",
2633 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2634 xs << XMLStream::ESCAPE_NONE
2636 << xml::EndTag("math");
2638 } else if (mathtype == BufferParams::HTML) {
2639 odocstringstream os;
2644 } catch (MathExportException const &) {}
2646 string const tag = (getType() == hullSimple) ? "span" : "div";
2647 xs << xml::StartTag(tag, "class='formula'", true)
2648 << XMLStream::ESCAPE_NONE
2650 << xml::EndTag(tag);
2654 // what we actually want is this:
2656 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2658 // || mathtype == BufferParams::Images
2660 // but what follows is equivalent, since we'll enter only if either (a) we
2661 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2662 // aren't doing LaTeX.
2664 // so this is for Images.
2665 if (!success && mathtype != BufferParams::LaTeX) {
2666 graphics::PreviewImage const * pimage = 0;
2668 loadPreview(docit_);
2669 pimage = preview_->getPreviewImage(buffer());
2670 // FIXME Do we always have png?
2673 if (pimage || op.dryrun) {
2674 string const filename = pimage ? pimage->filename().onlyFileName()
2675 : "previewimage.png";
2677 // if we are not in the master buffer, then we need to see that the
2678 // generated image is copied there; otherwise, preview fails.
2679 Buffer const * mbuf = buffer().masterBuffer();
2680 if (mbuf != &buffer()) {
2681 string mbtmp = mbuf->temppath();
2682 FileName const mbufimg(support::addName(mbtmp, filename));
2683 pimage->filename().copyTo(mbufimg);
2685 // add the file to the list of files to be exported
2686 op.exportdata->addExternalFile("xhtml", pimage->filename());
2689 string const tag = (getType() == hullSimple) ? "span" : "div";
2691 << xml::StartTag(tag, "style = \"text-align: center;\"")
2692 << xml::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2699 // so we'll pass this test if we've failed everything else, or
2700 // if mathtype was LaTeX, since we won't have entered any of the
2702 if (!success /* || mathtype != BufferParams::LaTeX */) {
2703 // Unfortunately, we cannot use latexString() because we do not want
2704 // $...$ or whatever.
2705 odocstringstream ls;
2706 otexrowstream ots(ls);
2707 TeXMathStream wi(ots, false, true, TeXMathStream::wsPreview);
2708 ModeSpecifier specifier(wi, MATH_MODE);
2710 docstring const latex = ls.str();
2712 // class='math' allows for use of jsMath
2713 // http://www.math.union.edu/~dpvc/jsMath/
2715 // probably should allow for some kind of customization here
2716 string const tag = (getType() == hullSimple) ? "span" : "div";
2717 xs << xml::StartTag(tag, "class='math'")
2726 void InsetMathHull::toString(odocstream & os) const
2728 odocstringstream ods;
2729 plaintext(ods, OutputParams(0));
2734 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2736 odocstringstream ods;
2739 // FIXME: this results in spilling TeX into the LyXHTML output since the
2740 // outliner is used to generate the LyXHTML list of figures/etc.
2746 string InsetMathHull::contextMenuName() const
2748 return "context-math";
2752 void InsetMathHull::recordLocation(DocIterator const & di)
2758 bool InsetMathHull::canPaintChange(BufferView const &) const
2760 // We let RowPainter do it seamlessly for inline insets