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 // right now, we only need to do this at export time
257 if (utype == OutputUpdate) {
258 for (size_t i = 0; i < numcnts; ++i) {
259 docstring const cnt = from_ascii(counters_to_save[i]);
260 if (cnts.hasCounter(cnt))
261 counter_map[cnt] = cnts.value(cnt);
265 // this has to be done separately
266 docstring const eqstr = from_ascii("equation");
267 if (cnts.hasCounter(eqstr)) {
268 if (utype == OutputUpdate)
269 counter_map[eqstr] = cnts.value(eqstr);
270 for (size_t i = 0; i != label_.size(); ++i) {
272 Paragraph const & par = it.paragraph();
273 if (!par.isDeleted(it.pos())) {
274 cnts.step(eqstr, utype);
275 numbers_[i] = cnts.theCounter(eqstr, lang);
277 numbers_[i] = from_ascii("#");
279 numbers_[i] = empty_docstring();
285 for (size_t i = 0; i != label_.size(); ++i) {
287 label_[i]->updateBuffer(it, utype, deleted);
290 InsetMathGrid::updateBuffer(it, utype, deleted);
294 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active,
295 UpdateType utype, TocBackend & backend) const
298 //FIXME: buffer_ should be set at creation for this inset! Problem is
299 // This inset is created at too many places (see Parser::parse1() in
304 TocBuilder & b = backend.builder("equation");
305 // compute first and last item
306 row_type first = nrows();
307 for (row_type row = 0; row != nrows(); ++row)
312 if (first == nrows())
315 row_type last = nrows() - 1;
316 for (; last != 0; --last)
319 // add equation numbers
320 b.pushItem(pit, docstring(), output_active);
322 b.argumentItem(bformat(from_ascii("(%1$s-%2$s)"),
323 numbers_[first], numbers_[last]));
324 for (row_type row = 0; row != nrows(); ++row) {
328 label_[row]->addToToc(pit, output_active, utype, backend);
329 docstring label = nicelabel(row);
331 // this is the only equation
332 b.argumentItem(label);
334 // insert as sub-items
335 b.pushItem(pit, label, output_active);
343 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
345 if (previewState(&cur.bv())) {
349 return InsetMathNest::editXY(cur, x, y);
353 InsetMath::mode_type InsetMathHull::currentMode() const
357 return UNDECIDED_MODE;
359 // definitely math mode ...
379 // FIXME: InsetMathGrid should be changed to let the real column alignment be
380 // given by a virtual method like displayColAlign, because the values produced
381 // by defaultColAlign can be invalidated by lfuns such as add-column. For the
382 // moment the values produced by defaultColAlign are not used, notably because
383 // alignment is not implemented in the LyXHTML output.
384 char InsetMathHull::defaultColAlign(col_type col)
386 return colAlign(type_, col);
390 char InsetMathHull::displayColAlign(idx_type idx) const
394 row_type const r = row(idx);
397 if (r == nrows() - 1)
408 return colAlign(type_, col(idx));
412 return InsetMathGrid::displayColAlign(idx);
416 int InsetMathHull::displayColSpace(col_type col) const
418 return colSpace(type_, col);
422 // FIXME: same comment as for defaultColAlign applies.
423 int InsetMathHull::defaultColSpace(col_type col)
425 return colSpace(type_, col);
429 string InsetMathHull::standardFont() const
435 return "lyxnochange";
442 ColorCode InsetMathHull::standardColor() const
447 return Color_foreground;
455 bool InsetMathHull::previewState(const BufferView *const bv) const
457 if (!editing(bv) && RenderPreview::previewMath()
458 && type_ != hullRegexp)
460 graphics::PreviewImage const * pimage =
461 preview_->getPreviewImage(bv->buffer());
462 return pimage && pimage->image();
469 const int ERROR_FRAME_WIDTH = 2;
471 bool previewTooSmall(Dimension const & dim)
473 return dim.width() <= 10 && dim.height() <= 10;
478 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
480 /* Compute \(above|below)displayskip
481 true value in LaTeX is 10pt plus 2pt minus 5pt (in normal size at 10pt)
482 But we use a fixed number of pixels and scale them with zoom.
484 int const bottom_display_margin = mi.base.bv->zoomedPixels(6);
485 int top_display_margin = bottom_display_margin;
486 // at start of paragraph, add an empty line
488 top_display_margin += theFontMetrics(mi.base.font).maxHeight() + 2;
490 if (previewState(mi.base.bv)) {
491 preview_->metrics(mi, dim);
492 if (previewTooSmall(dim)) {
493 // preview image is too small
494 dim.wid += 2 * ERROR_FRAME_WIDTH;
495 dim.asc += 2 * ERROR_FRAME_WIDTH;
497 // insert a gap in front of the formula
498 // value was hardcoded to 1 pixel
499 dim.wid += mi.base.bv->zoomedPixels(1) ;
501 dim.asc += top_display_margin;
502 dim.des += bottom_display_margin;
509 Changer dummy1 = mi.base.changeFontSet(standardFont());
510 Changer dummy2 = mi.base.font.changeStyle(display() ? DISPLAY_STYLE
513 // let the cells adjust themselves
514 InsetMathGrid::metrics(mi, dim);
517 // Check whether the numbering interferes with the equations
518 if (numberedType()) {
519 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
520 int extra_offset = 0;
521 for (row_type row = 0; row < nrows(); ++row) {
522 rowinfo(row).offset[mi.base.bv] += extra_offset;
525 docstring const nl = nicelabel(row);
527 mathed_string_dim(mi.base.font, nl, dimnl);
528 int const ind = indent(*mi.base.bv);
529 int const x = ind ? ind : (mi.base.textwidth - dim.wid) / 2;
530 // for some reason metrics does not trigger at the
531 // same point as draw, and therefore we use >= instead of >
532 if ((math_number == BufferParams::LEFT && dimnl.wid >= x)
533 || (math_number == BufferParams::RIGHT
534 && dimnl.wid >= mi.base.textwidth - x - dim.wid)) {
535 extra_offset += dimnl.height();
538 dim.des += extra_offset;
543 dim.asc += top_display_margin;
544 dim.des += bottom_display_margin;
547 // reserve some space for marker.
552 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
554 BufferView const * const bv = pi.base.bv;
555 if (previewState(bv)) {
556 Dimension const dim = dimension(*pi.base.bv);
557 if (previewTooSmall(dim))
559 return graphics::PreviewLoader::backgroundColor();
565 void InsetMathHull::drawMarkers(PainterInfo & pi, int x, int y) const
567 ColorCode pen_color = mouseHovered(pi.base.bv) || editing(pi.base.bv)?
568 Color_mathframe : Color_mathcorners;
569 // If the corners have the same color as the background, do not paint them.
570 if (lcolor.getX11HexName(Color_mathbg) == lcolor.getX11HexName(pen_color))
573 Inset::drawMarkers(pi, x, y);
574 Dimension const dim = dimension(*pi.base.bv);
575 int const t = x + dim.width() - 1;
576 int const a = y - dim.ascent();
577 pi.pain.line(x, a + 3, x, a, pen_color);
578 pi.pain.line(t, a + 3, t, a, pen_color);
579 pi.pain.line(x, a, x + 3, a, pen_color);
580 pi.pain.line(t - 3, a, t, a, pen_color);
584 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
586 Dimension const dim = dimension(*pi.base.bv);
587 if (previewTooSmall(dim)) {
588 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
589 dim.wid, dim.asc + dim.des, backgroundColor(pi));
593 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
594 dim.height() - 1, pi.backgroundColor(this));
598 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
600 BufferView const * const bv = pi.base.bv;
601 Dimension const dim = dimension(*bv);
603 if (type_ == hullRegexp)
604 pi.pain.rectangle(x + 2, y - dim.ascent() + 1,
605 dim.width() - 3, dim.height() - 2, Color_regexpframe);
607 if (previewState(bv)) {
608 // Do not draw change tracking cue if taken care of by RowPainter
610 Changer dummy = !canPaintChange(*bv) ? changeVar(pi.change, Change())
612 if (previewTooSmall(dim)) {
613 // we have an extra frame
614 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
616 // one pixel gap in front
617 // value was hardcoded to 1 pixel
618 int const gap = pi.base.bv->zoomedPixels(1) ;
619 preview_->draw(pi, x + gap, y);
624 // First draw the numbers
625 if (numberedType()) {
626 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
627 for (row_type row = 0; row < nrows(); ++row) {
628 int yy = y + rowinfo(row).offset[bv];
629 docstring const nl = nicelabel(row);
631 mathed_string_dim(pi.base.font, nl, dimnl);
632 if (math_number == BufferParams::LEFT) {
633 ColorCode const col = pi.selected_left
634 ? Color_selectiontext
635 : pi.base.font.color();
636 Changer dummy0 = pi.base.font.changeColor(col);
637 if (dimnl.wid > x - pi.leftx)
638 yy += rowinfo(row).descent + dimnl.asc;
639 pi.pain.fillRectangle(pi.leftx, yy - dimnl.asc,
640 dimnl.width(), dimnl.height(),
641 pi.selected_left ? Color_selection : pi.background_color);
642 pi.draw(pi.leftx, yy, nl);
644 ColorCode const col = pi.selected_right
645 ? Color_selectiontext
646 : pi.base.font.color();
647 Changer dummy0 = pi.base.font.changeColor(col);
648 if (dimnl.wid > pi.rightx - x - dim.wid)
649 yy += rowinfo(row).descent + dimnl.asc;
650 pi.pain.fillRectangle(pi.rightx - dimnl.wid, yy - dimnl.asc,
651 dimnl.width(), dimnl.height(),
652 pi.selected_right ? Color_selection : pi.background_color);
653 pi.draw(pi.rightx - dimnl.wid, yy, nl);
658 // Then the equations
659 ColorCode color = pi.selected && lyxrc.use_system_colors
660 ? Color_selectiontext : standardColor();
661 bool const really_change_color = pi.base.font.color() == Color_none;
662 Changer dummy0 = really_change_color ? pi.base.font.changeColor(color)
664 Changer dummy1 = pi.base.changeFontSet(standardFont());
665 Changer dummy2 = pi.base.font.changeStyle(display() ? DISPLAY_STYLE
667 InsetMathGrid::draw(pi, x + 1, y);
668 drawMarkers(pi, x, y);
670 // drawing change line
671 if (canPaintChange(*bv)) {
673 int const display_margin = display() ? pi.base.inPixels(Length(12, Length::PT)) : 0;
674 pi.change.paintCue(pi, x + 1, y + 1 - dim.asc + display_margin,
675 x + dim.wid, y + dim.des - display_margin);
680 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
683 InsetMathGrid::metricsT(mi, dim);
686 otexrowstream ots(os);
687 TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault);
689 dim.wid = os.str().size();
696 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
699 InsetMathGrid::drawT(pain, x, y);
702 otexrowstream ots(os);
703 TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault);
705 pain.draw(x, y, os.str().c_str());
710 static docstring latexString(InsetMathHull const & inset)
713 // This has to be static, because a preview snippet or a math
714 // macro containing math in text mode (such as $\text{$\phi$}$ or
715 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
716 // first time as a whole, and the second time only the inner math.
717 // In this last case inset.buffer() would be invalid.
718 static Encoding const * encoding = 0;
719 if (inset.isBufferValid())
720 encoding = &(inset.buffer().params().encoding());
721 otexrowstream ots(ls);
722 TeXMathStream wi(ots, false, true, TeXMathStream::wsPreview, encoding);
728 void InsetMathHull::initUnicodeMath() const
730 // Trigger classification of the unicode symbols in this inset
731 docstring const dummy = latexString(*this);
735 void InsetMathHull::addPreview(DocIterator const & inset_pos,
736 graphics::PreviewLoader & /*ploader*/) const
738 if (RenderPreview::previewMath()) {
739 preparePreview(inset_pos);
744 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
745 MacroNameSet & macros, MacroNameSet & defs) const
747 MacroNameSet::iterator const end = macros.end();
749 for (size_t i = 0; i < md.size(); ++i) {
750 InsetMathMacro const * mi = md[i].nucleus()->asMacro();
751 InsetMathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
752 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
753 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
754 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
755 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
757 // Look for macros in the arguments of this macro.
758 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
759 usedMacros(mi->cell(idx), pos, macros, defs);
760 // Make sure this is a macro defined in the document
761 // (as we also spot the macros in the symbols file)
762 // or that we have not already accounted for it.
763 docstring const name = mi->name();
764 if (macros.find(name) == end)
767 // Look for macros in the definition of this macro.
768 MathData ar(pos.buffer());
769 MacroData const * data =
770 pos.buffer()->getMacro(name, pos, true);
772 odocstringstream macro_def;
773 data->write(macro_def, true);
775 defs.insert(macro_def.str());
776 asArray(data->definition(), ar);
778 usedMacros(ar, pos, macros, defs);
780 MathData ar(pos.buffer());
781 asArray(mt->definition(), ar);
782 usedMacros(ar, pos, macros, defs);
784 if (!si->nuc().empty())
785 usedMacros(si->nuc(), pos, macros, defs);
787 usedMacros(si->down(), pos, macros, defs);
789 usedMacros(si->up(), pos, macros, defs);
790 } else if (fi || gi) {
791 idx_type nidx = fi ? fi->nargs() : gi->nargs();
792 for (idx_type idx = 0; idx < nidx; ++idx)
793 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
796 usedMacros(ni->cell(0), pos, macros, defs);
802 void InsetMathHull::preparePreview(DocIterator const & pos,
803 bool forexport) const
805 // there is no need to do all the macro stuff if we're not
806 // actually going to generate the preview.
807 if (!RenderPreview::previewMath() && !forexport)
810 Buffer const * buffer = pos.buffer();
812 // collect macros at this position
814 buffer->listMacroNames(macros);
816 // collect definitions only for the macros used in this inset
818 for (idx_type idx = 0; idx < nargs(); ++idx)
819 usedMacros(cell(idx), pos, macros, defs);
821 docstring macro_preamble;
822 for (auto const & defvar : defs)
823 macro_preamble.append(defvar);
825 // set the font series and size for this snippet
826 DocIterator dit = pos.getInnerText();
827 Paragraph const & par = dit.paragraph();
828 Font font = par.getFontSettings(buffer->params(), dit.pos());
829 font.fontInfo().realize(par.layout().font);
830 string const lsize = font.latexSize();
833 if (font.fontInfo().series() == BOLD_SERIES) {
834 setfont += from_ascii("\\textbf{");
837 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
838 setfont += from_ascii("\\" + lsize + '\n');
841 if (forexport && haveNumbers()) {
842 docstring eqstr = from_ascii("equation");
843 CounterMap::const_iterator it = counter_map.find(eqstr);
844 if (it != counter_map.end()) {
845 int num = it->second;
847 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
848 '{' + convert<docstring>(num) + '}' + '\n';
850 for (size_t i = 0; i != numcnts; ++i) {
851 docstring cnt = from_ascii(counters_to_save[i]);
852 it = counter_map.find(cnt);
853 if (it == counter_map.end())
855 int num = it->second;
857 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
858 '{' + convert<docstring>(num) + '}';
861 docstring const snippet = macro_preamble + setfont + setcnt
862 + latexString(*this) + endfont;
863 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
864 preview_->addPreview(snippet, *buffer, forexport);
868 void InsetMathHull::reloadPreview(DocIterator const & pos) const
871 preview_->startLoading(*pos.buffer());
875 void InsetMathHull::loadPreview(DocIterator const & pos) const
877 bool const forexport = true;
878 preparePreview(pos, forexport);
879 preview_->startLoading(*pos.buffer(), forexport);
883 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
885 if (RenderPreview::previewMath()) {
887 cur.screenUpdateFlags(Update::Force);
893 docstring InsetMathHull::label(row_type row) const
895 LASSERT(row < nrows(), return docstring());
896 if (InsetLabel * il = label_[row])
897 return il->screenLabel();
902 void InsetMathHull::label(row_type row, docstring const & label)
904 //lyxerr << "setting label '" << label << "' for row " << row << endl;
908 label_[row] = dummy_pointer;
911 label_[row]->updateLabelAndRefs(label);
913 label_[row]->setParam("name", label);
917 InsetCommandParams p(LABEL_CODE);
919 label_[row] = new InsetLabel(buffer_, p);
921 label_[row]->setBuffer(buffer());
925 void InsetMathHull::numbered(row_type row, Numbered num)
927 numbered_[row] = num;
928 if (!numbered(row) && label_[row]) {
935 bool InsetMathHull::numbered(row_type row) const
937 return numbered_[row] == NUMBER;
941 bool InsetMathHull::ams() const
961 for (auto const & row : numbered_)
968 bool InsetMathHull::outerDisplay() const
991 int InsetMathHull::rowFlags() const
1008 if (buffer().params().is_math_indent)
1009 return Display | AlignLeft;
1018 int InsetMathHull::indent(BufferView const & bv) const
1020 // FIXME: set this in the textclass. This value is what the article class uses.
1021 static Length default_indent(2.5, Length::EM);
1022 if (display() && buffer().params().is_math_indent) {
1023 Length const & len = buffer().params().getMathIndent();
1025 return bv.inPixels(default_indent);
1027 return bv.inPixels(len);
1029 return Inset::indent(bv);
1033 bool InsetMathHull::numberedType() const
1052 for (row_type row = 0; row < nrows(); ++row)
1059 void InsetMathHull::validate(LaTeXFeatures & features) const
1061 if (features.runparams().isLaTeX()) {
1063 features.require("amsmath");
1065 if (type_ == hullRegexp) {
1066 features.require("color");
1067 docstring frcol = from_utf8(lcolor.getLaTeXName(Color_regexpframe));
1068 docstring bgcol = from_ascii("white");
1069 features.addPreambleSnippet(
1070 "\\newcommand{\\regexp}[1]{\\fcolorbox{"
1072 + bgcol + "}{\\ensuremath{\\mathtt{#1}}}}");
1073 features.addPreambleSnippet(
1074 from_ascii("\\newcommand{\\endregexp}{}"));
1075 } else if (outerDisplay() && features.inDeletedInset()) {
1076 features.require("tikz");
1077 features.require("ct-tikz-object-sout");
1080 // Validation is necessary only if not using AMS math.
1081 // To be safe, we will always run mathedvalidate.
1082 //if (features.amsstyle)
1085 //features.binom = true;
1086 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
1087 // it would be better to do this elsewhere, but we can't validate in
1088 // InsetMathMatrix and we have no way, outside MathExtern, to know if
1089 // we even have any matrices.
1090 features.addCSSSnippet(
1091 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
1092 "table.matrix td{padding: 0.25px;}\n"
1093 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
1094 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
1096 InsetMathGrid::validate(features);
1100 CtObject InsetMathHull::getCtObject(OutputParams const & runparams) const
1102 CtObject res = CtObject::Normal;
1118 case hullMultline: {
1119 if (runparams.inulemcmd
1120 && (!runparams.local_font || runparams.local_font->fontInfo().strikeout() != FONT_ON))
1121 res = CtObject::UDisplayObject;
1123 res = CtObject::DisplayObject;
1131 void InsetMathHull::header_write(TeXMathStream & os) const
1133 bool n = numberedType();
1144 if (cell(0).empty())
1149 writeMathdisplayPreamble(os);
1153 os << "\\begin{equation" << star(n) << "}\n";
1163 writeMathdisplayPreamble(os);
1166 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1173 os << "\\begin{" << hullName(type_) << star(n) << '}'
1174 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1180 os << "\\begin{" << hullName(type_) << '}'
1181 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1191 os << "\\begin{unknown" << star(n) << "}\n";
1197 void InsetMathHull::footer_write(TeXMathStream & os) const
1199 bool n = numberedType();
1216 os << "\\end{equation" << star(n) << "}\n";
1219 writeMathdisplayPostamble(os);
1229 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1230 writeMathdisplayPostamble(os);
1237 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1243 os << "\\end{" << hullName(type_) << "}\n";
1247 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1248 os << "\\endregexp{}}";
1254 os << "\\end{unknown" << star(n) << "}\n";
1260 bool InsetMathHull::allowsTabularFeatures() const
1283 bool InsetMathHull::rowChangeOK() const
1286 type_ == hullEqnArray || type_ == hullAlign ||
1287 type_ == hullFlAlign || type_ == hullAlignAt ||
1288 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1289 type_ == hullGather || type_ == hullMultline;
1293 bool InsetMathHull::colChangeOK() const
1296 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1297 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1301 void InsetMathHull::addRow(row_type row)
1306 bool numbered = numberedType();
1307 // Move the number and raw pointer, do not call label() (bug 7511)
1308 InsetLabel * label = dummy_pointer;
1309 docstring number = empty_docstring();
1310 if (type_ == hullMultline) {
1311 if (row + 1 == nrows()) {
1312 numbered_[row] = NONUMBER;
1313 swap(label, label_[row]);
1314 swap(number, numbers_[row]);
1319 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1320 numbers_.insert(numbers_.begin() + row + 1, number);
1321 label_.insert(label_.begin() + row + 1, label);
1322 InsetMathGrid::addRow(row);
1326 void InsetMathHull::swapRow(row_type row)
1330 if (row + 1 == nrows())
1332 swap(numbered_[row], numbered_[row + 1]);
1333 swap(numbers_[row], numbers_[row + 1]);
1334 swap(label_[row], label_[row + 1]);
1335 InsetMathGrid::swapRow(row);
1339 void InsetMathHull::delRow(row_type row)
1341 if (nrows() <= 1 || !rowChangeOK())
1343 if (row + 1 == nrows() && type_ == hullMultline) {
1344 swap(numbered_[row - 1], numbered_[row]);
1345 swap(numbers_[row - 1], numbers_[row]);
1346 swap(label_[row - 1], label_[row]);
1347 InsetMathGrid::delRow(row);
1350 InsetMathGrid::delRow(row);
1351 // The last dummy row has no number info nor a label.
1352 // Test nrows() + 1 because we have already erased the row.
1353 if (row == nrows() + 1)
1355 numbered_.erase(numbered_.begin() + row);
1356 numbers_.erase(numbers_.begin() + row);
1358 label_.erase(label_.begin() + row);
1362 void InsetMathHull::addCol(col_type col)
1366 InsetMathGrid::addCol(col);
1370 void InsetMathHull::delCol(col_type col)
1372 if (ncols() <= 1 || !colChangeOK())
1374 InsetMathGrid::delCol(col);
1378 docstring InsetMathHull::nicelabel(row_type row) const
1382 docstring const & val = numbers_[row];
1384 return '(' + val + ')';
1385 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1389 void InsetMathHull::glueall(HullType type)
1392 for (idx_type i = 0; i < nargs(); ++i)
1394 InsetLabel * label = 0;
1395 if (type == hullEquation) {
1396 // preserve first non-empty label
1397 for (row_type row = 0; row < nrows(); ++row) {
1399 label = label_[row];
1405 *this = InsetMathHull(buffer_, hullSimple);
1412 void InsetMathHull::splitTo2Cols()
1414 LASSERT(ncols() == 1, return);
1415 InsetMathGrid::addCol(1);
1416 for (row_type row = 0; row < nrows(); ++row) {
1417 idx_type const i = 2 * row;
1418 pos_type pos = firstRelOp(cell(i));
1419 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1420 cell(i).erase(pos, cell(i).size());
1425 void InsetMathHull::splitTo3Cols()
1427 LASSERT(ncols() < 3, return);
1430 InsetMathGrid::addCol(2);
1431 for (row_type row = 0; row < nrows(); ++row) {
1432 idx_type const i = 3 * row + 1;
1433 if (!cell(i).empty()) {
1434 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1435 cell(i).erase(1, cell(i).size());
1441 void InsetMathHull::changeCols(col_type cols)
1443 if (ncols() == cols)
1445 else if (ncols() < cols) {
1451 while (ncols() < cols)
1452 InsetMathGrid::addCol(ncols());
1458 for (row_type row = 0; row < nrows(); ++row) {
1459 idx_type const i = row * ncols();
1460 for (col_type col = cols; col < ncols(); ++col) {
1461 cell(i + cols - 1).append(cell(i + col));
1465 while (ncols() > cols) {
1466 InsetMathGrid::delCol(ncols() - 1);
1471 HullType InsetMathHull::getType() const
1477 void InsetMathHull::setType(HullType type)
1484 bool InsetMathHull::isMutable(HullType type)
1508 void InsetMathHull::mutate(HullType newtype)
1510 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1512 if (newtype == type_)
1515 // This guards the algorithm below it, which is designed with certain types
1517 if (!isMutable(newtype) || !isMutable(type_)) {
1518 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1519 << "' to '" << to_utf8(hullName(newtype))
1520 << "' not implemented" << endl;
1524 // we try to move along the chain
1525 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1527 // +-------------------------------------+
1528 // we use eqnarray as intermediate type for mutations that are not
1529 // directly supported because it handles labels and numbering for
1534 setType(hullSimple);
1540 if (newtype == hullNone) {
1544 setType(hullEquation);
1545 numbered(0, label_[0] != nullptr);
1554 setType(hullSimple);
1559 // split it "nicely" on the first relop
1561 setType(hullEqnArray);
1569 // split it "nicely"
1604 setType(hullEqnArray);
1613 for (row_type row = 0; row < nrows(); ++row)
1614 numbered(row, false);
1624 for (row_type row = 0; row < nrows(); ++row)
1625 numbered(row, false);
1632 setType(hullEqnArray);
1662 for (row_type row = 0; row < nrows(); ++row)
1663 numbered(row, false);
1667 // first we mutate to EqnArray
1669 setType(hullEqnArray);
1676 // we passed the guard so we should not be here
1677 LYXERR0("Mutation not implemented, but should have been.");
1678 LASSERT(false, return);
1684 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1685 bool last_eoln) const
1688 if (numberedType()) {
1689 if (label_[row] && numbered(row)) {
1690 docstring const name =
1691 latex ? escape(label_[row]->getParam("name"))
1692 : label_[row]->getParam("name");
1693 res += "\\label{" + name + '}';
1695 if (type_ != hullMultline) {
1696 if (numbered_[row] == NONUMBER)
1697 res += "\\nonumber ";
1698 else if (numbered_[row] == NOTAG)
1702 // Never add \\ on the last empty line of eqnarray and friends
1704 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1707 void InsetMathHull::write(TeXMathStream & os) const
1709 ModeSpecifier specifier(os, MATH_MODE);
1711 InsetMathGrid::write(os);
1716 void InsetMathHull::normalize(NormalStream & os) const
1718 os << "[formula " << hullName(type_) << ' ';
1719 InsetMathGrid::normalize(os);
1724 void InsetMathHull::infoize(odocstream & os) const
1726 os << bformat(_("Type: %1$s"), hullName(type_));
1730 void InsetMathHull::check() const
1732 LATTEST(numbered_.size() == nrows());
1733 LATTEST(numbers_.size() == nrows());
1734 LATTEST(label_.size() == nrows());
1738 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1740 //FIXME: sort out whether we want std::string or docstring for those
1741 string const lang = func.getArg(0);
1742 docstring extra = from_utf8(func.getArg(1));
1744 extra = from_ascii("noextra");
1746 // replace selection with result of computation
1747 if (reduceSelectionToOneCell(cur)) {
1749 asArray(grabAndEraseSelection(cur), ar);
1750 lyxerr << "use selection: " << ar << endl;
1751 cur.insert(pipeThroughExtern(lang, extra, ar));
1755 // only inline, display or eqnarray math is allowed
1756 switch (getType()) {
1762 frontend::Alert::warning(_("Bad math environment"),
1763 _("Computation cannot be performed for AMS "
1764 "math environments.\nChange the math "
1765 "formula type and try again."));
1770 eq.push_back(MathAtom(new InsetMathChar('=')));
1772 // go to first item in line
1773 cur.idx() -= cur.idx() % ncols();
1776 if (getType() == hullSimple) {
1777 size_type pos = cur.cell().find_last(eq);
1779 if (pos == cur.cell().size()) {
1781 lyxerr << "use whole cell: " << ar << endl;
1783 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1784 lyxerr << "use partial cell form pos: " << pos << endl;
1786 cur.cell().append(eq);
1787 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1788 cur.pos() = cur.lastpos();
1792 if (getType() == hullEquation) {
1793 lyxerr << "use equation inset" << endl;
1794 mutate(hullEqnArray);
1795 MathData & ar = cur.cell();
1796 lyxerr << "use cell: " << ar << endl;
1800 cur.cell() = pipeThroughExtern(lang, extra, ar);
1801 // move to end of line
1802 cur.pos() = cur.lastpos();
1807 lyxerr << "use eqnarray" << endl;
1808 cur.idx() += 2 - cur.idx() % ncols();
1810 MathData ar = cur.cell();
1811 lyxerr << "use cell: " << ar << endl;
1812 // FIXME: temporarily disabled
1818 cur.cell() = pipeThroughExtern(lang, extra, ar);
1819 cur.pos() = cur.lastpos();
1824 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1826 //lyxerr << "action: " << cmd.action() << endl;
1827 switch (cmd.action()) {
1829 case LFUN_FINISHED_BACKWARD:
1830 case LFUN_FINISHED_FORWARD:
1831 case LFUN_FINISHED_RIGHT:
1832 case LFUN_FINISHED_LEFT:
1833 //lyxerr << "action: " << cmd.action() << endl;
1834 InsetMathGrid::doDispatch(cur, cmd);
1837 case LFUN_PARAGRAPH_BREAK:
1838 // just swallow this
1841 case LFUN_NEWLINE_INSERT:
1842 // some magic for the common case
1843 if (type_ == hullSimple || type_ == hullEquation) {
1844 cur.recordUndoInset();
1846 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1847 mutate(align ? hullAlign : hullEqnArray);
1848 // mutate() may change labels and such.
1849 cur.forceBufferUpdate();
1850 cur.idx() = nrows() * ncols() - 1;
1851 cur.pos() = cur.lastpos();
1853 InsetMathGrid::doDispatch(cur, cmd);
1856 case LFUN_MATH_NUMBER_TOGGLE: {
1857 //lyxerr << "toggling all numbers" << endl;
1858 cur.recordUndoInset();
1859 bool old = numberedType();
1860 if (type_ == hullMultline)
1861 numbered(nrows() - 1, !old);
1863 for (row_type row = 0; row < nrows(); ++row)
1864 numbered(row, !old);
1866 cur.message(old ? _("No number") : _("Number"));
1867 cur.forceBufferUpdate();
1871 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1872 cur.recordUndoInset();
1873 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1874 bool old = numbered(r);
1875 cur.message(old ? _("No number") : _("Number"));
1877 cur.forceBufferUpdate();
1881 case LFUN_LABEL_INSERT: {
1882 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1883 docstring old_label = label(r);
1884 docstring const default_label = from_ascii("eq:");
1885 if (old_label.empty())
1886 old_label = default_label;
1888 InsetCommandParams p(LABEL_CODE);
1889 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1890 string const data = InsetCommand::params2string(p);
1892 if (cmd.argument().empty())
1893 cur.bv().showDialog("label", data);
1895 FuncRequest fr(LFUN_INSET_INSERT, data);
1901 case LFUN_LABEL_COPY_AS_REFERENCE: {
1903 if (cmd.argument().empty() && &cur.inset() == this)
1904 // if there is no argument and we're inside math, we retrieve
1905 // the row number from the cursor position.
1906 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1908 // if there is an argument, find the corresponding label, else
1909 // check whether there is at least one label.
1910 for (row = 0; row != nrows(); ++row)
1911 if (numbered(row) && label_[row]
1912 && (cmd.argument().empty() || label(row) == cmd.argument()))
1919 InsetCommandParams p(REF_CODE, "ref");
1920 p["reference"] = label(row);
1921 cap::clearSelection();
1922 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1926 case LFUN_WORD_DELETE_FORWARD:
1927 case LFUN_CHAR_DELETE_FORWARD:
1928 if (col(cur.idx()) + 1 == ncols()
1929 && cur.pos() == cur.lastpos()
1930 && !cur.selection()) {
1931 if (!label(row(cur.idx())).empty()) {
1932 cur.recordUndoInset();
1933 label(row(cur.idx()), docstring());
1934 } else if (numbered(row(cur.idx()))) {
1935 cur.recordUndoInset();
1936 numbered(row(cur.idx()), false);
1937 cur.forceBufferUpdate();
1939 InsetMathGrid::doDispatch(cur, cmd);
1943 InsetMathGrid::doDispatch(cur, cmd);
1948 case LFUN_INSET_INSERT: {
1949 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1950 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1951 string const name = cmd.getArg(0);
1952 if (name == "label") {
1953 InsetCommandParams p(LABEL_CODE);
1954 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1955 docstring str = p["name"];
1956 cur.recordUndoInset();
1957 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1961 docstring old = label(r);
1964 // The label will take care of the reference update.
1968 // Newly created inset so initialize it.
1969 label_[r]->initView();
1972 cur.forceBufferUpdate();
1975 InsetMathGrid::doDispatch(cur, cmd);
1979 case LFUN_MATH_EXTERN:
1980 cur.recordUndoInset();
1984 case LFUN_MATH_MUTATE: {
1985 cur.recordUndoInset();
1986 row_type row = cur.row();
1987 col_type col = cur.col();
1988 mutate(hullType(cmd.argument()));
1989 cur.idx() = row * ncols() + col;
1990 if (cur.idx() > cur.lastidx()) {
1991 cur.idx() = cur.lastidx();
1992 cur.pos() = cur.lastpos();
1994 if (cur.pos() > cur.lastpos())
1995 cur.pos() = cur.lastpos();
1997 cur.forceBufferUpdate();
1998 // FIXME: find some more clever handling of the selection,
1999 // i.e. preserve it.
2000 cur.clearSelection();
2001 //cur.dispatched(FINISHED);
2005 case LFUN_MATH_DISPLAY: {
2006 cur.recordUndoInset();
2007 mutate(type_ == hullSimple ? hullEquation : hullSimple);
2008 // if the cursor is in a cell that got merged, move it to
2009 // start of the hull inset.
2010 if (cur.idx() > 0) {
2014 if (cur.pos() > cur.lastpos())
2015 cur.pos() = cur.lastpos();
2020 case LFUN_TABULAR_FEATURE:
2021 if (!allowsTabularFeatures())
2024 InsetMathGrid::doDispatch(cur, cmd);
2028 InsetMathGrid::doDispatch(cur, cmd);
2036 bool allowDisplayMath(Cursor const & cur)
2038 LATTEST(cur.depth() > 1);
2039 Cursor tmpcur = cur;
2042 FuncRequest cmd(LFUN_MATH_DISPLAY);
2043 return tmpcur.getStatus(cmd, status) && status.enabled();
2049 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
2050 FuncStatus & status) const
2052 switch (cmd.action()) {
2053 case LFUN_FINISHED_BACKWARD:
2054 case LFUN_FINISHED_FORWARD:
2055 case LFUN_FINISHED_RIGHT:
2056 case LFUN_FINISHED_LEFT:
2059 case LFUN_NEWLINE_INSERT:
2060 case LFUN_MATH_EXTERN:
2062 status.setEnabled(true);
2065 // we never allow this in math, and we want to bind enter
2066 // to another actions in command-alternatives
2067 case LFUN_PARAGRAPH_BREAK:
2068 status.setEnabled(false);
2070 case LFUN_MATH_MUTATE: {
2071 HullType const ht = hullType(cmd.argument());
2072 status.setOnOff(type_ == ht);
2073 status.setEnabled(isMutable(ht) && isMutable(type_));
2075 if (ht != hullSimple && status.enabled())
2076 status.setEnabled(allowDisplayMath(cur));
2079 case LFUN_MATH_DISPLAY: {
2080 status.setEnabled(display() || allowDisplayMath(cur));
2081 status.setOnOff(display());
2085 case LFUN_MATH_NUMBER_TOGGLE:
2086 // FIXME: what is the right test, this or the one of
2088 status.setEnabled(display());
2089 status.setOnOff(numberedType());
2092 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
2093 // FIXME: what is the right test, this or the one of
2095 bool const enable = (type_ == hullMultline)
2096 ? (nrows() - 1 == cur.row())
2098 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2099 status.setEnabled(enable);
2100 status.setOnOff(enable && numbered(r));
2104 case LFUN_LABEL_INSERT:
2105 status.setEnabled(type_ != hullSimple);
2108 case LFUN_LABEL_COPY_AS_REFERENCE: {
2109 bool enabled = false;
2110 if (cmd.argument().empty() && &cur.inset() == this) {
2111 // if there is no argument and we're inside math, we retrieve
2112 // the row number from the cursor position.
2113 row_type row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2114 enabled = numberedType() && label_[row] && numbered(row);
2116 // if there is an argument, find the corresponding label, else
2117 // check whether there is at least one label.
2118 for (row_type row = 0; row != nrows(); ++row) {
2119 if (numbered(row) && label_[row] &&
2120 (cmd.argument().empty() || label(row) == cmd.argument())) {
2126 status.setEnabled(enabled);
2130 case LFUN_INSET_INSERT:
2131 if (cmd.getArg(0) == "label") {
2132 status.setEnabled(type_ != hullSimple);
2135 return InsetMathGrid::getStatus(cur, cmd, status);
2137 case LFUN_TABULAR_FEATURE: {
2138 if (!allowsTabularFeatures())
2140 string s = cmd.getArg(0);
2142 && (s == "append-row"
2143 || s == "delete-row"
2144 || s == "copy-row")) {
2145 status.message(bformat(
2146 from_utf8(N_("Can't change number of rows in '%1$s'")),
2148 status.setEnabled(false);
2152 && (s == "append-column"
2153 || s == "delete-column"
2154 || s == "copy-column")) {
2155 status.message(bformat(
2156 from_utf8(N_("Can't change number of columns in '%1$s'")),
2158 status.setEnabled(false);
2161 if (s == "add-vline-left" || s == "add-vline-right") {
2162 status.message(bformat(
2163 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2165 status.setEnabled(false);
2168 if (s == "valign-top" || s == "valign-middle"
2169 || s == "valign-bottom" || s == "align-left"
2170 || s == "align-center" || s == "align-right") {
2171 status.setEnabled(false);
2174 return InsetMathGrid::getStatus(cur, cmd, status);
2178 return InsetMathGrid::getStatus(cur, cmd, status);
2183 int InsetMathHull::leftMargin() const
2185 return (getType() == hullSimple) ? 0 : InsetMathGrid::leftMargin();
2189 int InsetMathHull::rightMargin() const
2191 return (getType() == hullSimple) ? 0 : InsetMathGrid::rightMargin();
2195 int InsetMathHull::border() const
2197 return (getType() == hullSimple) ? 0 : InsetMathGrid::border();
2201 /////////////////////////////////////////////////////////////////////
2205 // simply scrap this function if you want
2206 void InsetMathHull::mutateToText()
2209 // translate to latex
2211 latex(os, false, false);
2212 string str = os.str();
2215 Text * lt = view_->cursor().innerText();
2216 string::const_iterator cit = str.begin();
2217 string::const_iterator end = str.end();
2218 for (; cit != end; ++cit)
2219 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2222 //dispatch(LFUN_ESCAPE);
2227 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2228 docstring const & font)
2230 // this whole function is a hack and won't work for incremental font
2233 if (cur.inset().asInsetMath()->name() == font)
2234 cur.handleFont(to_utf8(font));
2236 cur.handleNest(createInsetMath(font, cur.buffer()));
2242 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2247 font.fromString(to_utf8(arg), b);
2248 if (font.fontInfo().color() != Color_inherit) {
2249 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2255 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2257 InsetMathNest::edit(cur, front, entry_from);
2258 // The inset formula dimension is not necessarily the same as the
2259 // one of the instant preview image, so we have to indicate to the
2260 // BufferView that a metrics update is needed.
2261 cur.screenUpdateFlags(Update::Force);
2265 /////////////////////////////////////////////////////////////////////
2269 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2272 // FIXME: completely broken
2273 static InsetMathHull * lastformula = 0;
2274 static CursorBase current = DocIterator(ibegin(nucleus()));
2276 static string laststr;
2278 if (lastformula != this || laststr != str) {
2279 //lyxerr << "reset lastformula to " << this << endl;
2282 current = ibegin(nucleus());
2284 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2288 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2290 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2291 CursorSlice & top = it.back();
2292 MathData const & a = top.asInsetMath()->cell(top.idx_);
2293 if (a.matchpart(ar, top.pos_)) {
2294 bv->cursor().setSelection(it, ar.size());
2296 top.pos_ += ar.size();
2302 //lyxerr << "not found!" << endl;
2309 void InsetMathHull::write(ostream & os) const
2311 odocstringstream oss;
2312 otexrowstream ots(oss);
2313 TeXMathStream wi(ots, false, false, TeXMathStream::wsDefault);
2316 os << to_utf8(oss.str());
2320 void InsetMathHull::read(Lexer & lex)
2323 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2324 operator=(*at->asHullInset());
2328 bool InsetMathHull::readQuiet(Lexer & lex)
2331 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2333 operator=(*at->asHullInset());
2338 int InsetMathHull::plaintext(odocstringstream & os,
2339 OutputParams const & op, size_t max_length) const
2341 // Try enabling this now that there is a flag as requested at #2275.
2342 if (buffer().isExporting() && display()) {
2346 TextPainter tpain(dim.width(), dim.height());
2347 drawT(tpain, 0, dim.ascent());
2349 // reset metrics cache to "real" values
2351 return tpain.textheight();
2354 odocstringstream oss;
2355 otexrowstream ots(oss);
2356 Encoding const * const enc = encodings.fromLyXName("utf8");
2357 TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault, enc);
2360 if (type_ == hullRegexp)
2363 for (row_type r = 0; r < nrows(); ++r) {
2364 for (col_type c = 0; c < ncols(); ++c)
2365 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2366 // if it's for the TOC, we write just the first line
2367 // and do not include the newline.
2368 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2370 if (r < nrows() - 1)
2374 docstring const str = oss.str();
2380 void InsetMathHull::docbook(XMLStream & xs, OutputParams const & runparams) const {
2381 // Choose the tag around the MathML equation.
2384 if (getType() == hullSimple)
2385 name = from_ascii("inlineequation");
2387 doCR = true; // This is a block equation, always have <informalequation> on its own line.
2388 name = from_ascii("informalequation");
2391 // DocBook also has <equation>, but it comes with a title.
2392 // TODO: recognise \tag from amsmath? This would allow having <equation> with a proper title.
2396 bool mathmlNamespaceInline = buffer().params().docbook_mathml_prefix == BufferParams::NoPrefix;
2397 if (mathmlNamespaceInline)
2398 attr += "xmlns=\"http://www.w3.org/1998/Math/MathML\"";
2400 for (row_type i = 0; i < nrows(); ++i) {
2401 if (!label(i).empty()) {
2405 attr += "xml:id=\"" + xml::cleanID(label(i)) + "\"";
2411 if (!xs.isLastTagCR())
2414 xs << xml::StartTag(name, attr);
2417 // With DocBook 5, MathML must be within its own namespace (defined in Buffer.cpp::writeDocBookSource, except when
2418 // it should be inlined).
2419 // Output everything in a separate stream so that this does not interfere with the standard flow of DocBook tags.
2420 std::string mathmlNamespacePrefix;
2421 if (!mathmlNamespaceInline) {
2422 if (buffer().params().docbook_mathml_prefix == BufferParams::MPrefix)
2423 mathmlNamespacePrefix = "m";
2424 else if (buffer().params().docbook_mathml_prefix == BufferParams::MMLPrefix)
2425 mathmlNamespacePrefix = "mml";
2428 odocstringstream osmath;
2429 MathMLStream ms(osmath, mathmlNamespacePrefix, true);
2431 // Output the MathML subtree.
2432 // TeX transcription. Avoid MTag/ETag so that there are no extraneous spaces.
2433 ms << "<" << from_ascii("alt") << " role='tex'" << ">";
2434 // Workaround for db2latex: db2latex always includes equations with
2435 // \ensuremath{} or \begin{display}\end{display}
2436 // so we strip LyX' math environment
2437 odocstringstream ls;
2439 TeXMathStream wi(ols, false, false, TeXMathStream::wsDefault, runparams.encoding);
2440 InsetMathGrid::write(wi);
2441 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2442 ms << "</" << from_ascii("alt") << ">";
2444 // Actual transformation of the formula into MathML. This translation may fail (for example, due to custom macros).
2445 // The new output stream is required to deal with the errors: first write completely the formula into this
2446 // temporary stream; then, if it is possible without error, then copy it back to the "real" stream. Otherwise,
2447 // some incomplete tags might be put into the real stream.
2449 // First, generate the MathML expression. If there is an error in the generation, this block is not fully
2450 // executed, and the formula is not output to the DocBook stream.
2451 odocstringstream ostmp;
2452 MathMLStream mstmp(ostmp, ms.xmlns(), ms.xmlMode());
2455 // Choose the display style for the formula, to be output as an attribute near the formula root.
2456 std::string mathmlAttr;
2457 if (getType() == hullSimple)
2458 mathmlAttr = "display=\"inline\"";
2460 mathmlAttr = "display=\"block\"";
2462 // Then, output the formula.
2463 ms << MTag("math", mathmlAttr);
2465 osmath << ostmp.str(); // osmath is not a XMLStream, so no need for XMLStream::ESCAPE_NONE.
2467 } catch (MathExportException const &) {
2469 osmath << "<mathphrase>MathML export failed. Please report this as a bug to the LyX developers: "
2470 "https://www.lyx.org/trac.</mathphrase>";
2473 // Output the complete formula to the DocBook stream.
2474 xs << XMLStream::ESCAPE_NONE << osmath.str();
2476 xs << xml::EndTag(name);
2482 bool InsetMathHull::haveNumbers() const
2484 bool havenumbers = false;
2485 // inline formulas are never numbered (bug 7351 part 3)
2486 if (getType() == hullSimple)
2488 for (size_t i = 0; i != numbered_.size(); ++i) {
2499 // We need to do something about alignment here.
2501 // This duplicates code from InsetMathGrid, but
2502 // we need access here to number information,
2503 // and we simply do not have that in InsetMathGrid.
2504 void InsetMathHull::htmlize(HtmlStream & os) const
2506 bool const havenumbers = haveNumbers();
2507 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2510 os << cell(index(0, 0));
2514 os << MTag("table", "class='mathtable'");
2515 for (row_type row = 0; row < nrows(); ++row) {
2517 for (col_type col = 0; col < ncols(); ++col) {
2519 os << cell(index(row, col));
2524 docstring const & num = numbers_[row];
2526 os << '(' << num << ')';
2531 os << ETag("table");
2535 // this duplicates code from InsetMathGrid, but
2536 // we need access here to number information,
2537 // and we simply do not have that in InsetMathGrid.
2538 void InsetMathHull::mathmlize(MathMLStream & ms) const
2540 bool const havetable = haveNumbers() || nrows() > 1 || ncols() > 1;
2543 if (getType() == hullSimple) {
2544 ms << MTag("mtable");
2545 } else if (getType() >= hullAlign && getType() <= hullXXAlignAt) {
2547 for (col_type col = 0; col < ncols(); ++col) {
2548 alignment += (col % 2) ? "left " : "right ";
2550 ms << MTag("mtable", "displaystyle='true' columnalign='" + alignment + "'");
2552 ms << MTag("mtable", "displaystyle='true'");
2556 char const * const celltag = havetable ? "mtd" : "mrow";
2557 // FIXME There does not seem to be wide support at the moment
2558 // for mlabeledtr, so we have to use just mtr for now.
2559 // char const * const rowtag = haveNumbers() ? "mlabeledtr" : "mtr";
2560 char const * const rowtag = "mtr";
2561 for (row_type row = 0; row < nrows(); ++row) {
2564 for (col_type col = 0; col < ncols(); ++col) {
2566 << cell(index(row, col))
2570 if (haveNumbers()) {
2572 docstring const & num = numbers_[row];
2574 ms << MTagInline("mtext") << '(' << num << ')' << ETagInline("mtext");
2581 ms << ETag("mtable");
2585 void InsetMathHull::mathAsLatex(TeXMathStream & os) const
2587 MathEnsurer ensurer(os, false);
2588 bool havenumbers = haveNumbers();
2589 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2592 os << cell(index(0, 0));
2596 os << "<table class='mathtable'>";
2597 for (row_type row = 0; row < nrows(); ++row) {
2599 for (col_type col = 0; col < ncols(); ++col) {
2600 os << "<td class='math'>";
2601 os << cell(index(row, col));
2606 docstring const & num = numbers_[row];
2608 os << '(' << num << ')';
2617 docstring InsetMathHull::xhtml(XMLStream & xs, OutputParams const & op) const
2619 BufferParams::MathOutput const mathtype =
2620 buffer().masterBuffer()->params().html_math_output;
2622 bool success = false;
2624 // we output all the labels just at the beginning of the equation.
2625 // this should be fine.
2626 for (size_t i = 0; i != label_.size(); ++i) {
2627 InsetLabel const * const il = label_[i];
2633 // FIXME Eventually we would like to do this inset by inset.
2634 if (mathtype == BufferParams::MathML) {
2635 odocstringstream os;
2636 MathMLStream ms(os);
2640 } catch (MathExportException const &) {}
2642 if (getType() == hullSimple)
2643 xs << xml::StartTag("math",
2644 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2646 xs << xml::StartTag("math",
2647 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2648 xs << XMLStream::ESCAPE_NONE
2650 << xml::EndTag("math");
2652 } else if (mathtype == BufferParams::HTML) {
2653 odocstringstream os;
2658 } catch (MathExportException const &) {}
2660 string const tag = (getType() == hullSimple) ? "span" : "div";
2661 xs << xml::StartTag(tag, "class='formula'", true)
2662 << XMLStream::ESCAPE_NONE
2664 << xml::EndTag(tag);
2668 // what we actually want is this:
2670 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2672 // || mathtype == BufferParams::Images
2674 // but what follows is equivalent, since we'll enter only if either (a) we
2675 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2676 // aren't doing LaTeX.
2678 // so this is for Images.
2679 if (!success && mathtype != BufferParams::LaTeX) {
2680 graphics::PreviewImage const * pimage = 0;
2682 loadPreview(docit_);
2683 pimage = preview_->getPreviewImage(buffer());
2684 // FIXME Do we always have png?
2687 if (pimage || op.dryrun) {
2688 string const filename = pimage ? pimage->filename().onlyFileName()
2689 : "previewimage.png";
2691 // if we are not in the master buffer, then we need to see that the
2692 // generated image is copied there; otherwise, preview fails.
2693 Buffer const * mbuf = buffer().masterBuffer();
2694 if (mbuf != &buffer()) {
2695 string mbtmp = mbuf->temppath();
2696 FileName const mbufimg(support::addName(mbtmp, filename));
2697 pimage->filename().copyTo(mbufimg);
2699 // add the file to the list of files to be exported
2700 op.exportdata->addExternalFile("xhtml", pimage->filename());
2703 string const tag = (getType() == hullSimple) ? "span" : "div";
2705 << xml::StartTag(tag, "style = \"text-align: center;\"")
2706 << xml::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2713 // so we'll pass this test if we've failed everything else, or
2714 // if mathtype was LaTeX, since we won't have entered any of the
2716 if (!success /* || mathtype != BufferParams::LaTeX */) {
2717 // Unfortunately, we cannot use latexString() because we do not want
2718 // $...$ or whatever.
2719 odocstringstream ls;
2720 otexrowstream ots(ls);
2721 TeXMathStream wi(ots, false, true, TeXMathStream::wsPreview);
2722 ModeSpecifier specifier(wi, MATH_MODE);
2724 docstring const latex = ls.str();
2726 // class='math' allows for use of jsMath
2727 // http://www.math.union.edu/~dpvc/jsMath/
2729 // probably should allow for some kind of customization here
2730 string const tag = (getType() == hullSimple) ? "span" : "div";
2731 xs << xml::StartTag(tag, "class='math'")
2740 void InsetMathHull::toString(odocstream & os) const
2742 odocstringstream ods;
2743 plaintext(ods, OutputParams(0));
2748 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2750 odocstringstream ods;
2753 // FIXME: this results in spilling TeX into the LyXHTML output since the
2754 // outliner is used to generate the LyXHTML list of figures/etc.
2760 string InsetMathHull::contextMenuName() const
2762 return "context-math";
2766 void InsetMathHull::recordLocation(DocIterator const & di)
2772 bool InsetMathHull::canPaintChange(BufferView const &) const
2774 // We let RowPainter do it seamlessly for inline insets