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"
15 #include "InsetMathChar.h"
16 #include "InsetMathColor.h"
17 #include "InsetMathFrac.h"
18 #include "InsetMathNest.h"
19 #include "InsetMathScript.h"
20 #include "MathExtern.h"
21 #include "MathFactory.h"
22 #include "MathStream.h"
23 #include "MathSupport.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
30 #include "CutAndPaste.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
36 #include "LaTeXFeatures.h"
38 #include "MacroTable.h"
39 #include "InsetMathMacro.h"
40 #include "InsetMathMacroTemplate.h"
41 #include "MetricsInfo.h"
42 #include "Paragraph.h"
43 #include "ParIterator.h"
46 #include "TextClass.h"
47 #include "TextPainter.h"
48 #include "TocBackend.h"
50 #include "insets/InsetLabel.h"
51 #include "insets/InsetRef.h"
52 #include "insets/RenderPreview.h"
54 #include "graphics/GraphicsImage.h"
55 #include "graphics/PreviewImage.h"
56 #include "graphics/PreviewLoader.h"
58 #include "frontends/alert.h"
59 #include "frontends/FontMetrics.h"
60 #include "frontends/Painter.h"
62 #include "support/convert.h"
63 #include "support/debug.h"
64 #include "support/gettext.h"
65 #include "support/filetools.h"
66 #include "support/lassert.h"
67 #include "support/lstrings.h"
68 #include "support/RefChanger.h"
73 using namespace lyx::support;
77 using cap::grabAndEraseSelection;
78 using cap::reduceSelectionToOneCell;
82 int getCols(HullType type)
107 // returns position of first relation operator in the array
108 // used for "intelligent splitting"
109 size_t firstRelOp(MathData const & ar)
111 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
112 if ((*it)->mathClass() == MC_REL)
113 return it - ar.begin();
118 char const * star(bool numbered)
120 return numbered ? "" : "*";
124 // writes a preamble for underlined or struck out math display
125 void writeMathdisplayPreamble(WriteStream & os)
127 if (os.strikeoutMath())
130 if (os.ulemCmd() == WriteStream::UNDERLINE)
131 os << "\\raisebox{-\\belowdisplayshortskip}{"
132 "\\parbox[b]{\\linewidth}{";
133 else if (os.ulemCmd() == WriteStream::STRIKEOUT)
134 os << "\\parbox{\\linewidth}{";
138 // writes a postamble for underlined or struck out math display
139 void writeMathdisplayPostamble(WriteStream & os)
141 if (os.strikeoutMath())
144 if (os.ulemCmd() == WriteStream::UNDERLINE)
146 else if (os.ulemCmd() == WriteStream::STRIKEOUT)
154 HullType hullType(docstring const & s)
156 if (s == "none") return hullNone;
157 if (s == "simple") return hullSimple;
158 if (s == "equation") return hullEquation;
159 if (s == "eqnarray") return hullEqnArray;
160 if (s == "align") return hullAlign;
161 if (s == "alignat") return hullAlignAt;
162 if (s == "xalignat") return hullXAlignAt;
163 if (s == "xxalignat") return hullXXAlignAt;
164 if (s == "multline") return hullMultline;
165 if (s == "gather") return hullGather;
166 if (s == "flalign") return hullFlAlign;
167 if (s == "regexp") return hullRegexp;
168 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
173 docstring hullName(HullType type)
176 case hullNone: return from_ascii("none");
177 case hullSimple: return from_ascii("simple");
178 case hullEquation: return from_ascii("equation");
179 case hullEqnArray: return from_ascii("eqnarray");
180 case hullAlign: return from_ascii("align");
181 case hullAlignAt: return from_ascii("alignat");
182 case hullXAlignAt: return from_ascii("xalignat");
183 case hullXXAlignAt: return from_ascii("xxalignat");
184 case hullMultline: return from_ascii("multline");
185 case hullGather: return from_ascii("gather");
186 case hullFlAlign: return from_ascii("flalign");
187 case hullRegexp: return from_ascii("regexp");
189 lyxerr << "unknown hull type" << endl;
192 return from_ascii("none");
195 static InsetLabel * dummy_pointer = 0;
197 InsetMathHull::InsetMathHull(Buffer * buf)
198 : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, NONUMBER),
199 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
200 preview_(new RenderPreview(this))
202 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
203 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
204 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
205 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
212 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
213 : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, NONUMBER),
214 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
215 preview_(new RenderPreview(this))
223 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
229 InsetMathHull::~InsetMathHull()
231 for (auto & i : label_)
236 Inset * InsetMathHull::clone() const
238 return new InsetMathHull(*this);
242 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
246 InsetMathGrid::operator=(other);
248 numbered_ = other.numbered_;
249 numbers_ = other.numbers_;
250 buffer_ = other.buffer_;
251 for (auto & i : label_)
253 label_ = other.label_;
254 for (size_t i = 0; i != label_.size(); ++i) {
256 label_[i] = new InsetLabel(*label_[i]);
258 preview_.reset(new RenderPreview(*other.preview_, this));
264 void InsetMathHull::setBuffer(Buffer & buffer)
266 InsetMathGrid::setBuffer(buffer);
268 for (size_t i = 0; i != label_.size(); ++i) {
270 label_[i]->setBuffer(buffer);
275 // FIXME This should really be controlled by the TOC level, or
276 // something of the sort.
278 const char * counters_to_save[] = {"section", "chapter"};
279 unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
283 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
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 // if any of the equations are numbered, then we want to save the values
293 // of some of the counters.
295 BufferParams const & bp = buffer_->params();
296 string const & lang = it->getParLanguage(bp)->code();
298 buffer_->masterBuffer()->params().documentClass().counters();
300 // right now, we only need to do this at export time
301 if (utype == OutputUpdate) {
302 for (size_t i = 0; i < numcnts; ++i) {
303 docstring const cnt = from_ascii(counters_to_save[i]);
304 if (cnts.hasCounter(cnt))
305 counter_map[cnt] = cnts.value(cnt);
309 // this has to be done separately
310 docstring const eqstr = from_ascii("equation");
311 if (cnts.hasCounter(eqstr)) {
312 if (utype == OutputUpdate)
313 counter_map[eqstr] = cnts.value(eqstr);
314 for (size_t i = 0; i != label_.size(); ++i) {
316 Paragraph const & par = it.paragraph();
317 if (!par.isDeleted(it.pos())) {
318 cnts.step(eqstr, utype);
319 numbers_[i] = cnts.theCounter(eqstr, lang);
321 numbers_[i] = from_ascii("#");
323 numbers_[i] = empty_docstring();
329 for (size_t i = 0; i != label_.size(); ++i) {
331 label_[i]->updateBuffer(it, utype, deleted);
334 InsetMathGrid::updateBuffer(it, utype, deleted);
338 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active,
339 UpdateType utype, TocBackend & backend) const
342 //FIXME: buffer_ should be set at creation for this inset! Problem is
343 // This inset is created at too many places (see Parser::parse1() in
348 TocBuilder & b = backend.builder("equation");
349 // compute first and last item
350 row_type first = nrows();
351 for (row_type row = 0; row != nrows(); ++row)
356 if (first == nrows())
359 row_type last = nrows() - 1;
360 for (; last != 0; --last)
363 // add equation numbers
364 b.pushItem(pit, docstring(), output_active);
366 b.argumentItem(bformat(from_ascii("(%1$s-%2$s)"),
367 numbers_[first], numbers_[last]));
368 for (row_type row = 0; row != nrows(); ++row) {
372 label_[row]->addToToc(pit, output_active, utype, backend);
373 docstring label = nicelabel(row);
375 // this is the only equation
376 b.argumentItem(label);
378 // insert as sub-items
379 b.pushItem(pit, label, output_active);
387 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
389 if (previewState(&cur.bv())) {
393 return InsetMathNest::editXY(cur, x, y);
397 InsetMath::mode_type InsetMathHull::currentMode() const
401 return UNDECIDED_MODE;
403 // definitely math mode ...
423 // FIXME: InsetMathGrid should be changed to let the real column alignment be
424 // given by a virtual method like displayColAlign, because the values produced
425 // by defaultColAlign can be invalidated by lfuns such as add-column. For the
426 // moment the values produced by defaultColAlign are not used, notably because
427 // alignment is not implemented in the LyXHTML output.
428 char InsetMathHull::defaultColAlign(col_type col)
430 return colAlign(type_, col);
434 char InsetMathHull::displayColAlign(idx_type idx) const
438 row_type const r = row(idx);
441 if (r == nrows() - 1)
452 return colAlign(type_, col(idx));
456 return InsetMathGrid::displayColAlign(idx);
460 int InsetMathHull::displayColSpace(col_type col) const
462 return colSpace(type_, col);
466 // FIXME: same comment as for defaultColAlign applies.
467 int InsetMathHull::defaultColSpace(col_type col)
469 return colSpace(type_, col);
473 string InsetMathHull::standardFont() const
479 return "lyxnochange";
486 ColorCode InsetMathHull::standardColor() const
491 return Color_foreground;
499 bool InsetMathHull::previewState(const BufferView *const bv) const
501 if (!editing(bv) && RenderPreview::previewMath()
502 && type_ != hullRegexp)
504 graphics::PreviewImage const * pimage =
505 preview_->getPreviewImage(bv->buffer());
506 return pimage && pimage->image();
513 const int ERROR_FRAME_WIDTH = 2;
515 bool previewTooSmall(Dimension const & dim)
517 return dim.width() <= 10 && dim.height() <= 10;
522 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
524 /* Compute \(above|below)displayskip
525 true value in LaTeX is 10pt plus 2pt minus 5pt (in normal size at 10pt)
526 FIXME: make this dependent of current size? (minor improvement)
527 FIXME: if would be nice if this was not part of the inset, but
528 just increased the row ascent/descent.
529 FIXME: even better would be to handle the short skip case.
531 int const bottom_display_margin = mi.base.inPixels(Length(10, Length::PT));
532 int top_display_margin = bottom_display_margin;
533 // at start of paragraph, add an empty line
535 top_display_margin += theFontMetrics(mi.base.font).maxHeight() + 2;
537 if (previewState(mi.base.bv)) {
538 preview_->metrics(mi, dim);
539 if (previewTooSmall(dim)) {
540 // preview image is too small
541 dim.wid += 2 * ERROR_FRAME_WIDTH;
542 dim.asc += 2 * ERROR_FRAME_WIDTH;
544 // insert a gap in front of the formula
545 // value was hardcoded to 1 pixel
546 dim.wid += mi.base.bv->zoomedPixels(1) ;
548 dim.asc += top_display_margin;
549 dim.des += bottom_display_margin;
556 Changer dummy1 = mi.base.changeFontSet(standardFont());
557 Changer dummy2 = mi.base.font.changeStyle(display() ? DISPLAY_STYLE
560 // let the cells adjust themselves
561 InsetMathGrid::metrics(mi, dim);
564 // Check whether the numbering interferes with the equations
565 if (numberedType()) {
566 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
567 int extra_offset = 0;
568 for (row_type row = 0; row < nrows(); ++row) {
569 rowinfo(row).offset[mi.base.bv] += extra_offset;
572 docstring const nl = nicelabel(row);
574 mathed_string_dim(mi.base.font, nl, dimnl);
575 int const ind = indent(*mi.base.bv);
576 int const x = ind ? ind : (mi.base.textwidth - dim.wid) / 2;
577 // for some reason metrics does not trigger at the
578 // same point as draw, and therefore we use >= instead of >
579 if ((math_number == BufferParams::LEFT && dimnl.wid >= x)
580 || (math_number == BufferParams::RIGHT
581 && dimnl.wid >= mi.base.textwidth - x - dim.wid)) {
582 extra_offset += dimnl.height();
585 dim.des += extra_offset;
590 dim.asc += top_display_margin;
591 dim.des += bottom_display_margin;
594 // reserve some space for marker.
599 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
601 BufferView const * const bv = pi.base.bv;
602 if (previewState(bv)) {
603 Dimension const dim = dimension(*pi.base.bv);
604 if (previewTooSmall(dim))
606 return graphics::PreviewLoader::backgroundColor();
612 void InsetMathHull::drawMarkers(PainterInfo & pi, int x, int y) const
614 ColorCode pen_color = mouseHovered(pi.base.bv) || editing(pi.base.bv)?
615 Color_mathframe : Color_mathcorners;
616 // If the corners have the same color as the background, do not paint them.
617 if (lcolor.getX11HexName(Color_mathbg) == lcolor.getX11HexName(pen_color))
620 Inset::drawMarkers(pi, x, y);
621 Dimension const dim = dimension(*pi.base.bv);
622 int const t = x + dim.width() - 1;
623 int const a = y - dim.ascent();
624 pi.pain.line(x, a + 3, x, a, pen_color);
625 pi.pain.line(t, a + 3, t, a, pen_color);
626 pi.pain.line(x, a, x + 3, a, pen_color);
627 pi.pain.line(t - 3, a, t, a, pen_color);
631 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
633 Dimension const dim = dimension(*pi.base.bv);
634 if (previewTooSmall(dim)) {
635 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
636 dim.wid, dim.asc + dim.des, backgroundColor(pi));
639 // If there are numbers, the margins around the (displayed)
640 // equation have to be cleared.
642 pi.pain.fillRectangle(pi.leftx, y - dim.asc,
643 pi.rightx - pi.leftx, dim.height(), pi.background_color);
644 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
645 dim.asc + dim.des - 1, pi.backgroundColor(this));
649 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
651 BufferView const * const bv = pi.base.bv;
652 Dimension const dim = dimension(*bv);
654 if (type_ == hullRegexp)
655 pi.pain.rectangle(x + 2, y - dim.ascent() + 1,
656 dim.width() - 3, dim.height() - 2, Color_regexpframe);
658 if (previewState(bv)) {
659 // Do not draw change tracking cue if taken care of by RowPainter
661 Changer dummy = !canPaintChange(*bv) ? make_change(pi.change, Change())
663 if (previewTooSmall(dim)) {
664 // we have an extra frame
665 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
667 // one pixel gap in front
668 // value was hardcoded to 1 pixel
669 int const gap = pi.base.bv->zoomedPixels(1) ;
670 preview_->draw(pi, x + gap, y);
675 // First draw the numbers
676 ColorCode color = pi.selected && lyxrc.use_system_colors
677 ? Color_selectiontext : standardColor();
678 bool const really_change_color = pi.base.font.color() == Color_none;
679 Changer dummy0 = really_change_color ? pi.base.font.changeColor(color)
681 if (numberedType()) {
682 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
683 for (row_type row = 0; row < nrows(); ++row) {
684 int yy = y + rowinfo(row).offset[bv];
685 docstring const nl = nicelabel(row);
687 mathed_string_dim(pi.base.font, nl, dimnl);
688 if (math_number == BufferParams::LEFT) {
689 if (dimnl.wid > x - pi.leftx)
690 yy += rowinfo(row).descent + dimnl.asc;
691 pi.draw(pi.leftx, yy, nl);
693 if (dimnl.wid > pi.rightx - x - dim.wid)
694 yy += rowinfo(row).descent + dimnl.asc;
695 pi.draw(pi.rightx - dimnl.wid, yy, nl);
700 // Then the equations
701 Changer dummy1 = pi.base.changeFontSet(standardFont());
702 Changer dummy2 = pi.base.font.changeStyle(display() ? DISPLAY_STYLE
704 InsetMathGrid::draw(pi, x + 1, y);
705 drawMarkers(pi, x, y);
707 // drawing change line
708 if (canPaintChange(*bv)) {
710 int const display_margin = display() ? pi.base.inPixels(Length(12, Length::PT)) : 0;
711 pi.change.paintCue(pi, x + 1, y + 1 - dim.asc + display_margin,
712 x + dim.wid, y + dim.des - display_margin);
717 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
720 InsetMathGrid::metricsT(mi, dim);
723 otexrowstream ots(os);
724 WriteStream wi(ots, false, true, WriteStream::wsDefault);
726 dim.wid = os.str().size();
733 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
736 InsetMathGrid::drawT(pain, x, y);
739 otexrowstream ots(os);
740 WriteStream wi(ots, false, true, WriteStream::wsDefault);
742 pain.draw(x, y, os.str().c_str());
747 static docstring latexString(InsetMathHull const & inset)
750 // This has to be static, because a preview snippet or a math
751 // macro containing math in text mode (such as $\text{$\phi$}$ or
752 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
753 // first time as a whole, and the second time only the inner math.
754 // In this last case inset.buffer() would be invalid.
755 static Encoding const * encoding = 0;
756 if (inset.isBufferValid())
757 encoding = &(inset.buffer().params().encoding());
758 otexrowstream ots(ls);
759 WriteStream wi(ots, false, true, WriteStream::wsPreview, encoding);
765 void InsetMathHull::initUnicodeMath() const
767 // Trigger classification of the unicode symbols in this inset
768 docstring const dummy = latexString(*this);
772 void InsetMathHull::addPreview(DocIterator const & inset_pos,
773 graphics::PreviewLoader & /*ploader*/) const
775 if (RenderPreview::previewMath()) {
776 preparePreview(inset_pos);
781 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
782 MacroNameSet & macros, MacroNameSet & defs) const
784 MacroNameSet::iterator const end = macros.end();
786 for (size_t i = 0; i < md.size(); ++i) {
787 InsetMathMacro const * mi = md[i].nucleus()->asMacro();
788 InsetMathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
789 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
790 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
791 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
792 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
794 // Look for macros in the arguments of this macro.
795 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
796 usedMacros(mi->cell(idx), pos, macros, defs);
797 // Make sure this is a macro defined in the document
798 // (as we also spot the macros in the symbols file)
799 // or that we have not already accounted for it.
800 docstring const name = mi->name();
801 if (macros.find(name) == end)
804 // Look for macros in the definition of this macro.
805 MathData ar(pos.buffer());
806 MacroData const * data =
807 pos.buffer()->getMacro(name, pos, true);
809 odocstringstream macro_def;
810 data->write(macro_def, true);
812 defs.insert(macro_def.str());
813 asArray(data->definition(), ar);
815 usedMacros(ar, pos, macros, defs);
817 MathData ar(pos.buffer());
818 asArray(mt->definition(), ar);
819 usedMacros(ar, pos, macros, defs);
821 if (!si->nuc().empty())
822 usedMacros(si->nuc(), pos, macros, defs);
824 usedMacros(si->down(), pos, macros, defs);
826 usedMacros(si->up(), pos, macros, defs);
827 } else if (fi || gi) {
828 idx_type nidx = fi ? fi->nargs() : gi->nargs();
829 for (idx_type idx = 0; idx < nidx; ++idx)
830 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
833 usedMacros(ni->cell(0), pos, macros, defs);
839 void InsetMathHull::preparePreview(DocIterator const & pos,
840 bool forexport) const
842 // there is no need to do all the macro stuff if we're not
843 // actually going to generate the preview.
844 if (!RenderPreview::previewMath() && !forexport)
847 Buffer const * buffer = pos.buffer();
849 // collect macros at this position
851 buffer->listMacroNames(macros);
853 // collect definitions only for the macros used in this inset
855 for (idx_type idx = 0; idx < nargs(); ++idx)
856 usedMacros(cell(idx), pos, macros, defs);
858 docstring macro_preamble;
859 for (auto const & defvar : defs)
860 macro_preamble.append(defvar);
862 // set the font series and size for this snippet
863 DocIterator dit = pos.getInnerText();
864 Paragraph const & par = dit.paragraph();
865 Font font = par.getFontSettings(buffer->params(), dit.pos());
866 font.fontInfo().realize(par.layout().font);
867 string const lsize = font.latexSize();
870 if (font.fontInfo().series() == BOLD_SERIES) {
871 setfont += from_ascii("\\textbf{");
874 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
875 setfont += from_ascii("\\" + lsize + '\n');
878 if (forexport && haveNumbers()) {
879 docstring eqstr = from_ascii("equation");
880 CounterMap::const_iterator it = counter_map.find(eqstr);
881 if (it != counter_map.end()) {
882 int num = it->second;
884 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
885 '{' + convert<docstring>(num) + '}' + '\n';
887 for (size_t i = 0; i != numcnts; ++i) {
888 docstring cnt = from_ascii(counters_to_save[i]);
889 it = counter_map.find(cnt);
890 if (it == counter_map.end())
892 int num = it->second;
894 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
895 '{' + convert<docstring>(num) + '}';
898 docstring const snippet = macro_preamble + setfont + setcnt
899 + latexString(*this) + endfont;
900 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
901 preview_->addPreview(snippet, *buffer, forexport);
905 void InsetMathHull::reloadPreview(DocIterator const & pos) const
908 preview_->startLoading(*pos.buffer());
912 void InsetMathHull::loadPreview(DocIterator const & pos) const
914 bool const forexport = true;
915 preparePreview(pos, forexport);
916 preview_->startLoading(*pos.buffer(), forexport);
920 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
922 if (RenderPreview::previewMath()) {
924 cur.screenUpdateFlags(Update::Force);
930 docstring InsetMathHull::label(row_type row) const
932 LASSERT(row < nrows(), return docstring());
933 if (InsetLabel * il = label_[row])
934 return il->screenLabel();
939 void InsetMathHull::label(row_type row, docstring const & label)
941 //lyxerr << "setting label '" << label << "' for row " << row << endl;
945 label_[row] = dummy_pointer;
948 label_[row]->updateLabelAndRefs(label);
950 label_[row]->setParam("name", label);
954 InsetCommandParams p(LABEL_CODE);
956 label_[row] = new InsetLabel(buffer_, p);
958 label_[row]->setBuffer(buffer());
962 void InsetMathHull::numbered(row_type row, Numbered num)
964 numbered_[row] = num;
965 if (!numbered(row) && label_[row]) {
972 bool InsetMathHull::numbered(row_type row) const
974 return numbered_[row] == NUMBER;
978 bool InsetMathHull::ams() const
998 for (auto const & row : numbered_)
1005 bool InsetMathHull::outerDisplay() const
1028 Inset::RowFlags InsetMathHull::rowFlags() const
1045 if (buffer().params().is_math_indent)
1046 return Display | AlignLeft;
1055 int InsetMathHull::indent(BufferView const & bv) const
1057 // FIXME: set this in the textclass. This value is what the article class uses.
1058 static Length default_indent(2.5, Length::EM);
1059 if (display() && buffer().params().is_math_indent) {
1060 Length const & len = buffer().params().getMathIndent();
1062 return bv.inPixels(default_indent);
1064 return bv.inPixels(len);
1066 return Inset::indent(bv);
1070 bool InsetMathHull::numberedType() const
1089 for (row_type row = 0; row < nrows(); ++row)
1096 void InsetMathHull::validate(LaTeXFeatures & features) const
1098 if (features.runparams().isLaTeX()) {
1100 features.require("amsmath");
1102 if (type_ == hullRegexp) {
1103 features.require("color");
1104 docstring frcol = from_utf8(lcolor.getLaTeXName(Color_regexpframe));
1105 docstring bgcol = from_ascii("white");
1106 features.addPreambleSnippet(
1107 "\\newcommand{\\regexp}[1]{\\fcolorbox{"
1109 + bgcol + "}{\\ensuremath{\\mathtt{#1}}}}");
1110 features.addPreambleSnippet(
1111 from_ascii("\\newcommand{\\endregexp}{}"));
1112 } else if (outerDisplay() && features.inDeletedInset()) {
1113 features.require("tikz");
1114 features.require("ct-tikz-object-sout");
1117 // Validation is necessary only if not using AMS math.
1118 // To be safe, we will always run mathedvalidate.
1119 //if (features.amsstyle)
1122 //features.binom = true;
1123 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
1124 // it would be better to do this elsewhere, but we can't validate in
1125 // InsetMathMatrix and we have no way, outside MathExtern, to know if
1126 // we even have any matrices.
1127 features.addCSSSnippet(
1128 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
1129 "table.matrix td{padding: 0.25px;}\n"
1130 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
1131 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
1133 InsetMathGrid::validate(features);
1137 OutputParams::CtObject InsetMathHull::CtObject(OutputParams const & runparams) const
1139 OutputParams::CtObject res = OutputParams::CT_NORMAL;
1155 case hullMultline: {
1156 if (runparams.inulemcmd
1157 && (!runparams.local_font || runparams.local_font->fontInfo().strikeout() != FONT_ON))
1158 res = OutputParams::CT_UDISPLAYOBJECT;
1160 res = OutputParams::CT_DISPLAYOBJECT;
1168 void InsetMathHull::header_write(WriteStream & os) const
1170 bool n = numberedType();
1181 if (cell(0).empty())
1186 writeMathdisplayPreamble(os);
1190 os << "\\begin{equation" << star(n) << "}\n";
1200 writeMathdisplayPreamble(os);
1203 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1210 os << "\\begin{" << hullName(type_) << star(n) << '}'
1211 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1217 os << "\\begin{" << hullName(type_) << '}'
1218 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1228 os << "\\begin{unknown" << star(n) << "}\n";
1234 void InsetMathHull::footer_write(WriteStream & os) const
1236 bool n = numberedType();
1253 os << "\\end{equation" << star(n) << "}\n";
1256 writeMathdisplayPostamble(os);
1266 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1267 writeMathdisplayPostamble(os);
1274 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1280 os << "\\end{" << hullName(type_) << "}\n";
1284 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1285 os << "\\endregexp{}}";
1291 os << "\\end{unknown" << star(n) << "}\n";
1297 bool InsetMathHull::allowsTabularFeatures() const
1320 bool InsetMathHull::rowChangeOK() const
1323 type_ == hullEqnArray || type_ == hullAlign ||
1324 type_ == hullFlAlign || type_ == hullAlignAt ||
1325 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1326 type_ == hullGather || type_ == hullMultline;
1330 bool InsetMathHull::colChangeOK() const
1333 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1334 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1338 void InsetMathHull::addRow(row_type row)
1343 bool numbered = numberedType();
1344 // Move the number and raw pointer, do not call label() (bug 7511)
1345 InsetLabel * label = dummy_pointer;
1346 docstring number = empty_docstring();
1347 if (type_ == hullMultline) {
1348 if (row + 1 == nrows()) {
1349 numbered_[row] = NONUMBER;
1350 swap(label, label_[row]);
1351 swap(number, numbers_[row]);
1356 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1357 numbers_.insert(numbers_.begin() + row + 1, number);
1358 label_.insert(label_.begin() + row + 1, label);
1359 InsetMathGrid::addRow(row);
1363 void InsetMathHull::swapRow(row_type row)
1367 if (row + 1 == nrows())
1369 swap(numbered_[row], numbered_[row + 1]);
1370 swap(numbers_[row], numbers_[row + 1]);
1371 swap(label_[row], label_[row + 1]);
1372 InsetMathGrid::swapRow(row);
1376 void InsetMathHull::delRow(row_type row)
1378 if (nrows() <= 1 || !rowChangeOK())
1380 if (row + 1 == nrows() && type_ == hullMultline) {
1381 swap(numbered_[row - 1], numbered_[row]);
1382 swap(numbers_[row - 1], numbers_[row]);
1383 swap(label_[row - 1], label_[row]);
1384 InsetMathGrid::delRow(row);
1387 InsetMathGrid::delRow(row);
1388 // The last dummy row has no number info nor a label.
1389 // Test nrows() + 1 because we have already erased the row.
1390 if (row == nrows() + 1)
1392 numbered_.erase(numbered_.begin() + row);
1393 numbers_.erase(numbers_.begin() + row);
1395 label_.erase(label_.begin() + row);
1399 void InsetMathHull::addCol(col_type col)
1403 InsetMathGrid::addCol(col);
1407 void InsetMathHull::delCol(col_type col)
1409 if (ncols() <= 1 || !colChangeOK())
1411 InsetMathGrid::delCol(col);
1415 docstring InsetMathHull::nicelabel(row_type row) const
1419 docstring const & val = numbers_[row];
1421 return '(' + val + ')';
1422 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1426 void InsetMathHull::glueall(HullType type)
1429 for (idx_type i = 0; i < nargs(); ++i)
1431 InsetLabel * label = 0;
1432 if (type == hullEquation) {
1433 // preserve first non-empty label
1434 for (row_type row = 0; row < nrows(); ++row) {
1436 label = label_[row];
1442 *this = InsetMathHull(buffer_, hullSimple);
1449 void InsetMathHull::splitTo2Cols()
1451 LASSERT(ncols() == 1, return);
1452 InsetMathGrid::addCol(1);
1453 for (row_type row = 0; row < nrows(); ++row) {
1454 idx_type const i = 2 * row;
1455 pos_type pos = firstRelOp(cell(i));
1456 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1457 cell(i).erase(pos, cell(i).size());
1462 void InsetMathHull::splitTo3Cols()
1464 LASSERT(ncols() < 3, return);
1467 InsetMathGrid::addCol(2);
1468 for (row_type row = 0; row < nrows(); ++row) {
1469 idx_type const i = 3 * row + 1;
1470 if (!cell(i).empty()) {
1471 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1472 cell(i).erase(1, cell(i).size());
1478 void InsetMathHull::changeCols(col_type cols)
1480 if (ncols() == cols)
1482 else if (ncols() < cols) {
1488 while (ncols() < cols)
1489 InsetMathGrid::addCol(ncols());
1495 for (row_type row = 0; row < nrows(); ++row) {
1496 idx_type const i = row * ncols();
1497 for (col_type col = cols; col < ncols(); ++col) {
1498 cell(i + cols - 1).append(cell(i + col));
1502 while (ncols() > cols) {
1503 InsetMathGrid::delCol(ncols() - 1);
1508 HullType InsetMathHull::getType() const
1514 void InsetMathHull::setType(HullType type)
1521 bool InsetMathHull::isMutable(HullType type)
1545 void InsetMathHull::mutate(HullType newtype)
1547 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1549 if (newtype == type_)
1552 // This guards the algorithm below it, which is designed with certain types
1554 if (!isMutable(newtype) || !isMutable(type_)) {
1555 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1556 << "' to '" << to_utf8(hullName(newtype))
1557 << "' not implemented" << endl;
1561 // we try to move along the chain
1562 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1564 // +-------------------------------------+
1565 // we use eqnarray as intermediate type for mutations that are not
1566 // directly supported because it handles labels and numbering for
1571 setType(hullSimple);
1577 if (newtype == hullNone) {
1581 setType(hullEquation);
1582 numbered(0, label_[0] != nullptr);
1591 setType(hullSimple);
1596 // split it "nicely" on the first relop
1598 setType(hullEqnArray);
1606 // split it "nicely"
1641 setType(hullEqnArray);
1650 for (row_type row = 0; row < nrows(); ++row)
1651 numbered(row, false);
1661 for (row_type row = 0; row < nrows(); ++row)
1662 numbered(row, false);
1669 setType(hullEqnArray);
1699 for (row_type row = 0; row < nrows(); ++row)
1700 numbered(row, false);
1704 // first we mutate to EqnArray
1706 setType(hullEqnArray);
1713 // we passed the guard so we should not be here
1714 LYXERR0("Mutation not implemented, but should have been.");
1715 LASSERT(false, return);
1721 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1722 bool last_eoln) const
1725 if (numberedType()) {
1726 if (label_[row] && numbered(row)) {
1727 docstring const name =
1728 latex ? escape(label_[row]->getParam("name"))
1729 : label_[row]->getParam("name");
1730 res += "\\label{" + name + '}';
1732 if (type_ != hullMultline) {
1733 if (numbered_[row] == NONUMBER)
1734 res += "\\nonumber ";
1735 else if (numbered_[row] == NOTAG)
1739 // Never add \\ on the last empty line of eqnarray and friends
1741 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1744 void InsetMathHull::write(WriteStream & os) const
1746 ModeSpecifier specifier(os, MATH_MODE);
1748 InsetMathGrid::write(os);
1753 void InsetMathHull::normalize(NormalStream & os) const
1755 os << "[formula " << hullName(type_) << ' ';
1756 InsetMathGrid::normalize(os);
1761 void InsetMathHull::infoize(odocstream & os) const
1763 os << bformat(_("Type: %1$s"), hullName(type_));
1767 void InsetMathHull::check() const
1769 LATTEST(numbered_.size() == nrows());
1770 LATTEST(numbers_.size() == nrows());
1771 LATTEST(label_.size() == nrows());
1775 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1777 //FIXME: sort out whether we want std::string or docstring for those
1778 string const lang = func.getArg(0);
1779 docstring extra = from_utf8(func.getArg(1));
1781 extra = from_ascii("noextra");
1783 // replace selection with result of computation
1784 if (reduceSelectionToOneCell(cur)) {
1786 asArray(grabAndEraseSelection(cur), ar);
1787 lyxerr << "use selection: " << ar << endl;
1788 cur.insert(pipeThroughExtern(lang, extra, ar));
1792 // only inline, display or eqnarray math is allowed
1793 switch (getType()) {
1799 frontend::Alert::warning(_("Bad math environment"),
1800 _("Computation cannot be performed for AMS "
1801 "math environments.\nChange the math "
1802 "formula type and try again."));
1807 eq.push_back(MathAtom(new InsetMathChar('=')));
1809 // go to first item in line
1810 cur.idx() -= cur.idx() % ncols();
1813 if (getType() == hullSimple) {
1814 size_type pos = cur.cell().find_last(eq);
1816 if (pos == cur.cell().size()) {
1818 lyxerr << "use whole cell: " << ar << endl;
1820 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1821 lyxerr << "use partial cell form pos: " << pos << endl;
1823 cur.cell().append(eq);
1824 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1825 cur.pos() = cur.lastpos();
1829 if (getType() == hullEquation) {
1830 lyxerr << "use equation inset" << endl;
1831 mutate(hullEqnArray);
1832 MathData & ar = cur.cell();
1833 lyxerr << "use cell: " << ar << endl;
1837 cur.cell() = pipeThroughExtern(lang, extra, ar);
1838 // move to end of line
1839 cur.pos() = cur.lastpos();
1844 lyxerr << "use eqnarray" << endl;
1845 cur.idx() += 2 - cur.idx() % ncols();
1847 MathData ar = cur.cell();
1848 lyxerr << "use cell: " << ar << endl;
1849 // FIXME: temporarily disabled
1855 cur.cell() = pipeThroughExtern(lang, extra, ar);
1856 cur.pos() = cur.lastpos();
1861 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1863 //lyxerr << "action: " << cmd.action() << endl;
1864 switch (cmd.action()) {
1866 case LFUN_FINISHED_BACKWARD:
1867 case LFUN_FINISHED_FORWARD:
1868 case LFUN_FINISHED_RIGHT:
1869 case LFUN_FINISHED_LEFT:
1870 //lyxerr << "action: " << cmd.action() << endl;
1871 InsetMathGrid::doDispatch(cur, cmd);
1874 case LFUN_PARAGRAPH_BREAK:
1875 // just swallow this
1878 case LFUN_NEWLINE_INSERT:
1879 // some magic for the common case
1880 if (type_ == hullSimple || type_ == hullEquation) {
1881 cur.recordUndoInset();
1883 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1884 mutate(align ? hullAlign : hullEqnArray);
1885 // mutate() may change labels and such.
1886 cur.forceBufferUpdate();
1887 cur.idx() = nrows() * ncols() - 1;
1888 cur.pos() = cur.lastpos();
1890 InsetMathGrid::doDispatch(cur, cmd);
1893 case LFUN_MATH_NUMBER_TOGGLE: {
1894 //lyxerr << "toggling all numbers" << endl;
1895 cur.recordUndoInset();
1896 bool old = numberedType();
1897 if (type_ == hullMultline)
1898 numbered(nrows() - 1, !old);
1900 for (row_type row = 0; row < nrows(); ++row)
1901 numbered(row, !old);
1903 cur.message(old ? _("No number") : _("Number"));
1904 cur.forceBufferUpdate();
1908 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1909 cur.recordUndoInset();
1910 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1911 bool old = numbered(r);
1912 cur.message(old ? _("No number") : _("Number"));
1914 cur.forceBufferUpdate();
1918 case LFUN_LABEL_INSERT: {
1919 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1920 docstring old_label = label(r);
1921 docstring const default_label = from_ascii("eq:");
1922 if (old_label.empty())
1923 old_label = default_label;
1925 InsetCommandParams p(LABEL_CODE);
1926 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1927 string const data = InsetCommand::params2string(p);
1929 if (cmd.argument().empty())
1930 cur.bv().showDialog("label", data);
1932 FuncRequest fr(LFUN_INSET_INSERT, data);
1938 case LFUN_LABEL_COPY_AS_REFERENCE: {
1940 if (cmd.argument().empty() && &cur.inset() == this)
1941 // if there is no argument and we're inside math, we retrieve
1942 // the row number from the cursor position.
1943 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1945 // if there is an argument, find the corresponding label, else
1946 // check whether there is at least one label.
1947 for (row = 0; row != nrows(); ++row)
1948 if (numbered(row) && label_[row]
1949 && (cmd.argument().empty() || label(row) == cmd.argument()))
1956 InsetCommandParams p(REF_CODE, "ref");
1957 p["reference"] = label(row);
1958 cap::clearSelection();
1959 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1963 case LFUN_WORD_DELETE_FORWARD:
1964 case LFUN_CHAR_DELETE_FORWARD:
1965 if (col(cur.idx()) + 1 == ncols()
1966 && cur.pos() == cur.lastpos()
1967 && !cur.selection()) {
1968 if (!label(row(cur.idx())).empty()) {
1969 cur.recordUndoInset();
1970 label(row(cur.idx()), docstring());
1971 } else if (numbered(row(cur.idx()))) {
1972 cur.recordUndoInset();
1973 numbered(row(cur.idx()), false);
1974 cur.forceBufferUpdate();
1976 InsetMathGrid::doDispatch(cur, cmd);
1980 InsetMathGrid::doDispatch(cur, cmd);
1985 case LFUN_INSET_INSERT: {
1986 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1987 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1988 string const name = cmd.getArg(0);
1989 if (name == "label") {
1990 InsetCommandParams p(LABEL_CODE);
1991 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1992 docstring str = p["name"];
1993 cur.recordUndoInset();
1994 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1998 docstring old = label(r);
2001 // The label will take care of the reference update.
2005 // Newly created inset so initialize it.
2006 label_[r]->initView();
2009 cur.forceBufferUpdate();
2012 InsetMathGrid::doDispatch(cur, cmd);
2016 case LFUN_MATH_EXTERN:
2017 cur.recordUndoInset();
2021 case LFUN_MATH_MUTATE: {
2022 cur.recordUndoInset();
2023 row_type row = cur.row();
2024 col_type col = cur.col();
2025 mutate(hullType(cmd.argument()));
2026 cur.idx() = row * ncols() + col;
2027 if (cur.idx() > cur.lastidx()) {
2028 cur.idx() = cur.lastidx();
2029 cur.pos() = cur.lastpos();
2031 if (cur.pos() > cur.lastpos())
2032 cur.pos() = cur.lastpos();
2034 cur.forceBufferUpdate();
2035 // FIXME: find some more clever handling of the selection,
2036 // i.e. preserve it.
2037 cur.clearSelection();
2038 //cur.dispatched(FINISHED);
2042 case LFUN_MATH_DISPLAY: {
2043 cur.recordUndoInset();
2044 mutate(type_ == hullSimple ? hullEquation : hullSimple);
2045 // if the cursor is in a cell that got merged, move it to
2046 // start of the hull inset.
2047 if (cur.idx() > 0) {
2051 if (cur.pos() > cur.lastpos())
2052 cur.pos() = cur.lastpos();
2057 case LFUN_TABULAR_FEATURE:
2058 if (!allowsTabularFeatures())
2061 InsetMathGrid::doDispatch(cur, cmd);
2065 InsetMathGrid::doDispatch(cur, cmd);
2073 bool allowDisplayMath(Cursor const & cur)
2075 LATTEST(cur.depth() > 1);
2076 Cursor tmpcur = cur;
2079 FuncRequest cmd(LFUN_MATH_DISPLAY);
2080 return tmpcur.getStatus(cmd, status) && status.enabled();
2086 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
2087 FuncStatus & status) const
2089 switch (cmd.action()) {
2090 case LFUN_FINISHED_BACKWARD:
2091 case LFUN_FINISHED_FORWARD:
2092 case LFUN_FINISHED_RIGHT:
2093 case LFUN_FINISHED_LEFT:
2096 case LFUN_NEWLINE_INSERT:
2097 case LFUN_MATH_EXTERN:
2099 status.setEnabled(true);
2102 // we never allow this in math, and we want to bind enter
2103 // to another actions in command-alternatives
2104 case LFUN_PARAGRAPH_BREAK:
2105 status.setEnabled(false);
2107 case LFUN_MATH_MUTATE: {
2108 HullType const ht = hullType(cmd.argument());
2109 status.setOnOff(type_ == ht);
2110 status.setEnabled(isMutable(ht) && isMutable(type_));
2112 if (ht != hullSimple && status.enabled())
2113 status.setEnabled(allowDisplayMath(cur));
2116 case LFUN_MATH_DISPLAY: {
2117 status.setEnabled(display() || allowDisplayMath(cur));
2118 status.setOnOff(display());
2122 case LFUN_MATH_NUMBER_TOGGLE:
2123 // FIXME: what is the right test, this or the one of
2125 status.setEnabled(display());
2126 status.setOnOff(numberedType());
2129 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
2130 // FIXME: what is the right test, this or the one of
2132 bool const enable = (type_ == hullMultline)
2133 ? (nrows() - 1 == cur.row())
2135 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2136 status.setEnabled(enable);
2137 status.setOnOff(enable && numbered(r));
2141 case LFUN_LABEL_INSERT:
2142 status.setEnabled(type_ != hullSimple);
2145 case LFUN_LABEL_COPY_AS_REFERENCE: {
2146 bool enabled = false;
2147 if (cmd.argument().empty() && &cur.inset() == this) {
2148 // if there is no argument and we're inside math, we retrieve
2149 // the row number from the cursor position.
2150 row_type row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2151 enabled = numberedType() && label_[row] && numbered(row);
2153 // if there is an argument, find the corresponding label, else
2154 // check whether there is at least one label.
2155 for (row_type row = 0; row != nrows(); ++row) {
2156 if (numbered(row) && label_[row] &&
2157 (cmd.argument().empty() || label(row) == cmd.argument())) {
2163 status.setEnabled(enabled);
2167 case LFUN_INSET_INSERT:
2168 if (cmd.getArg(0) == "label") {
2169 status.setEnabled(type_ != hullSimple);
2172 return InsetMathGrid::getStatus(cur, cmd, status);
2174 case LFUN_TABULAR_FEATURE: {
2175 if (!allowsTabularFeatures())
2177 string s = cmd.getArg(0);
2179 && (s == "append-row"
2180 || s == "delete-row"
2181 || s == "copy-row")) {
2182 status.message(bformat(
2183 from_utf8(N_("Can't change number of rows in '%1$s'")),
2185 status.setEnabled(false);
2189 && (s == "append-column"
2190 || s == "delete-column"
2191 || s == "copy-column")) {
2192 status.message(bformat(
2193 from_utf8(N_("Can't change number of columns in '%1$s'")),
2195 status.setEnabled(false);
2198 if (s == "add-vline-left" || s == "add-vline-right") {
2199 status.message(bformat(
2200 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2202 status.setEnabled(false);
2205 if (s == "valign-top" || s == "valign-middle"
2206 || s == "valign-bottom" || s == "align-left"
2207 || s == "align-center" || s == "align-right") {
2208 status.setEnabled(false);
2211 return InsetMathGrid::getStatus(cur, cmd, status);
2215 return InsetMathGrid::getStatus(cur, cmd, status);
2220 int InsetMathHull::leftMargin() const
2222 return (getType() == hullSimple) ? 0 : InsetMathGrid::leftMargin();
2226 int InsetMathHull::rightMargin() const
2228 return (getType() == hullSimple) ? 0 : InsetMathGrid::rightMargin();
2232 int InsetMathHull::border() const
2234 return (getType() == hullSimple) ? 0 : InsetMathGrid::border();
2238 /////////////////////////////////////////////////////////////////////
2242 // simply scrap this function if you want
2243 void InsetMathHull::mutateToText()
2246 // translate to latex
2248 latex(os, false, false);
2249 string str = os.str();
2252 Text * lt = view_->cursor().innerText();
2253 string::const_iterator cit = str.begin();
2254 string::const_iterator end = str.end();
2255 for (; cit != end; ++cit)
2256 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2259 //dispatch(LFUN_ESCAPE);
2264 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2265 docstring const & font)
2267 // this whole function is a hack and won't work for incremental font
2270 if (cur.inset().asInsetMath()->name() == font)
2271 cur.handleFont(to_utf8(font));
2273 cur.handleNest(createInsetMath(font, cur.buffer()));
2279 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2284 font.fromString(to_utf8(arg), b);
2285 if (font.fontInfo().color() != Color_inherit) {
2286 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2292 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2294 InsetMathNest::edit(cur, front, entry_from);
2295 // The inset formula dimension is not necessarily the same as the
2296 // one of the instant preview image, so we have to indicate to the
2297 // BufferView that a metrics update is needed.
2298 cur.screenUpdateFlags(Update::Force);
2302 /////////////////////////////////////////////////////////////////////
2306 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2309 // FIXME: completely broken
2310 static InsetMathHull * lastformula = 0;
2311 static CursorBase current = DocIterator(ibegin(nucleus()));
2313 static string laststr;
2315 if (lastformula != this || laststr != str) {
2316 //lyxerr << "reset lastformula to " << this << endl;
2319 current = ibegin(nucleus());
2321 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2325 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2327 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2328 CursorSlice & top = it.back();
2329 MathData const & a = top.asInsetMath()->cell(top.idx_);
2330 if (a.matchpart(ar, top.pos_)) {
2331 bv->cursor().setSelection(it, ar.size());
2333 top.pos_ += ar.size();
2339 //lyxerr << "not found!" << endl;
2346 void InsetMathHull::write(ostream & os) const
2348 odocstringstream oss;
2349 otexrowstream ots(oss);
2350 WriteStream wi(ots, false, false, WriteStream::wsDefault);
2353 os << to_utf8(oss.str());
2357 void InsetMathHull::read(Lexer & lex)
2360 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2361 operator=(*at->asHullInset());
2365 bool InsetMathHull::readQuiet(Lexer & lex)
2368 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2370 operator=(*at->asHullInset());
2375 int InsetMathHull::plaintext(odocstringstream & os,
2376 OutputParams const & op, size_t max_length) const
2378 // Try enabling this now that there is a flag as requested at #2275.
2379 if (buffer().isExporting() && display()) {
2383 TextPainter tpain(dim.width(), dim.height());
2384 drawT(tpain, 0, dim.ascent());
2386 // reset metrics cache to "real" values
2388 return tpain.textheight();
2391 odocstringstream oss;
2392 otexrowstream ots(oss);
2393 Encoding const * const enc = encodings.fromLyXName("utf8");
2394 WriteStream wi(ots, false, true, WriteStream::wsDefault, enc);
2397 if (type_ == hullRegexp)
2400 for (row_type r = 0; r < nrows(); ++r) {
2401 for (col_type c = 0; c < ncols(); ++c)
2402 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2403 // if it's for the TOC, we write just the first line
2404 // and do not include the newline.
2405 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2407 if (r < nrows() - 1)
2411 docstring const str = oss.str();
2417 void InsetMathHull::docbook(XMLStream & xs, OutputParams const & runparams) const
2419 // Choose the tag around the MathML equation.
2422 if (getType() == hullSimple)
2423 name = from_ascii("inlineequation");
2425 doCR = true; // This is a block equation, always have <informalequation> on its own line.
2426 name = from_ascii("informalequation");
2429 // DocBook also has <equation>, but it comes with a title.
2430 // TODO: recognise \tag from amsmath? This would allow having <equation> with a proper title.
2433 for (row_type i = 0; i < nrows(); ++i) {
2434 if (!label(i).empty()) {
2435 attr = "xml:id=\"" + xml::cleanID(label(i)) + "\"";
2441 if (!xs.isLastTagCR())
2444 xs << xml::StartTag(name, attr);
2447 // With DocBook 5, MathML must be within its own namespace; defined in Buffer.cpp::writeDocBookSource as "m".
2448 // Output everything in a separate stream so that this does not interfere with the standard flow of DocBook tags.
2449 odocstringstream osmath;
2450 MathStream ms(osmath, "m", true);
2452 // Output the MathML subtree.
2453 odocstringstream ls;
2456 // TeX transcription. Avoid MTag/ETag so that there are no extraneous spaces.
2457 ms << "<" << from_ascii("alt") << " role='tex'" << ">";
2458 // Workaround for db2latex: db2latex always includes equations with
2459 // \ensuremath{} or \begin{display}\end{display}
2460 // so we strip LyX' math environment
2461 WriteStream wi(ols, false, false, WriteStream::wsDefault, runparams.encoding);
2462 InsetMathGrid::write(wi);
2463 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2464 ms << "</" << from_ascii("alt") << ">";
2466 // Actual transformation of the formula into MathML. This translation may fail (for example, due to custom macros).
2467 // The new output stream is required to deal with the errors: first write completely the formula into this
2468 // temporary stream; then, if it is possible without error, then copy it back to the "real" stream. Otherwise,
2469 // some incomplete tags might be put into the real stream.
2471 // First, generate the MathML expression.
2472 odocstringstream ostmp;
2473 MathStream mstmp(ostmp, ms.xmlns(), ms.xmlMode());
2474 InsetMathGrid::mathmlize(mstmp);
2476 // Then, output it (but only if the generation can be done without errors!).
2479 osmath << ostmp.str(); // osmath is not a XMLStream, so no need for XMLStream::ESCAPE_NONE.
2481 } catch (MathExportException const &) {
2483 osmath << "<mathphrase>MathML export failed. Please report this as a bug.</mathphrase>";
2486 // Output the complete formula to the DocBook stream.
2487 xs << XMLStream::ESCAPE_NONE << osmath.str();
2489 xs << xml::EndTag(name);
2495 bool InsetMathHull::haveNumbers() const
2497 bool havenumbers = false;
2498 // inline formulas are never numbered (bug 7351 part 3)
2499 if (getType() == hullSimple)
2501 for (size_t i = 0; i != numbered_.size(); ++i) {
2512 // We need to do something about alignment here.
2514 // This duplicates code from InsetMathGrid, but
2515 // we need access here to number information,
2516 // and we simply do not have that in InsetMathGrid.
2517 void InsetMathHull::htmlize(HtmlStream & os) const
2519 bool const havenumbers = haveNumbers();
2520 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2523 os << cell(index(0, 0));
2527 os << MTag("table", "class='mathtable'");
2528 for (row_type row = 0; row < nrows(); ++row) {
2530 for (col_type col = 0; col < ncols(); ++col) {
2532 os << cell(index(row, col));
2537 docstring const & num = numbers_[row];
2539 os << '(' << num << ')';
2544 os << ETag("table");
2548 // this duplicates code from InsetMathGrid, but
2549 // we need access here to number information,
2550 // and we simply do not have that in InsetMathGrid.
2551 void InsetMathHull::mathmlize(MathStream & ms) const
2553 bool const havenumbers = haveNumbers();
2554 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2557 ms << MTag("mtable");
2558 char const * const celltag = havetable ? "mtd" : "mrow";
2559 // FIXME There does not seem to be wide support at the moment
2560 // for mlabeledtr, so we have to use just mtr for now.
2561 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2562 char const * const rowtag = "mtr";
2563 for (row_type row = 0; row < nrows(); ++row) {
2566 for (col_type col = 0; col < ncols(); ++col) {
2568 << cell(index(row, col))
2574 docstring const & num = numbers_[row];
2576 ms << '(' << num << ')';
2583 ms << ETag("mtable");
2587 void InsetMathHull::mathAsLatex(WriteStream & os) const
2589 MathEnsurer ensurer(os, false);
2590 bool havenumbers = haveNumbers();
2591 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2594 os << cell(index(0, 0));
2598 os << "<table class='mathtable'>";
2599 for (row_type row = 0; row < nrows(); ++row) {
2601 for (col_type col = 0; col < ncols(); ++col) {
2602 os << "<td class='math'>";
2603 os << cell(index(row, col));
2608 docstring const & num = numbers_[row];
2610 os << '(' << num << ')';
2619 docstring InsetMathHull::xhtml(XMLStream & xs, OutputParams const & op) const
2621 BufferParams::MathOutput const mathtype =
2622 buffer().masterBuffer()->params().html_math_output;
2624 bool success = false;
2626 // we output all the labels just at the beginning of the equation.
2627 // this should be fine.
2628 for (size_t i = 0; i != label_.size(); ++i) {
2629 InsetLabel const * const il = label_[i];
2635 // FIXME Eventually we would like to do this inset by inset.
2636 if (mathtype == BufferParams::MathML) {
2637 odocstringstream os;
2642 } catch (MathExportException const &) {}
2644 if (getType() == hullSimple)
2645 xs << xml::StartTag("math",
2646 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2648 xs << xml::StartTag("math",
2649 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2650 xs << XMLStream::ESCAPE_NONE
2652 << xml::EndTag("math");
2654 } else if (mathtype == BufferParams::HTML) {
2655 odocstringstream os;
2660 } catch (MathExportException const &) {}
2662 string const tag = (getType() == hullSimple) ? "span" : "div";
2663 xs << xml::StartTag(tag, "class='formula'", true)
2664 << XMLStream::ESCAPE_NONE
2666 << xml::EndTag(tag);
2670 // what we actually want is this:
2672 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2674 // || mathtype == BufferParams::Images
2676 // but what follows is equivalent, since we'll enter only if either (a) we
2677 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2678 // aren't doing LaTeX.
2680 // so this is for Images.
2681 if (!success && mathtype != BufferParams::LaTeX) {
2682 graphics::PreviewImage const * pimage = 0;
2684 loadPreview(docit_);
2685 pimage = preview_->getPreviewImage(buffer());
2686 // FIXME Do we always have png?
2689 if (pimage || op.dryrun) {
2690 string const filename = pimage ? pimage->filename().onlyFileName()
2691 : "previewimage.png";
2693 // if we are not in the master buffer, then we need to see that the
2694 // generated image is copied there; otherwise, preview fails.
2695 Buffer const * mbuf = buffer().masterBuffer();
2696 if (mbuf != &buffer()) {
2697 string mbtmp = mbuf->temppath();
2698 FileName const mbufimg(support::addName(mbtmp, filename));
2699 pimage->filename().copyTo(mbufimg);
2701 // add the file to the list of files to be exported
2702 op.exportdata->addExternalFile("xhtml", pimage->filename());
2705 string const tag = (getType() == hullSimple) ? "span" : "div";
2707 << xml::StartTag(tag, "style = \"text-align: center;\"")
2708 << xml::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2715 // so we'll pass this test if we've failed everything else, or
2716 // if mathtype was LaTeX, since we won't have entered any of the
2718 if (!success /* || mathtype != BufferParams::LaTeX */) {
2719 // Unfortunately, we cannot use latexString() because we do not want
2720 // $...$ or whatever.
2721 odocstringstream ls;
2722 otexrowstream ots(ls);
2723 WriteStream wi(ots, false, true, WriteStream::wsPreview);
2724 ModeSpecifier specifier(wi, MATH_MODE);
2726 docstring const latex = ls.str();
2728 // class='math' allows for use of jsMath
2729 // http://www.math.union.edu/~dpvc/jsMath/
2731 // probably should allow for some kind of customization here
2732 string const tag = (getType() == hullSimple) ? "span" : "div";
2733 xs << xml::StartTag(tag, "class='math'")
2742 void InsetMathHull::toString(odocstream & os) const
2744 odocstringstream ods;
2745 plaintext(ods, OutputParams(0));
2750 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2752 odocstringstream ods;
2755 // FIXME: this results in spilling TeX into the LyXHTML output since the
2756 // outliner is used to generate the LyXHTML list of figures/etc.
2762 string InsetMathHull::contextMenuName() const
2764 return "context-math";
2768 void InsetMathHull::recordLocation(DocIterator const & di)
2774 bool InsetMathHull::canPaintChange(BufferView const &) const
2776 // We let RowPainter do it seamlessly for inline insets