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) {
261 Paragraph const & par = it.paragraph();
262 if (!par.isDeleted(it.pos())) {
263 cnts.step(eqstr, utype);
264 numbers_[i] = cnts.theCounter(eqstr, lang);
266 numbers_[i] = from_ascii("#");
268 numbers_[i] = empty_docstring();
274 for (size_t i = 0; i != label_.size(); ++i) {
276 label_[i]->updateBuffer(it, utype, deleted);
279 InsetMathGrid::updateBuffer(it, utype, deleted);
283 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active,
284 UpdateType utype, TocBackend & backend) const
287 //FIXME: buffer_ should be set at creation for this inset! Problem is
288 // This inset is created at too many places (see Parser::parse1() in
293 TocBuilder & b = backend.builder("equation");
294 // compute first and last item
295 row_type first = nrows();
296 for (row_type row = 0; row != nrows(); ++row)
301 if (first == nrows())
304 row_type last = nrows() - 1;
305 for (; last != 0; --last)
308 // add equation numbers
309 b.pushItem(pit, docstring(), output_active);
311 b.argumentItem(bformat(from_ascii("(%1$s-%2$s)"),
312 numbers_[first], numbers_[last]));
313 for (row_type row = 0; row != nrows(); ++row) {
317 label_[row]->addToToc(pit, output_active, utype, backend);
318 docstring label = nicelabel(row);
320 // this is the only equation
321 b.argumentItem(label);
323 // insert as sub-items
324 b.pushItem(pit, label, output_active);
332 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
334 if (previewState(&cur.bv())) {
338 return InsetMathNest::editXY(cur, x, y);
342 InsetMath::mode_type InsetMathHull::currentMode() const
346 return UNDECIDED_MODE;
348 // definitely math mode ...
368 // FIXME: InsetMathGrid should be changed to let the real column alignment be
369 // given by a virtual method like displayColAlign, because the values produced
370 // by defaultColAlign can be invalidated by lfuns such as add-column. For the
371 // moment the values produced by defaultColAlign are not used, notably because
372 // alignment is not implemented in the LyXHTML output.
373 char InsetMathHull::defaultColAlign(col_type col)
375 return colAlign(type_, col);
379 char InsetMathHull::displayColAlign(idx_type idx) const
383 row_type const r = row(idx);
386 if (r == nrows() - 1)
397 return colAlign(type_, col(idx));
401 return InsetMathGrid::displayColAlign(idx);
405 int InsetMathHull::displayColSpace(col_type col) const
407 return colSpace(type_, col);
411 // FIXME: same comment as for defaultColAlign applies.
412 int InsetMathHull::defaultColSpace(col_type col)
414 return colSpace(type_, col);
418 string InsetMathHull::standardFont() const
424 return "lyxnochange";
431 ColorCode InsetMathHull::standardColor() const
436 return Color_foreground;
444 bool InsetMathHull::previewState(const BufferView *const bv) const
446 if (!editing(bv) && RenderPreview::previewMath()
447 && type_ != hullRegexp)
449 graphics::PreviewImage const * pimage =
450 preview_->getPreviewImage(bv->buffer());
451 return pimage && pimage->image();
458 const int ERROR_FRAME_WIDTH = 2;
460 bool previewTooSmall(Dimension const & dim)
462 return dim.width() <= 10 && dim.height() <= 10;
467 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
469 /* Compute \(above|below)displayskip
470 true value in LaTeX is 10pt plus 2pt minus 5pt (in normal size at 10pt)
471 But we use a fixed number of pixels and scale them with zoom.
473 int const bottom_display_margin = mi.base.bv->zoomedPixels(6);
474 int top_display_margin = bottom_display_margin;
475 // at start of paragraph, add an empty line
477 top_display_margin += theFontMetrics(mi.base.font).maxHeight() + 2;
479 if (previewState(mi.base.bv)) {
480 preview_->metrics(mi, dim);
481 if (previewTooSmall(dim)) {
482 // preview image is too small
483 dim.wid += 2 * ERROR_FRAME_WIDTH;
484 dim.asc += 2 * ERROR_FRAME_WIDTH;
486 // insert a gap in front of the formula
487 // value was hardcoded to 1 pixel
488 dim.wid += mi.base.bv->zoomedPixels(1) ;
490 dim.asc += top_display_margin;
491 dim.des += bottom_display_margin;
498 Changer dummy1 = mi.base.changeFontSet(standardFont());
499 Changer dummy2 = mi.base.font.changeStyle(display() ? DISPLAY_STYLE
502 // let the cells adjust themselves
503 InsetMathGrid::metrics(mi, dim);
506 // Check whether the numbering interferes with the equations
507 if (numberedType()) {
508 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
509 int extra_offset = 0;
510 for (row_type row = 0; row < nrows(); ++row) {
511 rowinfo(row).offset[mi.base.bv] += extra_offset;
512 docstring const nl = nicelabel(row);
516 mathed_string_dim(mi.base.font, nl, dimnl);
517 int const ind = indent(*mi.base.bv);
518 int const x = ind ? ind : (mi.base.textwidth - dim.wid) / 2;
519 // for some reason metrics does not trigger at the
520 // same point as draw, and therefore we use >= instead of >
521 if ((math_number == BufferParams::LEFT && dimnl.wid >= x)
522 || (math_number == BufferParams::RIGHT
523 && dimnl.wid >= mi.base.textwidth - x - dim.wid)) {
524 extra_offset += dimnl.height();
527 dim.des += extra_offset;
532 dim.asc += top_display_margin;
533 dim.des += bottom_display_margin;
536 // reserve some space for marker.
541 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
543 BufferView const * const bv = pi.base.bv;
544 if (previewState(bv)) {
545 Dimension const dim = dimension(*pi.base.bv);
546 if (previewTooSmall(dim))
548 return graphics::PreviewLoader::backgroundColor();
554 void InsetMathHull::drawMarkers(PainterInfo & pi, int x, int y) const
556 ColorCode pen_color = mouseHovered(pi.base.bv) || editing(pi.base.bv)?
557 Color_mathframe : Color_mathcorners;
558 // If the corners have the same color as the background, do not paint them.
559 if (lcolor.getX11HexName(Color_mathbg) == lcolor.getX11HexName(pen_color))
562 Inset::drawMarkers(pi, x, y);
563 Dimension const dim = dimension(*pi.base.bv);
564 int const t = x + dim.width() - 1;
565 int const a = y - dim.ascent();
566 pi.pain.line(x, a + 3, x, a, pen_color);
567 pi.pain.line(t, a + 3, t, a, pen_color);
568 pi.pain.line(x, a, x + 3, a, pen_color);
569 pi.pain.line(t - 3, a, t, a, pen_color);
573 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
575 Dimension const dim = dimension(*pi.base.bv);
576 if (previewTooSmall(dim)) {
577 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
578 dim.wid, dim.asc + dim.des, backgroundColor(pi));
582 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
583 dim.height() - 1, pi.backgroundColor(this));
587 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
589 BufferView const * const bv = pi.base.bv;
590 Dimension const dim = dimension(*bv);
592 if (type_ == hullRegexp)
593 pi.pain.rectangle(x + 2, y - dim.ascent() + 1,
594 dim.width() - 3, dim.height() - 2, Color_regexpframe);
596 if (previewState(bv)) {
597 // Do not draw change tracking cue if taken care of by RowPainter
599 Changer dummy = !canPaintChange(*bv) ? changeVar(pi.change, Change())
601 if (previewTooSmall(dim)) {
602 // we have an extra frame
603 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
605 // one pixel gap in front
606 // value was hardcoded to 1 pixel
607 int const gap = pi.base.bv->zoomedPixels(1) ;
608 preview_->draw(pi, x + gap, y);
613 // First draw the numbers
614 if (numberedType()) {
615 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
616 for (row_type row = 0; row < nrows(); ++row) {
617 int yy = y + rowinfo(row).offset[bv];
618 docstring const nl = nicelabel(row);
620 mathed_string_dim(pi.base.font, nl, dimnl);
621 if (math_number == BufferParams::LEFT) {
622 ColorCode const col = pi.selected_left
623 ? Color_selectiontext
624 : pi.base.font.color();
625 Changer dummy0 = pi.base.font.changeColor(col);
626 if (dimnl.wid > x - pi.leftx)
627 yy += rowinfo(row).descent + dimnl.asc;
628 pi.pain.fillRectangle(pi.leftx, yy - dimnl.asc,
629 dimnl.width(), dimnl.height(),
630 pi.selected_left ? Color_selection : pi.background_color);
631 pi.draw(pi.leftx, yy, nl);
633 ColorCode const col = pi.selected_right
634 ? Color_selectiontext
635 : pi.base.font.color();
636 Changer dummy0 = pi.base.font.changeColor(col);
637 if (dimnl.wid > pi.rightx - x - dim.wid)
638 yy += rowinfo(row).descent + dimnl.asc;
639 pi.pain.fillRectangle(pi.rightx - dimnl.wid, yy - dimnl.asc,
640 dimnl.width(), dimnl.height(),
641 pi.selected_right ? Color_selection : pi.background_color);
642 pi.draw(pi.rightx - dimnl.wid, yy, nl);
647 // Then the equations
648 ColorCode color = pi.selected && lyxrc.use_system_colors
649 ? Color_selectiontext : standardColor();
650 bool const really_change_color = pi.base.font.color() == Color_none;
651 Changer dummy0 = really_change_color ? pi.base.font.changeColor(color)
653 Changer dummy1 = pi.base.changeFontSet(standardFont());
654 Changer dummy2 = pi.base.font.changeStyle(display() ? DISPLAY_STYLE
656 InsetMathGrid::draw(pi, x + 1, y);
657 drawMarkers(pi, x, y);
659 // drawing change line
660 if (canPaintChange(*bv)) {
662 int const display_margin = display() ? pi.base.inPixels(Length(12, Length::PT)) : 0;
663 pi.change.paintCue(pi, x + 1, y + 1 - dim.asc + display_margin,
664 x + dim.wid, y + dim.des - display_margin);
669 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
672 InsetMathGrid::metricsT(mi, dim);
675 otexrowstream ots(os);
676 TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault);
678 dim.wid = os.str().size();
685 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
688 InsetMathGrid::drawT(pain, x, y);
691 otexrowstream ots(os);
692 TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault);
694 pain.draw(x, y, os.str().c_str());
699 static docstring latexString(InsetMathHull const & inset)
702 // This has to be static, because a preview snippet or a math
703 // macro containing math in text mode (such as $\text{$\phi$}$ or
704 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
705 // first time as a whole, and the second time only the inner math.
706 // In this last case inset.buffer() would be invalid.
707 static Encoding const * encoding = 0;
708 if (inset.isBufferValid())
709 encoding = &(inset.buffer().params().encoding());
710 otexrowstream ots(ls);
711 TeXMathStream wi(ots, false, true, TeXMathStream::wsPreview, encoding);
717 void InsetMathHull::initUnicodeMath() const
719 // Trigger classification of the unicode symbols in this inset
720 docstring const dummy = latexString(*this);
724 void InsetMathHull::addPreview(DocIterator const & inset_pos,
725 graphics::PreviewLoader & /*ploader*/) const
727 if (RenderPreview::previewMath()) {
728 preparePreview(inset_pos);
733 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
734 MacroNameSet & macros, MacroNameSet & defs) const
736 MacroNameSet::iterator const end = macros.end();
738 for (size_t i = 0; i < md.size(); ++i) {
739 InsetMathMacro const * mi = md[i].nucleus()->asMacro();
740 InsetMathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
741 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
742 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
743 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
744 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
746 // Look for macros in the arguments of this macro.
747 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
748 usedMacros(mi->cell(idx), pos, macros, defs);
749 // Make sure this is a macro defined in the document
750 // (as we also spot the macros in the symbols file)
751 // or that we have not already accounted for it.
752 docstring const name = mi->name();
753 if (macros.find(name) == end)
756 // Look for macros in the definition of this macro.
757 MathData ar(pos.buffer());
758 MacroData const * data =
759 pos.buffer()->getMacro(name, pos, true);
761 odocstringstream macro_def;
762 data->write(macro_def, true);
764 defs.insert(macro_def.str());
765 asArray(data->definition(), ar);
767 usedMacros(ar, pos, macros, defs);
769 MathData ar(pos.buffer());
770 asArray(mt->definition(), ar);
771 usedMacros(ar, pos, macros, defs);
773 if (!si->nuc().empty())
774 usedMacros(si->nuc(), pos, macros, defs);
776 usedMacros(si->down(), pos, macros, defs);
778 usedMacros(si->up(), pos, macros, defs);
779 } else if (fi || gi) {
780 idx_type nidx = fi ? fi->nargs() : gi->nargs();
781 for (idx_type idx = 0; idx < nidx; ++idx)
782 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
785 usedMacros(ni->cell(0), pos, macros, defs);
791 void InsetMathHull::preparePreview(DocIterator const & pos,
792 bool forexport) const
794 // there is no need to do all the macro stuff if we're not
795 // actually going to generate the preview.
796 if (!RenderPreview::previewMath() && !forexport)
799 Buffer const * buffer = pos.buffer();
801 // collect macros at this position
803 buffer->listMacroNames(macros);
805 // collect definitions only for the macros used in this inset
807 for (idx_type idx = 0; idx < nargs(); ++idx)
808 usedMacros(cell(idx), pos, macros, defs);
810 docstring macro_preamble;
811 for (auto const & defvar : defs)
812 macro_preamble.append(defvar);
814 // set the font series and size for this snippet
815 DocIterator dit = pos.getInnerText();
816 Paragraph const & par = dit.paragraph();
817 Font font = par.getFontSettings(buffer->params(), dit.pos());
818 font.fontInfo().realize(par.layout().font);
819 string const lsize = font.latexSize();
822 if (font.fontInfo().series() == BOLD_SERIES) {
823 setfont += from_ascii("\\textbf{");
826 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
827 setfont += from_ascii("\\" + lsize + '\n');
829 docstring const snippet = macro_preamble + setfont + latexString(*this) + endfont;
830 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
831 preview_->addPreview(snippet, *buffer, forexport);
835 void InsetMathHull::reloadPreview(DocIterator const & pos) const
838 preview_->startLoading(*pos.buffer());
842 void InsetMathHull::loadPreview(DocIterator const & pos) const
844 bool const forexport = true;
845 preparePreview(pos, forexport);
846 preview_->startLoading(*pos.buffer(), forexport);
850 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
852 if (RenderPreview::previewMath()) {
854 cur.screenUpdateFlags(Update::Force);
860 docstring InsetMathHull::label(row_type row) const
862 LASSERT(row < nrows(), return docstring());
863 if (InsetLabel * il = label_[row])
864 return il->screenLabel();
869 void InsetMathHull::label(row_type row, docstring const & label)
871 //lyxerr << "setting label '" << label << "' for row " << row << endl;
875 label_[row] = dummy_pointer;
878 label_[row]->updateLabelAndRefs(label);
880 label_[row]->setParam("name", label);
884 InsetCommandParams p(LABEL_CODE);
886 label_[row] = new InsetLabel(buffer_, p);
888 label_[row]->setBuffer(buffer());
892 void InsetMathHull::numbered(row_type row, Numbered num)
894 numbered_[row] = num;
898 bool InsetMathHull::numbered(row_type row) const
900 return numbered_[row] == NUMBER;
904 bool InsetMathHull::ams() const
924 for (auto const & row : numbered_)
931 bool InsetMathHull::outerDisplay() const
954 int InsetMathHull::rowFlags() const
971 if (buffer().params().is_math_indent)
972 return Display | AlignLeft;
981 int InsetMathHull::indent(BufferView const & bv) const
983 // FIXME: set this in the textclass. This value is what the article class uses.
984 static Length default_indent(2.5, Length::EM);
985 if (display() && buffer().params().is_math_indent) {
986 Length const & len = buffer().params().getMathIndent();
988 return bv.inPixels(default_indent);
990 return bv.inPixels(len);
992 return Inset::indent(bv);
996 bool InsetMathHull::numberedType() const
1015 for (row_type row = 0; row < nrows(); ++row)
1022 void InsetMathHull::validate(LaTeXFeatures & features) const
1024 if (features.runparams().isLaTeX()) {
1026 features.require("amsmath");
1028 if (type_ == hullRegexp) {
1029 features.require("color");
1030 docstring frcol = from_utf8(lcolor.getLaTeXName(Color_regexpframe));
1031 docstring bgcol = from_ascii("white");
1032 features.addPreambleSnippet(
1033 "\\newcommand{\\regexp}[1]{\\fcolorbox{"
1035 + bgcol + "}{\\ensuremath{\\mathtt{#1}}}}");
1036 features.addPreambleSnippet(
1037 from_ascii("\\newcommand{\\endregexp}{}"));
1038 } else if (outerDisplay() && features.inDeletedInset()) {
1039 features.require("tikz");
1040 features.require("ct-tikz-object-sout");
1043 // Validation is necessary only if not using AMS math.
1044 // To be safe, we will always run mathedvalidate.
1045 //if (features.amsstyle)
1048 //features.binom = true;
1049 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
1050 // it would be better to do this elsewhere, but we can't validate in
1051 // InsetMathMatrix and we have no way, outside MathExtern, to know if
1052 // we even have any matrices.
1053 features.addCSSSnippet(
1054 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
1055 "table.matrix td{padding: 0.25px;}\n"
1056 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
1057 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
1059 InsetMathGrid::validate(features);
1063 CtObject InsetMathHull::getCtObject(OutputParams const & runparams) const
1065 CtObject res = CtObject::Normal;
1081 case hullMultline: {
1082 if (runparams.inulemcmd
1083 && (!runparams.local_font || runparams.local_font->fontInfo().strikeout() != FONT_ON))
1084 res = CtObject::UDisplayObject;
1086 res = CtObject::DisplayObject;
1094 void InsetMathHull::header_write(TeXMathStream & os) const
1096 bool n = numberedType();
1107 if (cell(0).empty())
1112 writeMathdisplayPreamble(os);
1116 os << "\\begin{equation" << star(n) << "}\n";
1126 writeMathdisplayPreamble(os);
1129 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1136 os << "\\begin{" << hullName(type_) << star(n) << '}'
1137 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1143 os << "\\begin{" << hullName(type_) << '}'
1144 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1154 os << "\\begin{unknown" << star(n) << "}\n";
1160 void InsetMathHull::footer_write(TeXMathStream & os) const
1162 bool n = numberedType();
1179 os << "\\end{equation" << star(n) << "}\n";
1182 writeMathdisplayPostamble(os);
1192 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1193 writeMathdisplayPostamble(os);
1200 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1206 os << "\\end{" << hullName(type_) << "}\n";
1210 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1211 os << "\\endregexp{}}";
1217 os << "\\end{unknown" << star(n) << "}\n";
1223 bool InsetMathHull::allowsTabularFeatures() const
1246 bool InsetMathHull::rowChangeOK() const
1249 type_ == hullEqnArray || type_ == hullAlign ||
1250 type_ == hullFlAlign || type_ == hullAlignAt ||
1251 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1252 type_ == hullGather || type_ == hullMultline;
1256 bool InsetMathHull::colChangeOK() const
1259 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1260 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1264 void InsetMathHull::addRow(row_type row)
1269 bool numbered = numberedType();
1270 // Move the number and raw pointer, do not call label() (bug 7511)
1271 InsetLabel * label = dummy_pointer;
1272 docstring number = empty_docstring();
1273 if (type_ == hullMultline) {
1274 if (row + 1 == nrows()) {
1275 numbered_[row] = NONUMBER;
1276 swap(label, label_[row]);
1277 swap(number, numbers_[row]);
1282 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1283 numbers_.insert(numbers_.begin() + row + 1, number);
1284 label_.insert(label_.begin() + row + 1, label);
1285 InsetMathGrid::addRow(row);
1289 void InsetMathHull::swapRow(row_type row)
1293 if (row + 1 == nrows())
1295 swap(numbered_[row], numbered_[row + 1]);
1296 swap(numbers_[row], numbers_[row + 1]);
1297 swap(label_[row], label_[row + 1]);
1298 InsetMathGrid::swapRow(row);
1302 void InsetMathHull::delRow(row_type row)
1304 if (nrows() <= 1 || !rowChangeOK())
1306 if (row + 1 == nrows() && type_ == hullMultline) {
1307 swap(numbered_[row - 1], numbered_[row]);
1308 swap(numbers_[row - 1], numbers_[row]);
1309 swap(label_[row - 1], label_[row]);
1310 InsetMathGrid::delRow(row);
1313 InsetMathGrid::delRow(row);
1314 // The last dummy row has no number info nor a label.
1315 // Test nrows() + 1 because we have already erased the row.
1316 if (row == nrows() + 1)
1318 numbered_.erase(numbered_.begin() + row);
1319 numbers_.erase(numbers_.begin() + row);
1321 label_.erase(label_.begin() + row);
1325 void InsetMathHull::addCol(col_type col)
1329 InsetMathGrid::addCol(col);
1333 void InsetMathHull::delCol(col_type col)
1335 if (ncols() <= 1 || !colChangeOK())
1337 InsetMathGrid::delCol(col);
1341 docstring InsetMathHull::nicelabel(row_type row) const
1343 if (!numbered(row)) {
1346 return '[' + label_[row]->screenLabel() + ']';
1348 docstring const & val = numbers_[row];
1350 return '(' + val + ')';
1351 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1355 void InsetMathHull::glueall(HullType type)
1358 for (idx_type i = 0; i < nargs(); ++i)
1360 InsetLabel * label = 0;
1361 if (type == hullEquation) {
1362 // preserve first non-empty label
1363 for (row_type row = 0; row < nrows(); ++row) {
1365 label = label_[row];
1371 *this = InsetMathHull(buffer_, hullSimple);
1378 void InsetMathHull::splitTo2Cols()
1380 LASSERT(ncols() == 1, return);
1381 InsetMathGrid::addCol(1);
1382 for (row_type row = 0; row < nrows(); ++row) {
1383 idx_type const i = 2 * row;
1384 pos_type pos = firstRelOp(cell(i));
1385 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1386 cell(i).erase(pos, cell(i).size());
1391 void InsetMathHull::splitTo3Cols()
1393 LASSERT(ncols() < 3, return);
1396 InsetMathGrid::addCol(2);
1397 for (row_type row = 0; row < nrows(); ++row) {
1398 idx_type const i = 3 * row + 1;
1399 if (!cell(i).empty()) {
1400 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1401 cell(i).erase(1, cell(i).size());
1407 void InsetMathHull::changeCols(col_type cols)
1409 if (ncols() == cols)
1411 else if (ncols() < cols) {
1417 while (ncols() < cols)
1418 InsetMathGrid::addCol(ncols());
1424 for (row_type row = 0; row < nrows(); ++row) {
1425 idx_type const i = row * ncols();
1426 for (col_type col = cols; col < ncols(); ++col) {
1427 cell(i + cols - 1).append(cell(i + col));
1431 while (ncols() > cols) {
1432 InsetMathGrid::delCol(ncols() - 1);
1437 HullType InsetMathHull::getType() const
1443 void InsetMathHull::setType(HullType type)
1450 bool InsetMathHull::isMutable(HullType type)
1474 void InsetMathHull::mutate(HullType newtype)
1476 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1478 if (newtype == type_)
1481 // This guards the algorithm below it, which is designed with certain types
1483 if (!isMutable(newtype) || !isMutable(type_)) {
1484 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1485 << "' to '" << to_utf8(hullName(newtype))
1486 << "' not implemented" << endl;
1490 // we try to move along the chain
1491 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1493 // +-------------------------------------+
1494 // we use eqnarray as intermediate type for mutations that are not
1495 // directly supported because it handles labels and numbering for
1500 setType(hullSimple);
1506 if (newtype == hullNone) {
1510 setType(hullEquation);
1511 numbered(0, label_[0] != nullptr);
1520 setType(hullSimple);
1525 // split it "nicely" on the first relop
1527 setType(hullEqnArray);
1535 // split it "nicely"
1570 setType(hullEqnArray);
1579 for (row_type row = 0; row < nrows(); ++row)
1580 numbered(row, false);
1590 for (row_type row = 0; row < nrows(); ++row)
1591 numbered(row, false);
1598 setType(hullEqnArray);
1628 for (row_type row = 0; row < nrows(); ++row)
1629 numbered(row, false);
1633 // first we mutate to EqnArray
1635 setType(hullEqnArray);
1642 // we passed the guard so we should not be here
1643 LYXERR0("Mutation not implemented, but should have been.");
1644 LASSERT(false, return);
1650 void InsetMathHull::eol(TeXMathStream & os, row_type row, bool fragile, bool latex,
1651 bool last_eoln) const
1653 if (numberedType()) {
1655 docstring const name =
1656 latex ? escape(label_[row]->getParam("name"))
1657 : label_[row]->getParam("name");
1658 os << "\\label{" + name + '}';
1660 if (type_ != hullMultline) {
1661 if (numbered_[row] == NONUMBER)
1662 os << "\\nonumber ";
1663 else if (numbered_[row] == NOTAG)
1666 if (os.output() == TeXMathStream::wsPreview && !numbers_[row].empty()) {
1667 os << "\\global\\def\\theequation{" << numbers_[row] << "}\n";
1671 // Never add \\ on the last empty line of eqnarray and friends
1673 InsetMathGrid::eol(os, row, fragile, latex, last_eoln);
1676 void InsetMathHull::write(TeXMathStream & os) const
1678 ModeSpecifier specifier(os, MATH_MODE);
1680 InsetMathGrid::write(os);
1685 void InsetMathHull::normalize(NormalStream & os) const
1687 os << "[formula " << hullName(type_) << ' ';
1688 InsetMathGrid::normalize(os);
1693 void InsetMathHull::infoize(odocstream & os) const
1695 os << bformat(_("Type: %1$s"), hullName(type_));
1699 void InsetMathHull::check() const
1701 LATTEST(numbered_.size() == nrows());
1702 LATTEST(numbers_.size() == nrows());
1703 LATTEST(label_.size() == nrows());
1707 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1709 //FIXME: sort out whether we want std::string or docstring for those
1710 string const lang = func.getArg(0);
1711 docstring extra = from_utf8(func.getArg(1));
1713 extra = from_ascii("noextra");
1715 // replace selection with result of computation
1716 if (reduceSelectionToOneCell(cur)) {
1718 asArray(grabAndEraseSelection(cur), ar);
1719 lyxerr << "use selection: " << ar << endl;
1720 cur.insert(pipeThroughExtern(lang, extra, ar));
1724 // only inline, display or eqnarray math is allowed
1725 switch (getType()) {
1731 frontend::Alert::warning(_("Bad math environment"),
1732 _("Computation cannot be performed for AMS "
1733 "math environments.\nChange the math "
1734 "formula type and try again."));
1739 eq.push_back(MathAtom(new InsetMathChar('=')));
1741 // go to first item in line
1742 cur.idx() -= cur.idx() % ncols();
1745 if (getType() == hullSimple) {
1746 size_type pos = cur.cell().find_last(eq);
1748 if (pos == cur.cell().size()) {
1750 lyxerr << "use whole cell: " << ar << endl;
1752 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1753 lyxerr << "use partial cell form pos: " << pos << endl;
1755 cur.cell().append(eq);
1756 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1757 cur.pos() = cur.lastpos();
1761 if (getType() == hullEquation) {
1762 lyxerr << "use equation inset" << endl;
1763 mutate(hullEqnArray);
1764 MathData & ar = cur.cell();
1765 lyxerr << "use cell: " << ar << endl;
1769 cur.cell() = pipeThroughExtern(lang, extra, ar);
1770 // move to end of line
1771 cur.pos() = cur.lastpos();
1776 lyxerr << "use eqnarray" << endl;
1777 cur.idx() += 2 - cur.idx() % ncols();
1779 MathData ar = cur.cell();
1780 lyxerr << "use cell: " << ar << endl;
1781 // FIXME: temporarily disabled
1787 cur.cell() = pipeThroughExtern(lang, extra, ar);
1788 cur.pos() = cur.lastpos();
1793 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1795 //lyxerr << "action: " << cmd.action() << endl;
1796 switch (cmd.action()) {
1798 case LFUN_FINISHED_BACKWARD:
1799 case LFUN_FINISHED_FORWARD:
1800 case LFUN_FINISHED_RIGHT:
1801 case LFUN_FINISHED_LEFT:
1802 //lyxerr << "action: " << cmd.action() << endl;
1803 InsetMathGrid::doDispatch(cur, cmd);
1806 case LFUN_PARAGRAPH_BREAK:
1807 // just swallow this
1810 case LFUN_NEWLINE_INSERT:
1811 // some magic for the common case
1812 if (type_ == hullSimple || type_ == hullEquation) {
1813 cur.recordUndoInset();
1815 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1816 mutate(align ? hullAlign : hullEqnArray);
1817 // mutate() may change labels and such.
1818 cur.forceBufferUpdate();
1819 cur.idx() = nrows() * ncols() - 1;
1820 cur.pos() = cur.lastpos();
1822 InsetMathGrid::doDispatch(cur, cmd);
1825 case LFUN_MATH_NUMBER_TOGGLE: {
1826 //lyxerr << "toggling all numbers" << endl;
1827 cur.recordUndoInset();
1828 bool old = numberedType();
1829 if (type_ == hullMultline)
1830 numbered(nrows() - 1, !old);
1832 for (row_type row = 0; row < nrows(); ++row)
1833 numbered(row, !old);
1835 cur.message(old ? _("No number") : _("Number"));
1836 cur.forceBufferUpdate();
1840 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1841 cur.recordUndoInset();
1842 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1843 bool old = numbered(r);
1844 cur.message(old ? _("No number") : _("Number"));
1846 cur.forceBufferUpdate();
1850 case LFUN_LABEL_INSERT: {
1851 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1852 docstring old_label = label(r);
1853 docstring const default_label = from_ascii("eq:");
1854 if (old_label.empty())
1855 old_label = default_label;
1857 InsetCommandParams p(LABEL_CODE);
1858 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1859 string const data = InsetCommand::params2string(p);
1861 if (cmd.argument().empty())
1862 cur.bv().showDialog("label", data);
1864 FuncRequest fr(LFUN_INSET_INSERT, data);
1870 case LFUN_LABEL_COPY_AS_REFERENCE: {
1872 if (cmd.argument().empty() && &cur.inset() == this)
1873 // if there is no argument and we're inside math, we retrieve
1874 // the row number from the cursor position.
1875 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1877 // if there is an argument, find the corresponding label, else
1878 // check whether there is at least one label.
1879 for (row = 0; row != nrows(); ++row)
1881 && (cmd.argument().empty() || label(row) == cmd.argument()))
1888 InsetCommandParams p(REF_CODE, "ref");
1889 p["reference"] = label(row);
1890 cap::clearSelection();
1891 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1895 case LFUN_WORD_DELETE_FORWARD:
1896 case LFUN_CHAR_DELETE_FORWARD:
1897 if (col(cur.idx()) + 1 == ncols()
1898 && cur.pos() == cur.lastpos()
1899 && !cur.selection()) {
1900 if (!label(row(cur.idx())).empty()) {
1901 cur.recordUndoInset();
1902 label(row(cur.idx()), docstring());
1903 } else if (numbered(row(cur.idx()))) {
1904 cur.recordUndoInset();
1905 numbered(row(cur.idx()), false);
1906 cur.forceBufferUpdate();
1908 InsetMathGrid::doDispatch(cur, cmd);
1912 InsetMathGrid::doDispatch(cur, cmd);
1917 case LFUN_INSET_INSERT: {
1918 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1919 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1920 string const name = cmd.getArg(0);
1921 if (name == "label") {
1922 InsetCommandParams p(LABEL_CODE);
1923 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1924 docstring str = p["name"];
1925 cur.recordUndoInset();
1926 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1930 docstring old = label(r);
1933 // The label will take care of the reference update.
1937 // Newly created inset so initialize it.
1938 label_[r]->initView();
1941 cur.forceBufferUpdate();
1944 InsetMathGrid::doDispatch(cur, cmd);
1948 case LFUN_MATH_EXTERN:
1949 cur.recordUndoInset();
1953 case LFUN_MATH_MUTATE: {
1954 cur.recordUndoInset();
1955 row_type row = cur.row();
1956 col_type col = cur.col();
1957 mutate(hullType(cmd.argument()));
1958 cur.idx() = row * ncols() + col;
1959 if (cur.idx() > cur.lastidx()) {
1960 cur.idx() = cur.lastidx();
1961 cur.pos() = cur.lastpos();
1963 if (cur.pos() > cur.lastpos())
1964 cur.pos() = cur.lastpos();
1966 cur.forceBufferUpdate();
1967 // FIXME: find some more clever handling of the selection,
1968 // i.e. preserve it.
1969 cur.clearSelection();
1970 //cur.dispatched(FINISHED);
1974 case LFUN_MATH_DISPLAY: {
1975 cur.recordUndoInset();
1976 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1977 // if the cursor is in a cell that got merged, move it to
1978 // start of the hull inset.
1979 if (cur.idx() > 0) {
1983 if (cur.pos() > cur.lastpos())
1984 cur.pos() = cur.lastpos();
1989 case LFUN_TABULAR_FEATURE:
1990 if (!allowsTabularFeatures())
1993 InsetMathGrid::doDispatch(cur, cmd);
1997 InsetMathGrid::doDispatch(cur, cmd);
2005 bool allowDisplayMath(Cursor const & cur)
2007 LATTEST(cur.depth() > 1);
2008 Cursor tmpcur = cur;
2011 FuncRequest cmd(LFUN_MATH_DISPLAY);
2012 return tmpcur.getStatus(cmd, status) && status.enabled();
2018 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
2019 FuncStatus & status) const
2021 switch (cmd.action()) {
2022 case LFUN_FINISHED_BACKWARD:
2023 case LFUN_FINISHED_FORWARD:
2024 case LFUN_FINISHED_RIGHT:
2025 case LFUN_FINISHED_LEFT:
2028 case LFUN_NEWLINE_INSERT:
2029 case LFUN_MATH_EXTERN:
2031 status.setEnabled(true);
2034 // we never allow this in math, and we want to bind enter
2035 // to another actions in command-alternatives
2036 case LFUN_PARAGRAPH_BREAK:
2037 status.setEnabled(false);
2039 case LFUN_MATH_MUTATE: {
2040 HullType const ht = hullType(cmd.argument());
2041 status.setOnOff(type_ == ht);
2042 status.setEnabled(isMutable(ht) && isMutable(type_));
2044 if (ht != hullSimple && status.enabled())
2045 status.setEnabled(allowDisplayMath(cur));
2048 case LFUN_MATH_DISPLAY: {
2049 status.setEnabled(display() || allowDisplayMath(cur));
2050 status.setOnOff(display());
2054 case LFUN_MATH_NUMBER_TOGGLE:
2055 // FIXME: what is the right test, this or the one of
2057 status.setEnabled(display());
2058 status.setOnOff(numberedType());
2061 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
2062 // FIXME: what is the right test, this or the one of
2064 bool const enable = (type_ == hullMultline)
2065 ? (nrows() - 1 == cur.row())
2067 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2068 status.setEnabled(enable);
2069 status.setOnOff(enable && numbered(r));
2073 case LFUN_LABEL_INSERT:
2074 status.setEnabled(type_ != hullSimple);
2077 case LFUN_LABEL_COPY_AS_REFERENCE: {
2078 bool enabled = false;
2079 if (cmd.argument().empty() && &cur.inset() == this) {
2080 // if there is no argument and we're inside math, we retrieve
2081 // the row number from the cursor position.
2082 row_type row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2083 enabled = numberedType() && label_[row];
2085 // if there is an argument, find the corresponding label, else
2086 // check whether there is at least one label.
2087 for (row_type row = 0; row != nrows(); ++row) {
2089 (cmd.argument().empty() || label(row) == cmd.argument())) {
2095 status.setEnabled(enabled);
2099 case LFUN_INSET_INSERT:
2100 if (cmd.getArg(0) == "label") {
2101 status.setEnabled(type_ != hullSimple);
2104 return InsetMathGrid::getStatus(cur, cmd, status);
2106 case LFUN_TABULAR_FEATURE: {
2107 if (!allowsTabularFeatures())
2109 string s = cmd.getArg(0);
2111 && (s == "append-row"
2112 || s == "delete-row"
2113 || s == "copy-row")) {
2114 status.message(bformat(
2115 from_utf8(N_("Can't change number of rows in '%1$s'")),
2117 status.setEnabled(false);
2121 && (s == "append-column"
2122 || s == "delete-column"
2123 || s == "copy-column")) {
2124 status.message(bformat(
2125 from_utf8(N_("Can't change number of columns in '%1$s'")),
2127 status.setEnabled(false);
2130 if (s == "add-vline-left" || s == "add-vline-right") {
2131 status.message(bformat(
2132 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2134 status.setEnabled(false);
2137 if (s == "valign-top" || s == "valign-middle"
2138 || s == "valign-bottom" || s == "align-left"
2139 || s == "align-center" || s == "align-right") {
2140 status.setEnabled(false);
2143 return InsetMathGrid::getStatus(cur, cmd, status);
2147 return InsetMathGrid::getStatus(cur, cmd, status);
2152 int InsetMathHull::leftMargin() const
2154 return (getType() == hullSimple) ? 0 : InsetMathGrid::leftMargin();
2158 int InsetMathHull::rightMargin() const
2160 return (getType() == hullSimple) ? 0 : InsetMathGrid::rightMargin();
2164 int InsetMathHull::border() const
2166 return (getType() == hullSimple) ? 0 : InsetMathGrid::border();
2170 /////////////////////////////////////////////////////////////////////
2174 // simply scrap this function if you want
2175 void InsetMathHull::mutateToText()
2178 // translate to latex
2180 latex(os, false, false);
2181 string str = os.str();
2184 Text * lt = view_->cursor().innerText();
2185 string::const_iterator cit = str.begin();
2186 string::const_iterator end = str.end();
2187 for (; cit != end; ++cit)
2188 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2191 //dispatch(LFUN_ESCAPE);
2196 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2197 docstring const & font)
2199 // this whole function is a hack and won't work for incremental font
2202 if (cur.inset().asInsetMath()->name() == font)
2203 cur.handleFont(to_utf8(font));
2205 cur.handleNest(createInsetMath(font, cur.buffer()));
2211 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2216 font.fromString(to_utf8(arg), b);
2217 if (font.fontInfo().color() != Color_inherit) {
2218 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2224 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2227 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
2228 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
2229 enter_front ? idxFirst(cur) : idxLast(cur);
2230 // The inset formula dimension is not necessarily the same as the
2231 // one of the instant preview image, so we have to indicate to the
2232 // BufferView that a metrics update is needed.
2233 cur.screenUpdateFlags(Update::Force);
2237 /////////////////////////////////////////////////////////////////////
2241 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2244 // FIXME: completely broken
2245 static InsetMathHull * lastformula = 0;
2246 static CursorBase current = DocIterator(ibegin(nucleus()));
2248 static string laststr;
2250 if (lastformula != this || laststr != str) {
2251 //lyxerr << "reset lastformula to " << this << endl;
2254 current = ibegin(nucleus());
2256 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2260 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2262 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2263 CursorSlice & top = it.back();
2264 MathData const & a = top.asInsetMath()->cell(top.idx_);
2265 if (a.matchpart(ar, top.pos_)) {
2266 bv->cursor().setSelection(it, ar.size());
2268 top.pos_ += ar.size();
2274 //lyxerr << "not found!" << endl;
2281 void InsetMathHull::write(ostream & os) const
2283 odocstringstream oss;
2284 otexrowstream ots(oss);
2285 TeXMathStream wi(ots, false, false, TeXMathStream::wsDefault);
2288 os << to_utf8(oss.str());
2292 void InsetMathHull::read(Lexer & lex)
2295 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2296 operator=(*at->asHullInset());
2300 bool InsetMathHull::readQuiet(Lexer & lex)
2303 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2305 operator=(*at->asHullInset());
2310 int InsetMathHull::plaintext(odocstringstream & os,
2311 OutputParams const & op, size_t max_length) const
2313 // Try enabling this now that there is a flag as requested at #2275.
2314 if (buffer().isExporting() && display()) {
2318 TextPainter tpain(dim.width(), dim.height());
2319 drawT(tpain, 0, dim.ascent());
2321 // reset metrics cache to "real" values
2323 return tpain.textheight();
2326 odocstringstream oss;
2327 otexrowstream ots(oss);
2328 Encoding const * const enc = encodings.fromLyXName("utf8");
2330 TeXMathStream::OutputType ot;
2331 if (op.find_effective())
2332 ot = TeXMathStream::wsSearchAdv;
2334 ot = TeXMathStream::wsDefault;
2336 if (type_ == hullRegexp) {
2337 TeXMathStream wi(ots, false, true, ot, enc);
2341 TeXMathStream wi(ots, false, true, ot, enc);
2342 for (row_type r = 0; r < nrows(); ++r) {
2343 for (col_type c = 0; c < ncols(); ++c)
2344 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2345 // if it's for the TOC, we write just the first line
2346 // and do not include the newline.
2347 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2349 if (r < nrows() - 1)
2353 docstring const str = oss.str();
2359 void InsetMathHull::docbook(XMLStream & xs, OutputParams const & runparams) const {
2360 // Choose the tag around the MathML equation.
2363 if (getType() == hullSimple)
2364 name = from_ascii("inlineequation");
2366 doCR = true; // This is a block equation, always have <informalequation> on its own line.
2367 name = from_ascii("informalequation");
2370 // DocBook also has <equation>, but it comes with a title.
2371 // TODO: recognise \tag from amsmath? This would allow having <equation> with a proper title.
2375 bool mathmlNamespaceInline = buffer().params().docbook_mathml_prefix == BufferParams::NoPrefix;
2376 if (mathmlNamespaceInline)
2377 attr += "xmlns=\"http://www.w3.org/1998/Math/MathML\"";
2379 for (row_type i = 0; i < nrows(); ++i) {
2380 if (!label(i).empty()) {
2384 attr += "xml:id=\"" + xml::cleanID(label(i)) + "\"";
2390 if (!xs.isLastTagCR())
2393 xs << xml::StartTag(name, attr);
2396 // With DocBook 5, MathML must be within its own namespace (defined in Buffer.cpp::writeDocBookSource, except when
2397 // it should be inlined).
2398 // Output everything in a separate stream so that this does not interfere with the standard flow of DocBook tags.
2399 std::string mathmlNamespacePrefix;
2400 if (!mathmlNamespaceInline) {
2401 if (buffer().params().docbook_mathml_prefix == BufferParams::MPrefix)
2402 mathmlNamespacePrefix = "m";
2403 else if (buffer().params().docbook_mathml_prefix == BufferParams::MMLPrefix)
2404 mathmlNamespacePrefix = "mml";
2407 odocstringstream osmath;
2408 MathMLStream ms(osmath, mathmlNamespacePrefix, true);
2410 // Output the MathML subtree.
2411 // TeX transcription. Avoid MTag/ETag so that there are no extraneous spaces.
2412 ms << "<" << from_ascii("alt") << " role='tex'" << ">";
2413 // Workaround for db2latex: db2latex always includes equations with
2414 // \ensuremath{} or \begin{display}\end{display}
2415 // so we strip LyX' math environment
2416 odocstringstream ls;
2418 TeXMathStream wi(ols, false, false, TeXMathStream::wsDefault, runparams.encoding);
2419 InsetMathGrid::write(wi);
2420 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2421 ms << "</" << from_ascii("alt") << ">";
2423 // Actual transformation of the formula into MathML. This translation may fail (for example, due to custom macros).
2424 // The new output stream is required to deal with the errors: first write completely the formula into this
2425 // temporary stream; then, if it is possible without error, then copy it back to the "real" stream. Otherwise,
2426 // some incomplete tags might be put into the real stream.
2428 // First, generate the MathML expression. If there is an error in the generation, this block is not fully
2429 // executed, and the formula is not output to the DocBook stream.
2430 odocstringstream ostmp;
2431 MathMLStream mstmp(ostmp, ms.xmlns(), ms.xmlMode());
2434 // Choose the display style for the formula, to be output as an attribute near the formula root.
2435 std::string mathmlAttr;
2436 if (getType() == hullSimple)
2437 mathmlAttr = "display=\"inline\"";
2439 mathmlAttr = "display=\"block\"";
2441 // Then, output the formula.
2442 ms << MTag("math", mathmlAttr);
2444 osmath << ostmp.str(); // osmath is not a XMLStream, so no need for XMLStream::ESCAPE_NONE.
2446 } catch (MathExportException const &) {
2448 osmath << "<mathphrase>MathML export failed. Please report this as a bug to the LyX developers: "
2449 "https://www.lyx.org/trac.</mathphrase>";
2452 // Output the complete formula to the DocBook stream.
2453 xs << XMLStream::ESCAPE_NONE << osmath.str();
2455 xs << xml::EndTag(name);
2461 bool InsetMathHull::haveNumbers() const
2463 bool havenumbers = false;
2464 // inline formulas are never numbered (bug 7351 part 3)
2465 if (getType() == hullSimple)
2467 for (size_t i = 0; i != numbered_.size(); ++i) {
2478 // We need to do something about alignment here.
2480 // This duplicates code from InsetMathGrid, but
2481 // we need access here to number information,
2482 // and we simply do not have that in InsetMathGrid.
2483 void InsetMathHull::htmlize(HtmlStream & os) const
2485 bool const havenumbers = haveNumbers();
2486 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2489 os << cell(index(0, 0));
2493 os << MTag("table", "class='mathtable'");
2494 for (row_type row = 0; row < nrows(); ++row) {
2496 for (col_type col = 0; col < ncols(); ++col) {
2498 os << cell(index(row, col));
2503 docstring const & num = numbers_[row];
2505 os << '(' << num << ')';
2510 os << ETag("table");
2514 // this duplicates code from InsetMathGrid, but
2515 // we need access here to number information,
2516 // and we simply do not have that in InsetMathGrid.
2517 void InsetMathHull::mathmlize(MathMLStream & ms) const
2519 bool const havetable = haveNumbers() || nrows() > 1 || ncols() > 1;
2522 if (getType() == hullSimple) {
2523 ms << MTag("mtable");
2524 } else if (getType() >= hullAlign && getType() <= hullXXAlignAt) {
2526 for (col_type col = 0; col < ncols(); ++col) {
2527 alignment += (col % 2) ? "left " : "right ";
2529 ms << MTag("mtable", "displaystyle='true' columnalign='" + alignment + "'");
2531 ms << MTag("mtable", "displaystyle='true'");
2535 char const * const celltag = havetable ? "mtd" : "mrow";
2536 // FIXME There does not seem to be wide support at the moment
2537 // for mlabeledtr, so we have to use just mtr for now.
2538 // char const * const rowtag = haveNumbers() ? "mlabeledtr" : "mtr";
2539 char const * const rowtag = "mtr";
2540 for (row_type row = 0; row < nrows(); ++row) {
2543 for (col_type col = 0; col < ncols(); ++col) {
2545 << cell(index(row, col))
2549 if (haveNumbers()) {
2551 docstring const & num = numbers_[row];
2553 ms << MTagInline("mtext") << '(' << num << ')' << ETagInline("mtext");
2560 ms << ETag("mtable");
2564 void InsetMathHull::mathAsLatex(TeXMathStream & os) const
2566 MathEnsurer ensurer(os, false);
2567 bool havenumbers = haveNumbers();
2568 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2571 os << cell(index(0, 0));
2575 os << "<table class='mathtable'>";
2576 for (row_type row = 0; row < nrows(); ++row) {
2578 for (col_type col = 0; col < ncols(); ++col) {
2579 os << "<td class='math'>";
2580 os << cell(index(row, col));
2585 docstring const & num = numbers_[row];
2587 os << '(' << num << ')';
2596 docstring InsetMathHull::xhtml(XMLStream & xs, OutputParams const & op) const
2598 BufferParams::MathOutput const mathtype =
2599 buffer().masterBuffer()->params().html_math_output;
2601 bool success = false;
2603 // we output all the labels just at the beginning of the equation.
2604 // this should be fine.
2605 for (size_t i = 0; i != label_.size(); ++i) {
2606 InsetLabel const * const il = label_[i];
2612 // FIXME Eventually we would like to do this inset by inset.
2613 if (mathtype == BufferParams::MathML) {
2614 odocstringstream os;
2615 MathMLStream ms(os);
2619 } catch (MathExportException const &) {}
2621 if (getType() == hullSimple)
2622 xs << xml::StartTag("math",
2623 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2625 xs << xml::StartTag("math",
2626 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2627 xs << XMLStream::ESCAPE_NONE
2629 << xml::EndTag("math");
2631 } else if (mathtype == BufferParams::HTML) {
2632 odocstringstream os;
2637 } catch (MathExportException const &) {}
2639 string const tag = (getType() == hullSimple) ? "span" : "div";
2640 xs << xml::StartTag(tag, "class='formula'", true)
2641 << XMLStream::ESCAPE_NONE
2643 << xml::EndTag(tag);
2647 // what we actually want is this:
2649 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2651 // || mathtype == BufferParams::Images
2653 // but what follows is equivalent, since we'll enter only if either (a) we
2654 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2655 // aren't doing LaTeX.
2657 // so this is for Images.
2658 if (!success && mathtype != BufferParams::LaTeX) {
2659 graphics::PreviewImage const * pimage = 0;
2661 loadPreview(docit_);
2662 pimage = preview_->getPreviewImage(buffer());
2663 // FIXME Do we always have png?
2666 if (pimage || op.dryrun) {
2667 string const filename = pimage ? pimage->filename().onlyFileName()
2668 : "previewimage.png";
2670 // if we are not in the master buffer, then we need to see that the
2671 // generated image is copied there; otherwise, preview fails.
2672 Buffer const * mbuf = buffer().masterBuffer();
2673 if (mbuf != &buffer()) {
2674 string mbtmp = mbuf->temppath();
2675 FileName const mbufimg(support::addName(mbtmp, filename));
2676 pimage->filename().copyTo(mbufimg);
2678 // add the file to the list of files to be exported
2679 op.exportdata->addExternalFile("xhtml", pimage->filename());
2682 string const tag = (getType() == hullSimple) ? "span" : "div";
2684 << xml::StartTag(tag, "style = \"text-align: center;\"")
2685 << xml::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2692 // so we'll pass this test if we've failed everything else, or
2693 // if mathtype was LaTeX, since we won't have entered any of the
2695 if (!success /* || mathtype != BufferParams::LaTeX */) {
2696 // Unfortunately, we cannot use latexString() because we do not want
2697 // $...$ or whatever.
2698 odocstringstream ls;
2699 otexrowstream ots(ls);
2700 TeXMathStream wi(ots, false, true, TeXMathStream::wsPreview);
2701 ModeSpecifier specifier(wi, MATH_MODE);
2703 docstring const latex = ls.str();
2705 // class='math' allows for use of jsMath
2706 // http://www.math.union.edu/~dpvc/jsMath/
2708 // probably should allow for some kind of customization here
2709 string const tag = (getType() == hullSimple) ? "span" : "div";
2710 xs << xml::StartTag(tag, "class='math'")
2719 void InsetMathHull::toString(odocstream & os) const
2721 odocstringstream ods;
2722 plaintext(ods, OutputParams(0));
2727 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2729 odocstringstream ods;
2732 // FIXME: this results in spilling TeX into the LyXHTML output since the
2733 // outliner is used to generate the LyXHTML list of figures/etc.
2739 string InsetMathHull::contextMenuName() const
2741 return "context-math";
2745 void InsetMathHull::recordLocation(DocIterator const & di)
2751 bool InsetMathHull::canPaintChange(BufferView const &) const
2753 // We let RowPainter do it seamlessly for inline insets