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 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
234 //FIXME: buffer_ should be set at creation for this inset! Problem is
235 // This inset is created at too many places (see Parser::parse1() in
240 // if any of the equations are numbered, then we want to save the values
241 // of some of the counters.
243 BufferParams const & bp = buffer_->params();
244 string const & lang = it->getParLanguage(bp)->code();
246 buffer_->masterBuffer()->params().documentClass().counters();
248 // this has to be done separately
249 docstring const eqstr = from_ascii("equation");
250 if (cnts.hasCounter(eqstr)) {
251 for (size_t i = 0; i != label_.size(); ++i) {
252 docstring const oldnumber = numbers_[i];
254 Paragraph const & par = it.paragraph();
255 if (!par.isDeleted(it.pos())) {
256 cnts.step(eqstr, utype);
257 numbers_[i] = cnts.theCounter(eqstr, lang);
259 numbers_[i] = from_ascii("#");
261 numbers_[i] = empty_docstring();
262 // If the numbering has changed, trigger a new preview
263 if (oldnumber != numbers_[i] && RenderPreview::previewMath()) {
264 // Do we need to remove it first?
265 //preview_->removePreview(*buffer_);
273 for (size_t i = 0; i != label_.size(); ++i) {
275 label_[i]->updateBuffer(it, utype, deleted);
278 InsetMathGrid::updateBuffer(it, utype, deleted);
282 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active,
283 UpdateType utype, TocBackend & backend) const
286 //FIXME: buffer_ should be set at creation for this inset! Problem is
287 // This inset is created at too many places (see Parser::parse1() in
292 TocBuilder & b = backend.builder("equation");
293 // compute first and last item
294 row_type first = nrows();
295 for (row_type row = 0; row != nrows(); ++row)
300 if (first == nrows())
303 row_type last = nrows() - 1;
304 for (; last != 0; --last)
307 // add equation numbers
308 b.pushItem(pit, docstring(), output_active);
310 b.argumentItem(bformat(from_ascii("(%1$s-%2$s)"),
311 numbers_[first], numbers_[last]));
312 for (row_type row = 0; row != nrows(); ++row) {
316 label_[row]->addToToc(pit, output_active, utype, backend);
317 docstring label = nicelabel(row);
319 // this is the only equation
320 b.argumentItem(label);
322 // insert as sub-items
323 b.pushItem(pit, label, output_active);
331 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
333 if (previewState(&cur.bv())) {
337 return InsetMathNest::editXY(cur, x, y);
341 InsetMath::mode_type InsetMathHull::currentMode() const
345 return UNDECIDED_MODE;
347 // definitely math mode ...
367 // FIXME: InsetMathGrid should be changed to let the real column alignment be
368 // given by a virtual method like displayColAlign, because the values produced
369 // by defaultColAlign can be invalidated by lfuns such as add-column. For the
370 // moment the values produced by defaultColAlign are not used, notably because
371 // alignment is not implemented in the LyXHTML output.
372 char InsetMathHull::defaultColAlign(col_type col)
374 return colAlign(type_, col);
378 char InsetMathHull::displayColAlign(idx_type idx) const
382 row_type const r = row(idx);
385 if (r == nrows() - 1)
396 return colAlign(type_, col(idx));
400 return InsetMathGrid::displayColAlign(idx);
404 int InsetMathHull::displayColSpace(col_type col) const
406 return colSpace(type_, col);
410 // FIXME: same comment as for defaultColAlign applies.
411 int InsetMathHull::defaultColSpace(col_type col)
413 return colSpace(type_, col);
417 string InsetMathHull::standardFont() const
423 return "lyxnochange";
430 ColorCode InsetMathHull::standardColor() const
435 return Color_foreground;
443 bool InsetMathHull::previewState(const BufferView *const bv) const
445 if (!editing(bv) && RenderPreview::previewMath()
446 && type_ != hullRegexp)
448 graphics::PreviewImage const * pimage =
449 preview_->getPreviewImage(bv->buffer());
450 return pimage && pimage->image();
457 const int ERROR_FRAME_WIDTH = 2;
459 bool previewTooSmall(Dimension const & dim)
461 return dim.width() <= 10 && dim.height() <= 10;
466 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
468 /* Compute \(above|below)displayskip
469 true value in LaTeX is 10pt plus 2pt minus 5pt (in normal size at 10pt)
470 But we use a fixed number of pixels and scale them with zoom.
472 int const bottom_display_margin = mi.base.bv->zoomedPixels(6);
473 int top_display_margin = bottom_display_margin;
474 // at start of paragraph, add an empty line
476 top_display_margin += theFontMetrics(mi.base.font).maxHeight() + 2;
478 if (previewState(mi.base.bv)) {
479 preview_->metrics(mi, dim);
480 if (previewTooSmall(dim)) {
481 // preview image is too small
482 dim.wid += 2 * ERROR_FRAME_WIDTH;
483 dim.asc += 2 * ERROR_FRAME_WIDTH;
485 // insert a gap in front of the formula
486 // value was hardcoded to 1 pixel
487 dim.wid += mi.base.bv->zoomedPixels(1) ;
489 dim.asc += top_display_margin;
490 dim.des += bottom_display_margin;
497 Changer dummy1 = mi.base.changeFontSet(standardFont());
498 Changer dummy2 = mi.base.font.changeStyle(display() ? DISPLAY_STYLE
501 // let the cells adjust themselves
502 InsetMathGrid::metrics(mi, dim);
505 // Check whether the numbering interferes with the equations
506 if (numberedType()) {
507 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
508 int extra_offset = 0;
509 for (row_type row = 0; row < nrows(); ++row) {
510 rowinfo(row).offset[mi.base.bv] += extra_offset;
511 docstring const nl = nicelabel(row);
515 mathed_string_dim(mi.base.font, nl, dimnl);
516 int const ind = indent(*mi.base.bv);
517 int const x = ind ? ind : (mi.base.textwidth - dim.wid) / 2;
518 // for some reason metrics does not trigger at the
519 // same point as draw, and therefore we use >= instead of >
520 if ((math_number == BufferParams::LEFT && dimnl.wid >= x)
521 || (math_number == BufferParams::RIGHT
522 && dimnl.wid >= mi.base.textwidth - x - dim.wid)) {
523 extra_offset += dimnl.height();
526 dim.des += extra_offset;
531 dim.asc += top_display_margin;
532 dim.des += bottom_display_margin;
535 // reserve some space for marker.
540 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
542 BufferView const * const bv = pi.base.bv;
543 if (previewState(bv)) {
544 Dimension const dim = dimension(*pi.base.bv);
545 if (previewTooSmall(dim))
547 return graphics::PreviewLoader::backgroundColor();
553 void InsetMathHull::drawMarkers(PainterInfo & pi, int x, int y) const
555 ColorCode pen_color = mouseHovered(pi.base.bv) || editing(pi.base.bv)?
556 Color_mathframe : Color_mathcorners;
557 // If the corners have the same color as the background, do not paint them.
558 if (lcolor.getX11HexName(Color_mathbg) == lcolor.getX11HexName(pen_color))
561 Inset::drawMarkers(pi, x, y);
562 Dimension const dim = dimension(*pi.base.bv);
563 int const t = x + dim.width() - 1;
564 int const a = y - dim.ascent();
565 pi.pain.line(x, a + 3, x, a, pen_color);
566 pi.pain.line(t, a + 3, t, a, pen_color);
567 pi.pain.line(x, a, x + 3, a, pen_color);
568 pi.pain.line(t - 3, a, t, a, pen_color);
572 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
574 Dimension const dim = dimension(*pi.base.bv);
575 if (previewTooSmall(dim)) {
576 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
577 dim.wid, dim.asc + dim.des, backgroundColor(pi));
581 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
582 dim.height() - 1, pi.backgroundColor(this));
586 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
588 BufferView const * const bv = pi.base.bv;
589 Dimension const dim = dimension(*bv);
591 if (type_ == hullRegexp)
592 pi.pain.rectangle(x + 2, y - dim.ascent() + 1,
593 dim.width() - 3, dim.height() - 2, Color_regexpframe);
595 if (previewState(bv)) {
596 // Do not draw change tracking cue if taken care of by RowPainter
598 Changer dummy = !canPaintChange(*bv) ? changeVar(pi.change, Change())
600 if (previewTooSmall(dim)) {
601 // we have an extra frame
602 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
604 // one pixel gap in front
605 // value was hardcoded to 1 pixel
606 int const gap = pi.base.bv->zoomedPixels(1) ;
607 preview_->draw(pi, x + gap, y);
612 // First draw the numbers
613 if (numberedType()) {
614 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
615 for (row_type row = 0; row < nrows(); ++row) {
616 int yy = y + rowinfo(row).offset[bv];
617 docstring const nl = nicelabel(row);
619 mathed_string_dim(pi.base.font, nl, dimnl);
620 if (math_number == BufferParams::LEFT) {
621 ColorCode const col = pi.selected_left
622 ? Color_selectiontext
623 : pi.base.font.color();
624 Changer dummy0 = pi.base.font.changeColor(col);
625 if (dimnl.wid > x - pi.leftx)
626 yy += rowinfo(row).descent + dimnl.asc;
627 pi.pain.fillRectangle(pi.leftx, yy - dimnl.asc,
628 dimnl.width(), dimnl.height(),
629 pi.selected_left ? Color_selection : pi.background_color);
630 pi.draw(pi.leftx, yy, nl);
632 ColorCode const col = pi.selected_right
633 ? Color_selectiontext
634 : pi.base.font.color();
635 Changer dummy0 = pi.base.font.changeColor(col);
636 if (dimnl.wid > pi.rightx - x - dim.wid)
637 yy += rowinfo(row).descent + dimnl.asc;
638 pi.pain.fillRectangle(pi.rightx - dimnl.wid, yy - dimnl.asc,
639 dimnl.width(), dimnl.height(),
640 pi.selected_right ? Color_selection : pi.background_color);
641 pi.draw(pi.rightx - dimnl.wid, yy, nl);
646 // Then the equations
647 ColorCode color = pi.selected && lyxrc.use_system_colors
648 ? Color_selectiontext : standardColor();
649 bool const really_change_color = pi.base.font.color() == Color_none;
650 Changer dummy0 = really_change_color ? pi.base.font.changeColor(color)
652 Changer dummy1 = pi.base.changeFontSet(standardFont());
653 Changer dummy2 = pi.base.font.changeStyle(display() ? DISPLAY_STYLE
655 InsetMathGrid::draw(pi, x + 1, y);
656 drawMarkers(pi, x, y);
658 // drawing change line
659 if (canPaintChange(*bv)) {
661 int const display_margin = display() ? pi.base.inPixels(Length(12, Length::PT)) : 0;
662 pi.change.paintCue(pi, x + 1, y + 1 - dim.asc + display_margin,
663 x + dim.wid, y + dim.des - display_margin);
668 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
671 InsetMathGrid::metricsT(mi, dim);
674 otexrowstream ots(os);
675 TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault);
677 dim.wid = os.str().size();
684 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
687 InsetMathGrid::drawT(pain, x, y);
690 otexrowstream ots(os);
691 TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault);
693 pain.draw(x, y, os.str().c_str());
698 static docstring latexString(InsetMathHull const & inset)
701 // This has to be static, because a preview snippet or a math
702 // macro containing math in text mode (such as $\text{$\phi$}$ or
703 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
704 // first time as a whole, and the second time only the inner math.
705 // In this last case inset.buffer() would be invalid.
706 static Encoding const * encoding = 0;
707 if (inset.isBufferValid())
708 encoding = &(inset.buffer().params().encoding());
709 otexrowstream ots(ls);
710 TeXMathStream wi(ots, false, true, TeXMathStream::wsPreview, encoding);
712 docstring const s = ls.str();
714 for (char_type c : s) {
715 if (encoding->encodable(c))
718 // indicate the encoding error by a boxed '?'
719 res += "{\\fboxsep=1pt\\fbox{?}}";
720 LYXERR0("Uncodable character" << " '"
729 void InsetMathHull::initUnicodeMath() const
731 // Trigger classification of the unicode symbols in this inset
732 docstring const dummy = latexString(*this);
736 void InsetMathHull::addPreview(DocIterator const & inset_pos,
737 graphics::PreviewLoader & /*ploader*/) const
739 if (RenderPreview::previewMath()) {
740 preparePreview(inset_pos);
745 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
746 MacroNameSet & macros, MacroNameSet & defs) const
748 MacroNameSet::iterator const end = macros.end();
750 for (size_t i = 0; i < md.size(); ++i) {
751 InsetMathMacro const * mi = md[i].nucleus()->asMacro();
752 InsetMathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
753 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
754 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
755 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
756 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
758 // Look for macros in the arguments of this macro.
759 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
760 usedMacros(mi->cell(idx), pos, macros, defs);
761 // Make sure this is a macro defined in the document
762 // (as we also spot the macros in the symbols file)
763 // or that we have not already accounted for it.
764 docstring const name = mi->name();
765 if (macros.find(name) == end)
768 // Look for macros in the definition of this macro.
769 MathData ar(pos.buffer());
770 MacroData const * data =
771 pos.buffer()->getMacro(name, pos, true);
773 odocstringstream macro_def;
774 data->write(macro_def, true);
776 defs.insert(macro_def.str());
777 asArray(data->definition(), ar);
779 usedMacros(ar, pos, macros, defs);
781 MathData ar(pos.buffer());
782 asArray(mt->definition(), ar);
783 usedMacros(ar, pos, macros, defs);
785 if (!si->nuc().empty())
786 usedMacros(si->nuc(), pos, macros, defs);
788 usedMacros(si->down(), pos, macros, defs);
790 usedMacros(si->up(), pos, macros, defs);
791 } else if (fi || gi) {
792 idx_type nidx = fi ? fi->nargs() : gi->nargs();
793 for (idx_type idx = 0; idx < nidx; ++idx)
794 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
797 usedMacros(ni->cell(0), pos, macros, defs);
803 void InsetMathHull::preparePreview(DocIterator const & pos,
804 bool forexport) const
806 // there is no need to do all the macro stuff if we're not
807 // actually going to generate the preview.
808 if (!RenderPreview::previewMath() && !forexport)
811 Buffer const * buffer = pos.buffer();
813 // collect macros at this position
815 buffer->listMacroNames(macros);
817 // collect definitions only for the macros used in this inset
819 for (idx_type idx = 0; idx < nargs(); ++idx)
820 usedMacros(cell(idx), pos, macros, defs);
822 docstring macro_preamble;
823 for (auto const & defvar : defs)
824 macro_preamble.append(defvar);
826 // set the font series and size for this snippet
827 DocIterator dit = pos.getInnerText();
828 Paragraph const & par = dit.paragraph();
829 Font font = par.getFontSettings(buffer->params(), dit.pos());
830 font.fontInfo().realize(par.layout().font);
831 string const lsize = font.latexSize();
834 if (font.fontInfo().series() == BOLD_SERIES) {
835 setfont += from_ascii("\\textbf{");
838 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
839 setfont += from_ascii("\\" + lsize + '\n');
841 docstring const snippet = macro_preamble + setfont + latexString(*this) + endfont;
842 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
843 preview_->addPreview(snippet, *buffer, forexport);
847 void InsetMathHull::reloadPreview(DocIterator const & pos) const
850 preview_->startLoading(*pos.buffer());
854 void InsetMathHull::loadPreview(DocIterator const & pos) const
856 bool const forexport = true;
857 preparePreview(pos, forexport);
858 preview_->startLoading(*pos.buffer(), forexport);
862 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
864 if (RenderPreview::previewMath()) {
866 cur.screenUpdateFlags(Update::Force);
872 docstring InsetMathHull::label(row_type row) const
874 LASSERT(row < nrows(), return docstring());
875 if (InsetLabel * il = label_[row])
876 return il->screenLabel();
881 void InsetMathHull::label(row_type row, docstring const & label)
883 //lyxerr << "setting label '" << label << "' for row " << row << endl;
887 label_[row] = dummy_pointer;
890 label_[row]->updateLabelAndRefs(label);
892 label_[row]->setParam("name", label);
896 InsetCommandParams p(LABEL_CODE);
898 label_[row] = new InsetLabel(buffer_, p);
900 label_[row]->setBuffer(buffer());
904 void InsetMathHull::numbered(row_type row, Numbered num)
906 numbered_[row] = num;
910 bool InsetMathHull::numbered(row_type row) const
912 return numbered_[row] == NUMBER;
916 bool InsetMathHull::ams() const
936 for (auto const & row : numbered_)
943 bool InsetMathHull::outerDisplay() const
966 int InsetMathHull::rowFlags() const
983 if (buffer().params().is_math_indent)
984 return Display | AlignLeft;
993 int InsetMathHull::indent(BufferView const & bv) const
995 // FIXME: set this in the textclass. This value is what the article class uses.
996 static Length default_indent(2.5, Length::EM);
997 if (display() && buffer().params().is_math_indent) {
998 Length const & len = buffer().params().getMathIndent();
1000 return bv.inPixels(default_indent);
1002 return bv.inPixels(len);
1004 return Inset::indent(bv);
1008 bool InsetMathHull::numberedType() const
1027 for (row_type row = 0; row < nrows(); ++row)
1034 void InsetMathHull::validate(LaTeXFeatures & features) const
1036 if (features.runparams().isLaTeX()) {
1038 features.require("amsmath");
1040 if (type_ == hullRegexp) {
1041 features.require("color");
1042 docstring frcol = from_utf8(lcolor.getLaTeXName(Color_regexpframe));
1043 docstring bgcol = from_ascii("white");
1044 features.addPreambleSnippet(
1045 "\\newcommand{\\regexp}[1]{\\fcolorbox{"
1047 + bgcol + "}{\\ensuremath{\\mathtt{#1}}}}");
1048 features.addPreambleSnippet(
1049 from_ascii("\\newcommand{\\endregexp}{}"));
1050 } else if (outerDisplay() && features.inDeletedInset()) {
1051 features.require("tikz");
1052 features.require("ct-tikz-object-sout");
1055 // Validation is necessary only if not using AMS math.
1056 // To be safe, we will always run mathedvalidate.
1057 //if (features.amsstyle)
1060 //features.binom = true;
1061 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
1062 // it would be better to do this elsewhere, but we can't validate in
1063 // InsetMathMatrix and we have no way, outside MathExtern, to know if
1064 // we even have any matrices.
1065 features.addCSSSnippet(
1066 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
1067 "table.matrix td{padding: 0.25px;}\n"
1068 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
1069 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
1071 InsetMathGrid::validate(features);
1075 CtObject InsetMathHull::getCtObject(OutputParams const & runparams) const
1077 CtObject res = CtObject::Normal;
1093 case hullMultline: {
1094 if (runparams.inulemcmd
1095 && (!runparams.local_font || runparams.local_font->fontInfo().strikeout() != FONT_ON))
1096 res = CtObject::UDisplayObject;
1098 res = CtObject::DisplayObject;
1106 void InsetMathHull::header_write(TeXMathStream & os) const
1108 bool n = numberedType();
1119 if (cell(0).empty())
1124 writeMathdisplayPreamble(os);
1128 os << "\\begin{equation" << star(n) << "}\n";
1138 writeMathdisplayPreamble(os);
1141 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1148 os << "\\begin{" << hullName(type_) << star(n) << '}'
1149 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1155 os << "\\begin{" << hullName(type_) << '}'
1156 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1166 os << "\\begin{unknown" << star(n) << "}\n";
1172 void InsetMathHull::footer_write(TeXMathStream & os) const
1174 bool n = numberedType();
1191 os << "\\end{equation" << star(n) << "}\n";
1194 writeMathdisplayPostamble(os);
1204 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1205 writeMathdisplayPostamble(os);
1212 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1218 os << "\\end{" << hullName(type_) << "}\n";
1222 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1223 os << "\\endregexp{}}";
1229 os << "\\end{unknown" << star(n) << "}\n";
1235 bool InsetMathHull::allowsTabularFeatures() const
1258 bool InsetMathHull::rowChangeOK() const
1261 type_ == hullEqnArray || type_ == hullAlign ||
1262 type_ == hullFlAlign || type_ == hullAlignAt ||
1263 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1264 type_ == hullGather || type_ == hullMultline;
1268 bool InsetMathHull::colChangeOK() const
1271 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1272 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1276 void InsetMathHull::addRow(row_type row)
1281 bool numbered = numberedType();
1282 // Move the number and raw pointer, do not call label() (bug 7511)
1283 InsetLabel * label = dummy_pointer;
1284 docstring number = empty_docstring();
1285 if (type_ == hullMultline) {
1286 if (row + 1 == nrows()) {
1287 numbered_[row] = NONUMBER;
1288 swap(label, label_[row]);
1289 swap(number, numbers_[row]);
1294 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1295 numbers_.insert(numbers_.begin() + row + 1, number);
1296 label_.insert(label_.begin() + row + 1, label);
1297 InsetMathGrid::addRow(row);
1301 void InsetMathHull::swapRow(row_type row)
1305 if (row + 1 == nrows())
1307 swap(numbered_[row], numbered_[row + 1]);
1308 swap(numbers_[row], numbers_[row + 1]);
1309 swap(label_[row], label_[row + 1]);
1310 InsetMathGrid::swapRow(row);
1314 void InsetMathHull::delRow(row_type row)
1316 if (nrows() <= 1 || !rowChangeOK())
1318 if (row + 1 == nrows() && type_ == hullMultline) {
1319 swap(numbered_[row - 1], numbered_[row]);
1320 swap(numbers_[row - 1], numbers_[row]);
1321 swap(label_[row - 1], label_[row]);
1322 InsetMathGrid::delRow(row);
1325 InsetMathGrid::delRow(row);
1326 // The last dummy row has no number info nor a label.
1327 // Test nrows() + 1 because we have already erased the row.
1328 if (row == nrows() + 1)
1330 numbered_.erase(numbered_.begin() + row);
1331 numbers_.erase(numbers_.begin() + row);
1333 label_.erase(label_.begin() + row);
1337 void InsetMathHull::addCol(col_type col)
1341 InsetMathGrid::addCol(col);
1345 void InsetMathHull::delCol(col_type col)
1347 if (ncols() <= 1 || !colChangeOK())
1349 InsetMathGrid::delCol(col);
1353 docstring InsetMathHull::nicelabel(row_type row) const
1355 if (!numbered(row)) {
1358 return '[' + label_[row]->screenLabel() + ']';
1360 docstring const & val = numbers_[row];
1362 return '(' + val + ')';
1363 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1367 void InsetMathHull::glueall(HullType type)
1370 for (idx_type i = 0; i < nargs(); ++i)
1372 InsetLabel * label = 0;
1373 if (type == hullEquation) {
1374 // preserve first non-empty label
1375 for (row_type row = 0; row < nrows(); ++row) {
1377 label = label_[row];
1383 *this = InsetMathHull(buffer_, hullSimple);
1390 void InsetMathHull::splitTo2Cols()
1392 LASSERT(ncols() == 1, return);
1393 InsetMathGrid::addCol(1);
1394 for (row_type row = 0; row < nrows(); ++row) {
1395 idx_type const i = 2 * row;
1396 pos_type pos = firstRelOp(cell(i));
1397 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1398 cell(i).erase(pos, cell(i).size());
1403 void InsetMathHull::splitTo3Cols()
1405 LASSERT(ncols() < 3, return);
1408 InsetMathGrid::addCol(2);
1409 for (row_type row = 0; row < nrows(); ++row) {
1410 idx_type const i = 3 * row + 1;
1411 if (!cell(i).empty()) {
1412 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1413 cell(i).erase(1, cell(i).size());
1419 void InsetMathHull::changeCols(col_type cols)
1421 if (ncols() == cols)
1423 else if (ncols() < cols) {
1429 while (ncols() < cols)
1430 InsetMathGrid::addCol(ncols());
1436 for (row_type row = 0; row < nrows(); ++row) {
1437 idx_type const i = row * ncols();
1438 for (col_type col = cols; col < ncols(); ++col) {
1439 cell(i + cols - 1).append(cell(i + col));
1443 while (ncols() > cols) {
1444 InsetMathGrid::delCol(ncols() - 1);
1449 HullType InsetMathHull::getType() const
1455 void InsetMathHull::setType(HullType type)
1462 bool InsetMathHull::isMutable(HullType type)
1486 void InsetMathHull::mutate(HullType newtype)
1488 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1490 if (newtype == type_)
1493 // This guards the algorithm below it, which is designed with certain types
1495 if (!isMutable(newtype) || !isMutable(type_)) {
1496 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1497 << "' to '" << to_utf8(hullName(newtype))
1498 << "' not implemented" << endl;
1502 // we try to move along the chain
1503 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1505 // +-------------------------------------+
1506 // we use eqnarray as intermediate type for mutations that are not
1507 // directly supported because it handles labels and numbering for
1512 setType(hullSimple);
1518 if (newtype == hullNone) {
1522 setType(hullEquation);
1523 numbered(0, label_[0] != nullptr);
1532 setType(hullSimple);
1537 // split it "nicely" on the first relop
1539 setType(hullEqnArray);
1547 // split it "nicely"
1582 setType(hullEqnArray);
1591 for (row_type row = 0; row < nrows(); ++row)
1592 numbered(row, false);
1602 for (row_type row = 0; row < nrows(); ++row)
1603 numbered(row, false);
1610 setType(hullEqnArray);
1640 for (row_type row = 0; row < nrows(); ++row)
1641 numbered(row, false);
1645 // first we mutate to EqnArray
1647 setType(hullEqnArray);
1654 // we passed the guard so we should not be here
1655 LYXERR0("Mutation not implemented, but should have been.");
1656 LASSERT(false, return);
1662 void InsetMathHull::eol(TeXMathStream & os, row_type row, bool fragile, bool latex,
1663 bool last_eoln) const
1665 if (numberedType()) {
1667 docstring const name =
1668 latex ? escape(label_[row]->getParam("name"))
1669 : label_[row]->getParam("name");
1670 os << "\\label{" + name + '}';
1672 if (type_ != hullMultline) {
1673 if (numbered_[row] == NONUMBER)
1674 os << "\\nonumber ";
1675 else if (numbered_[row] == NOTAG)
1678 if (os.output() == TeXMathStream::wsPreview && !numbers_[row].empty()) {
1679 os << "\\global\\def\\theequation{" << numbers_[row] << "}\n";
1683 // Never add \\ on the last empty line of eqnarray and friends
1685 InsetMathGrid::eol(os, row, fragile, latex, last_eoln);
1688 void InsetMathHull::write(TeXMathStream & os) const
1690 ModeSpecifier specifier(os, MATH_MODE);
1692 InsetMathGrid::write(os);
1697 void InsetMathHull::normalize(NormalStream & os) const
1699 os << "[formula " << hullName(type_) << ' ';
1700 InsetMathGrid::normalize(os);
1705 void InsetMathHull::infoize(odocstream & os) const
1707 os << bformat(_("Type: %1$s"), hullName(type_));
1711 void InsetMathHull::check() const
1713 LATTEST(numbered_.size() == nrows());
1714 LATTEST(numbers_.size() == nrows());
1715 LATTEST(label_.size() == nrows());
1719 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1721 //FIXME: sort out whether we want std::string or docstring for those
1722 string const lang = func.getArg(0);
1723 docstring extra = from_utf8(func.getArg(1));
1725 extra = from_ascii("noextra");
1727 // replace selection with result of computation
1728 if (reduceSelectionToOneCell(cur)) {
1730 asArray(grabAndEraseSelection(cur), ar);
1731 lyxerr << "use selection: " << ar << endl;
1732 cur.insert(pipeThroughExtern(lang, extra, ar));
1736 // only inline, display or eqnarray math is allowed
1737 switch (getType()) {
1743 frontend::Alert::warning(_("Bad math environment"),
1744 _("Computation cannot be performed for AMS "
1745 "math environments.\nChange the math "
1746 "formula type and try again."));
1751 eq.push_back(MathAtom(new InsetMathChar('=')));
1753 // go to first item in line
1754 cur.idx() -= cur.idx() % ncols();
1757 if (getType() == hullSimple) {
1758 size_type pos = cur.cell().find_last(eq);
1760 if (pos == cur.cell().size()) {
1762 lyxerr << "use whole cell: " << ar << endl;
1764 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1765 lyxerr << "use partial cell form pos: " << pos << endl;
1767 cur.cell().append(eq);
1768 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1769 cur.pos() = cur.lastpos();
1773 if (getType() == hullEquation) {
1774 lyxerr << "use equation inset" << endl;
1775 mutate(hullEqnArray);
1776 MathData & ar = cur.cell();
1777 lyxerr << "use cell: " << ar << endl;
1781 cur.cell() = pipeThroughExtern(lang, extra, ar);
1782 // move to end of line
1783 cur.pos() = cur.lastpos();
1788 lyxerr << "use eqnarray" << endl;
1789 cur.idx() += 2 - cur.idx() % ncols();
1791 MathData ar = cur.cell();
1792 lyxerr << "use cell: " << ar << endl;
1793 // FIXME: temporarily disabled
1799 cur.cell() = pipeThroughExtern(lang, extra, ar);
1800 cur.pos() = cur.lastpos();
1805 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1807 //lyxerr << "action: " << cmd.action() << endl;
1808 switch (cmd.action()) {
1810 case LFUN_FINISHED_BACKWARD:
1811 case LFUN_FINISHED_FORWARD:
1812 case LFUN_FINISHED_RIGHT:
1813 case LFUN_FINISHED_LEFT:
1814 //lyxerr << "action: " << cmd.action() << endl;
1815 InsetMathGrid::doDispatch(cur, cmd);
1818 case LFUN_PARAGRAPH_BREAK:
1819 // just swallow this
1822 case LFUN_NEWLINE_INSERT:
1823 // some magic for the common case
1824 if (type_ == hullSimple || type_ == hullEquation) {
1825 cur.recordUndoInset();
1827 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1828 mutate(align ? hullAlign : hullEqnArray);
1829 // mutate() may change labels and such.
1830 cur.forceBufferUpdate();
1831 cur.idx() = nrows() * ncols() - 1;
1832 cur.pos() = cur.lastpos();
1834 InsetMathGrid::doDispatch(cur, cmd);
1837 case LFUN_MATH_NUMBER_TOGGLE: {
1838 //lyxerr << "toggling all numbers" << endl;
1839 cur.recordUndoInset();
1840 bool old = numberedType();
1841 if (type_ == hullMultline) {
1842 row_type row = nrows() - 1;
1843 numbered(row, !old);
1844 if (old && label_[row]) {
1849 for (row_type row = 0; row < nrows(); ++row) {
1850 numbered(row, !old);
1851 if (old && label_[row]) {
1858 cur.message(old ? _("No number") : _("Number"));
1859 cur.forceBufferUpdate();
1863 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1864 cur.recordUndoInset();
1865 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1866 bool old = numbered(r);
1867 cur.message(old ? _("No number") : _("Number"));
1869 if (old && label_[r]) {
1873 cur.forceBufferUpdate();
1877 case LFUN_LABEL_INSERT: {
1878 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1879 docstring old_label = label(r);
1880 docstring const default_label = from_ascii("eq:");
1881 if (old_label.empty())
1882 old_label = default_label;
1884 InsetCommandParams p(LABEL_CODE);
1885 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1886 string const data = InsetCommand::params2string(p);
1888 if (cmd.argument().empty())
1889 cur.bv().showDialog("label", data);
1891 FuncRequest fr(LFUN_INSET_INSERT, data);
1897 case LFUN_LABEL_COPY_AS_REFERENCE: {
1899 if (cmd.argument().empty() && &cur.inset() == this)
1900 // if there is no argument and we're inside math, we retrieve
1901 // the row number from the cursor position.
1902 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1904 // if there is an argument, find the corresponding label, else
1905 // check whether there is at least one label.
1906 for (row = 0; row != nrows(); ++row)
1908 && (cmd.argument().empty() || label(row) == cmd.argument()))
1915 InsetCommandParams p(REF_CODE, "ref");
1916 p["reference"] = label(row);
1917 cap::clearSelection();
1918 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1922 case LFUN_WORD_DELETE_FORWARD:
1923 case LFUN_CHAR_DELETE_FORWARD:
1924 if (col(cur.idx()) + 1 == ncols()
1925 && cur.pos() == cur.lastpos()
1926 && !cur.selection()) {
1927 if (!label(row(cur.idx())).empty()) {
1928 cur.recordUndoInset();
1929 label(row(cur.idx()), docstring());
1930 } else if (numbered(row(cur.idx()))) {
1931 cur.recordUndoInset();
1932 numbered(row(cur.idx()), false);
1933 cur.forceBufferUpdate();
1935 InsetMathGrid::doDispatch(cur, cmd);
1939 InsetMathGrid::doDispatch(cur, cmd);
1944 case LFUN_INSET_INSERT: {
1945 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1946 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1947 string const name = cmd.getArg(0);
1948 if (name == "label") {
1949 InsetCommandParams p(LABEL_CODE);
1950 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1951 docstring str = p["name"];
1952 cur.recordUndoInset();
1953 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1957 docstring old = label(r);
1960 // The label will take care of the reference update.
1964 // Newly created inset so initialize it.
1965 label_[r]->initView();
1968 cur.forceBufferUpdate();
1971 InsetMathGrid::doDispatch(cur, cmd);
1975 case LFUN_MATH_EXTERN:
1976 cur.recordUndoInset();
1980 case LFUN_MATH_MUTATE: {
1981 cur.recordUndoInset();
1982 row_type row = cur.row();
1983 col_type col = cur.col();
1984 mutate(hullType(cmd.argument()));
1985 cur.idx() = row * ncols() + col;
1986 if (cur.idx() > cur.lastidx()) {
1987 cur.idx() = cur.lastidx();
1988 cur.pos() = cur.lastpos();
1990 if (cur.pos() > cur.lastpos())
1991 cur.pos() = cur.lastpos();
1993 cur.forceBufferUpdate();
1994 // FIXME: find some more clever handling of the selection,
1995 // i.e. preserve it.
1996 cur.clearSelection();
1997 //cur.dispatched(FINISHED);
2001 case LFUN_MATH_DISPLAY: {
2002 cur.recordUndoInset();
2003 mutate(type_ == hullSimple ? hullEquation : hullSimple);
2004 // if the cursor is in a cell that got merged, move it to
2005 // start of the hull inset.
2006 if (cur.idx() > 0) {
2010 if (cur.pos() > cur.lastpos())
2011 cur.pos() = cur.lastpos();
2016 case LFUN_TABULAR_FEATURE:
2017 if (!allowsTabularFeatures())
2020 InsetMathGrid::doDispatch(cur, cmd);
2024 InsetMathGrid::doDispatch(cur, cmd);
2032 bool allowDisplayMath(Cursor const & cur)
2034 LATTEST(cur.depth() > 1);
2035 Cursor tmpcur = cur;
2038 FuncRequest cmd(LFUN_MATH_DISPLAY);
2039 return tmpcur.getStatus(cmd, status) && status.enabled();
2045 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
2046 FuncStatus & status) const
2048 switch (cmd.action()) {
2049 case LFUN_FINISHED_BACKWARD:
2050 case LFUN_FINISHED_FORWARD:
2051 case LFUN_FINISHED_RIGHT:
2052 case LFUN_FINISHED_LEFT:
2055 case LFUN_NEWLINE_INSERT:
2056 case LFUN_MATH_EXTERN:
2058 status.setEnabled(true);
2061 // we never allow this in math, and we want to bind enter
2062 // to another actions in command-alternatives
2063 case LFUN_PARAGRAPH_BREAK:
2064 status.setEnabled(false);
2066 case LFUN_MATH_MUTATE: {
2067 HullType const ht = hullType(cmd.argument());
2068 status.setOnOff(type_ == ht);
2069 status.setEnabled(isMutable(ht) && isMutable(type_));
2071 if (ht != hullSimple && status.enabled())
2072 status.setEnabled(allowDisplayMath(cur));
2075 case LFUN_MATH_DISPLAY: {
2076 status.setEnabled(display() || allowDisplayMath(cur));
2077 status.setOnOff(display());
2081 case LFUN_MATH_NUMBER_TOGGLE:
2082 // FIXME: what is the right test, this or the one of
2084 status.setEnabled(display());
2085 status.setOnOff(numberedType());
2088 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
2089 // FIXME: what is the right test, this or the one of
2091 bool const enable = (type_ == hullMultline)
2092 ? (nrows() - 1 == cur.row())
2094 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2095 status.setEnabled(enable);
2096 status.setOnOff(enable && numbered(r));
2100 case LFUN_LABEL_INSERT:
2101 status.setEnabled(type_ != hullSimple);
2104 case LFUN_LABEL_COPY_AS_REFERENCE: {
2105 bool enabled = false;
2106 if (cmd.argument().empty() && &cur.inset() == this) {
2107 // if there is no argument and we're inside math, we retrieve
2108 // the row number from the cursor position.
2109 row_type row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2110 enabled = numberedType() && label_[row];
2112 // if there is an argument, find the corresponding label, else
2113 // check whether there is at least one label.
2114 for (row_type row = 0; row != nrows(); ++row) {
2116 (cmd.argument().empty() || label(row) == cmd.argument())) {
2122 status.setEnabled(enabled);
2126 case LFUN_INSET_INSERT:
2127 if (cmd.getArg(0) == "label") {
2128 status.setEnabled(type_ != hullSimple);
2131 return InsetMathGrid::getStatus(cur, cmd, status);
2133 case LFUN_TABULAR_FEATURE: {
2134 if (!allowsTabularFeatures())
2136 string s = cmd.getArg(0);
2138 && (s == "append-row"
2139 || s == "delete-row"
2140 || s == "copy-row")) {
2141 status.message(bformat(
2142 from_utf8(N_("Can't change number of rows in '%1$s'")),
2144 status.setEnabled(false);
2148 && (s == "append-column"
2149 || s == "delete-column"
2150 || s == "copy-column")) {
2151 status.message(bformat(
2152 from_utf8(N_("Can't change number of columns in '%1$s'")),
2154 status.setEnabled(false);
2157 if (s == "add-vline-left" || s == "add-vline-right") {
2158 status.message(bformat(
2159 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2161 status.setEnabled(false);
2164 if (s == "valign-top" || s == "valign-middle"
2165 || s == "valign-bottom" || s == "align-left"
2166 || s == "align-center" || s == "align-right") {
2167 status.setEnabled(false);
2170 return InsetMathGrid::getStatus(cur, cmd, status);
2174 return InsetMathGrid::getStatus(cur, cmd, status);
2179 int InsetMathHull::leftMargin() const
2181 return (getType() == hullSimple) ? 0 : InsetMathGrid::leftMargin();
2185 int InsetMathHull::rightMargin() const
2187 return (getType() == hullSimple) ? 0 : InsetMathGrid::rightMargin();
2191 int InsetMathHull::border() const
2193 return (getType() == hullSimple) ? 0 : InsetMathGrid::border();
2197 /////////////////////////////////////////////////////////////////////
2201 // simply scrap this function if you want
2202 void InsetMathHull::mutateToText()
2205 // translate to latex
2207 latex(os, false, false);
2208 string str = os.str();
2211 Text * lt = view_->cursor().innerText();
2212 string::const_iterator cit = str.begin();
2213 string::const_iterator end = str.end();
2214 for (; cit != end; ++cit)
2215 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2218 //dispatch(LFUN_ESCAPE);
2223 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2224 docstring const & font)
2226 // this whole function is a hack and won't work for incremental font
2229 if (cur.inset().asInsetMath()->name() == font)
2230 cur.handleFont(to_utf8(font));
2232 cur.handleNest(createInsetMath(font, cur.buffer()));
2238 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2243 font.fromString(to_utf8(arg), b);
2244 if (font.fontInfo().color() != Color_inherit) {
2245 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2251 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2254 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
2255 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
2256 enter_front ? idxFirst(cur) : idxLast(cur);
2257 // The inset formula dimension is not necessarily the same as the
2258 // one of the instant preview image, so we have to indicate to the
2259 // BufferView that a metrics update is needed.
2260 cur.screenUpdateFlags(Update::Force);
2264 /////////////////////////////////////////////////////////////////////
2268 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2271 // FIXME: completely broken
2272 static InsetMathHull * lastformula = 0;
2273 static CursorBase current = DocIterator(ibegin(nucleus()));
2275 static string laststr;
2277 if (lastformula != this || laststr != str) {
2278 //lyxerr << "reset lastformula to " << this << endl;
2281 current = ibegin(nucleus());
2283 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2287 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2289 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2290 CursorSlice & top = it.back();
2291 MathData const & a = top.asInsetMath()->cell(top.idx_);
2292 if (a.matchpart(ar, top.pos_)) {
2293 bv->cursor().setSelection(it, ar.size());
2295 top.pos_ += ar.size();
2301 //lyxerr << "not found!" << endl;
2308 void InsetMathHull::write(ostream & os) const
2310 odocstringstream oss;
2311 otexrowstream ots(oss);
2312 TeXMathStream wi(ots, false, false, TeXMathStream::wsDefault);
2315 os << to_utf8(oss.str());
2319 void InsetMathHull::read(Lexer & lex)
2322 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2323 operator=(*at->asHullInset());
2327 bool InsetMathHull::readQuiet(Lexer & lex)
2330 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2332 operator=(*at->asHullInset());
2337 int InsetMathHull::plaintext(odocstringstream & os,
2338 OutputParams const & op, size_t max_length) const
2340 // Try enabling this now that there is a flag as requested at #2275.
2341 if (buffer().isExporting() && display()) {
2345 TextPainter tpain(dim.width(), dim.height());
2346 drawT(tpain, 0, dim.ascent());
2348 // reset metrics cache to "real" values
2350 return tpain.textheight();
2353 odocstringstream oss;
2354 otexrowstream ots(oss);
2355 Encoding const * const enc = encodings.fromLyXName("utf8");
2357 TeXMathStream::OutputType ot;
2358 if (op.find_effective())
2359 ot = TeXMathStream::wsSearchAdv;
2361 ot = TeXMathStream::wsDefault;
2363 if (type_ == hullRegexp) {
2364 TeXMathStream wi(ots, false, true, ot, enc);
2368 TeXMathStream wi(ots, false, true, ot, enc);
2369 for (row_type r = 0; r < nrows(); ++r) {
2370 for (col_type c = 0; c < ncols(); ++c)
2371 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2372 // if it's for the TOC, we write just the first line
2373 // and do not include the newline.
2374 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2376 if (r < nrows() - 1)
2380 docstring const str = oss.str();
2386 void InsetMathHull::docbook(XMLStream & xs, OutputParams const & runparams) const {
2387 // Choose the tag around the MathML equation.
2390 if (getType() == hullSimple)
2391 name = from_ascii("inlineequation");
2393 doCR = true; // This is a block equation, always have <informalequation> on its own line.
2394 name = from_ascii("informalequation");
2397 // DocBook also has <equation>, but it comes with a title.
2398 // TODO: recognise \tag from amsmath? This would allow having <equation> with a proper title.
2402 bool mathmlNamespaceInline = buffer().params().docbook_mathml_prefix == BufferParams::NoPrefix;
2403 if (mathmlNamespaceInline)
2404 attr += "xmlns=\"http://www.w3.org/1998/Math/MathML\"";
2406 for (row_type i = 0; i < nrows(); ++i) {
2407 if (!label(i).empty()) {
2411 attr += "xml:id=\"" + xml::cleanID(label(i)) + "\"";
2417 if (!xs.isLastTagCR())
2420 xs << xml::StartTag(name, attr);
2423 // With DocBook 5, MathML must be within its own namespace (defined in Buffer.cpp::writeDocBookSource, except when
2424 // it should be inlined).
2425 // Output everything in a separate stream so that this does not interfere with the standard flow of DocBook tags.
2426 std::string mathmlNamespacePrefix;
2427 if (!mathmlNamespaceInline) {
2428 if (buffer().params().docbook_mathml_prefix == BufferParams::MPrefix)
2429 mathmlNamespacePrefix = "m";
2430 else if (buffer().params().docbook_mathml_prefix == BufferParams::MMLPrefix)
2431 mathmlNamespacePrefix = "mml";
2434 odocstringstream osmath;
2435 MathMLStream ms(osmath, mathmlNamespacePrefix, true);
2437 // Output the MathML subtree.
2438 // TeX transcription. Avoid MTag/ETag so that there are no extraneous spaces.
2439 ms << "<" << from_ascii("alt") << " role='tex'" << ">";
2440 // Workaround for db2latex: db2latex always includes equations with
2441 // \ensuremath{} or \begin{display}\end{display}
2442 // so we strip LyX' math environment
2443 odocstringstream ls;
2445 TeXMathStream wi(ols, false, false, TeXMathStream::wsDefault, runparams.encoding);
2446 InsetMathGrid::write(wi);
2447 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2448 ms << "</" << from_ascii("alt") << ">";
2450 // Actual transformation of the formula into MathML. This translation may fail (for example, due to custom macros).
2451 // The new output stream is required to deal with the errors: first write completely the formula into this
2452 // temporary stream; then, if it is possible without error, then copy it back to the "real" stream. Otherwise,
2453 // some incomplete tags might be put into the real stream.
2455 // First, generate the MathML expression. If there is an error in the generation, this block is not fully
2456 // executed, and the formula is not output to the DocBook stream.
2457 odocstringstream ostmp;
2458 MathMLStream mstmp(ostmp, ms.xmlns(), ms.xmlMode());
2461 // Choose the display style for the formula, to be output as an attribute near the formula root.
2462 std::string mathmlAttr;
2463 if (getType() == hullSimple)
2464 mathmlAttr = "display=\"inline\"";
2466 mathmlAttr = "display=\"block\"";
2468 // Then, output the formula.
2469 ms << MTag("math", mathmlAttr);
2471 osmath << ostmp.str(); // osmath is not a XMLStream, so no need for XMLStream::ESCAPE_NONE.
2473 } catch (MathExportException const &) {
2475 osmath << "<mathphrase>MathML export failed. Please report this as a bug to the LyX developers: "
2476 "https://www.lyx.org/trac.</mathphrase>";
2479 // Output the complete formula to the DocBook stream.
2480 xs << XMLStream::ESCAPE_NONE << osmath.str();
2482 xs << xml::EndTag(name);
2488 bool InsetMathHull::haveNumbers() const
2490 bool havenumbers = false;
2491 // inline formulas are never numbered (bug 7351 part 3)
2492 if (getType() == hullSimple)
2494 for (size_t i = 0; i != numbered_.size(); ++i) {
2505 // We need to do something about alignment here.
2507 // This duplicates code from InsetMathGrid, but
2508 // we need access here to number information,
2509 // and we simply do not have that in InsetMathGrid.
2510 void InsetMathHull::htmlize(HtmlStream & os) const
2512 bool const havenumbers = haveNumbers();
2513 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2516 os << cell(index(0, 0));
2520 os << MTag("table", "class='mathtable'");
2521 for (row_type row = 0; row < nrows(); ++row) {
2523 for (col_type col = 0; col < ncols(); ++col) {
2525 os << cell(index(row, col));
2530 docstring const & num = numbers_[row];
2532 os << '(' << num << ')';
2537 os << ETag("table");
2541 // this duplicates code from InsetMathGrid, but
2542 // we need access here to number information,
2543 // and we simply do not have that in InsetMathGrid.
2544 void InsetMathHull::mathmlize(MathMLStream & ms) const
2546 bool const havetable = haveNumbers() || nrows() > 1 || ncols() > 1;
2549 if (getType() == hullSimple) {
2550 ms << MTag("mtable");
2551 } else if (getType() >= hullAlign && getType() <= hullXXAlignAt) {
2553 for (col_type col = 0; col < ncols(); ++col) {
2554 alignment += (col % 2) ? "left " : "right ";
2556 ms << MTag("mtable", "displaystyle='true' columnalign='" + alignment + "'");
2558 ms << MTag("mtable", "displaystyle='true'");
2562 char const * const celltag = havetable ? "mtd" : "mrow";
2563 // FIXME There does not seem to be wide support at the moment
2564 // for mlabeledtr, so we have to use just mtr for now.
2565 // char const * const rowtag = haveNumbers() ? "mlabeledtr" : "mtr";
2566 char const * const rowtag = "mtr";
2567 for (row_type row = 0; row < nrows(); ++row) {
2570 for (col_type col = 0; col < ncols(); ++col) {
2572 << cell(index(row, col))
2576 if (haveNumbers()) {
2578 docstring const & num = numbers_[row];
2580 ms << MTagInline("mtext") << '(' << num << ')' << ETagInline("mtext");
2587 ms << ETag("mtable");
2591 void InsetMathHull::mathAsLatex(TeXMathStream & os) const
2593 MathEnsurer ensurer(os, false);
2594 bool havenumbers = haveNumbers();
2595 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2598 os << cell(index(0, 0));
2602 os << "<table class='mathtable'>";
2603 for (row_type row = 0; row < nrows(); ++row) {
2605 for (col_type col = 0; col < ncols(); ++col) {
2606 os << "<td class='math'>";
2607 os << cell(index(row, col));
2612 docstring const & num = numbers_[row];
2614 os << '(' << num << ')';
2623 docstring InsetMathHull::xhtml(XMLStream & xs, OutputParams const & op) const
2625 BufferParams::MathOutput const mathtype =
2626 buffer().masterBuffer()->params().html_math_output;
2628 bool success = false;
2630 // we output all the labels just at the beginning of the equation.
2631 // this should be fine.
2632 for (size_t i = 0; i != label_.size(); ++i) {
2633 InsetLabel const * const il = label_[i];
2639 // FIXME Eventually we would like to do this inset by inset.
2640 if (mathtype == BufferParams::MathML) {
2641 odocstringstream os;
2642 MathMLStream ms(os);
2646 } catch (MathExportException const &) {}
2648 if (getType() == hullSimple)
2649 xs << xml::StartTag("math",
2650 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2652 xs << xml::StartTag("math",
2653 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2654 xs << XMLStream::ESCAPE_NONE
2656 << xml::EndTag("math");
2658 } else if (mathtype == BufferParams::HTML) {
2659 odocstringstream os;
2664 } catch (MathExportException const &) {}
2666 string const tag = (getType() == hullSimple) ? "span" : "div";
2667 xs << xml::StartTag(tag, "class='formula'", true)
2668 << XMLStream::ESCAPE_NONE
2670 << xml::EndTag(tag);
2674 // what we actually want is this:
2676 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2678 // || mathtype == BufferParams::Images
2680 // but what follows is equivalent, since we'll enter only if either (a) we
2681 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2682 // aren't doing LaTeX.
2684 // so this is for Images.
2685 if (!success && mathtype != BufferParams::LaTeX) {
2686 graphics::PreviewImage const * pimage = 0;
2688 loadPreview(docit_);
2689 pimage = preview_->getPreviewImage(buffer());
2690 // FIXME Do we always have png?
2693 if (pimage || op.dryrun) {
2694 string const filename = pimage ? pimage->filename().onlyFileName()
2695 : "previewimage.png";
2697 // if we are not in the master buffer, then we need to see that the
2698 // generated image is copied there; otherwise, preview fails.
2699 Buffer const * mbuf = buffer().masterBuffer();
2700 if (mbuf != &buffer()) {
2701 string mbtmp = mbuf->temppath();
2702 FileName const mbufimg(support::addName(mbtmp, filename));
2703 pimage->filename().copyTo(mbufimg);
2705 // add the file to the list of files to be exported
2706 op.exportdata->addExternalFile("xhtml", pimage->filename());
2709 string const tag = (getType() == hullSimple) ? "span" : "div";
2711 << xml::StartTag(tag, "style = \"text-align: center;\"")
2712 << xml::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2719 // so we'll pass this test if we've failed everything else, or
2720 // if mathtype was LaTeX, since we won't have entered any of the
2722 if (!success /* || mathtype != BufferParams::LaTeX */) {
2723 // Unfortunately, we cannot use latexString() because we do not want
2724 // $...$ or whatever.
2725 odocstringstream ls;
2726 otexrowstream ots(ls);
2727 TeXMathStream wi(ots, false, true, TeXMathStream::wsPreview);
2728 ModeSpecifier specifier(wi, MATH_MODE);
2730 docstring const latex = ls.str();
2732 // class='math' allows for use of jsMath
2733 // http://www.math.union.edu/~dpvc/jsMath/
2735 // probably should allow for some kind of customization here
2736 string const tag = (getType() == hullSimple) ? "span" : "div";
2737 xs << xml::StartTag(tag, "class='math'")
2746 void InsetMathHull::toString(odocstream & os) const
2748 odocstringstream ods;
2749 plaintext(ods, OutputParams(0));
2754 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2756 odocstringstream ods;
2759 // FIXME: this results in spilling TeX into the LyXHTML output since the
2760 // outliner is used to generate the LyXHTML list of figures/etc.
2766 string InsetMathHull::contextMenuName() const
2768 return "context-math";
2772 void InsetMathHull::recordLocation(DocIterator const & di)
2778 bool InsetMathHull::canPaintChange(BufferView const &) const
2780 // We let RowPainter do it seamlessly for inline insets