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"
43 #include "Paragraph.h"
44 #include "ParIterator.h"
47 #include "TextClass.h"
48 #include "TextPainter.h"
49 #include "TocBackend.h"
51 #include "insets/InsetLabel.h"
52 #include "insets/InsetRef.h"
53 #include "insets/RenderPreview.h"
55 #include "graphics/GraphicsImage.h"
56 #include "graphics/PreviewImage.h"
57 #include "graphics/PreviewLoader.h"
59 #include "frontends/alert.h"
60 #include "frontends/FontMetrics.h"
61 #include "frontends/Painter.h"
63 #include "support/convert.h"
64 #include "support/debug.h"
65 #include "support/gettext.h"
66 #include "support/filetools.h"
67 #include "support/lassert.h"
68 #include "support/lstrings.h"
69 #include "support/RefChanger.h"
74 using namespace lyx::support;
78 using cap::grabAndEraseSelection;
79 using cap::reduceSelectionToOneCell;
83 int getCols(HullType type)
108 // returns position of first relation operator in the array
109 // used for "intelligent splitting"
110 size_t firstRelOp(MathData const & ar)
112 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
113 if ((*it)->mathClass() == MC_REL)
114 return it - ar.begin();
119 char const * star(bool numbered)
121 return numbered ? "" : "*";
125 // writes a preamble for underlined or struck out math display
126 void writeMathdisplayPreamble(WriteStream & os)
128 if (os.strikeoutMath())
131 if (os.ulemCmd() == WriteStream::UNDERLINE)
132 os << "\\raisebox{-\\belowdisplayshortskip}{"
133 "\\parbox[b]{\\linewidth}{";
134 else if (os.ulemCmd() == WriteStream::STRIKEOUT)
135 os << "\\parbox{\\linewidth}{";
139 // writes a postamble for underlined or struck out math display
140 void writeMathdisplayPostamble(WriteStream & os)
142 if (os.strikeoutMath())
145 if (os.ulemCmd() == WriteStream::UNDERLINE)
147 else if (os.ulemCmd() == WriteStream::STRIKEOUT)
155 HullType hullType(docstring const & s)
157 if (s == "none") return hullNone;
158 if (s == "simple") return hullSimple;
159 if (s == "equation") return hullEquation;
160 if (s == "eqnarray") return hullEqnArray;
161 if (s == "align") return hullAlign;
162 if (s == "alignat") return hullAlignAt;
163 if (s == "xalignat") return hullXAlignAt;
164 if (s == "xxalignat") return hullXXAlignAt;
165 if (s == "multline") return hullMultline;
166 if (s == "gather") return hullGather;
167 if (s == "flalign") return hullFlAlign;
168 if (s == "regexp") return hullRegexp;
169 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
174 docstring hullName(HullType type)
177 case hullNone: return from_ascii("none");
178 case hullSimple: return from_ascii("simple");
179 case hullEquation: return from_ascii("equation");
180 case hullEqnArray: return from_ascii("eqnarray");
181 case hullAlign: return from_ascii("align");
182 case hullAlignAt: return from_ascii("alignat");
183 case hullXAlignAt: return from_ascii("xalignat");
184 case hullXXAlignAt: return from_ascii("xxalignat");
185 case hullMultline: return from_ascii("multline");
186 case hullGather: return from_ascii("gather");
187 case hullFlAlign: return from_ascii("flalign");
188 case hullRegexp: return from_ascii("regexp");
190 lyxerr << "unknown hull type" << endl;
193 return from_ascii("none");
196 static InsetLabel * dummy_pointer = 0;
198 InsetMathHull::InsetMathHull(Buffer * buf)
199 : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, NONUMBER),
200 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
201 preview_(new RenderPreview(this))
203 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
204 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
205 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
206 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
213 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
214 : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, NONUMBER),
215 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
216 preview_(new RenderPreview(this))
224 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
230 InsetMathHull::~InsetMathHull()
232 for (auto & i : label_)
237 Inset * InsetMathHull::clone() const
239 return new InsetMathHull(*this);
243 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
247 InsetMathGrid::operator=(other);
249 numbered_ = other.numbered_;
250 numbers_ = other.numbers_;
251 buffer_ = other.buffer_;
252 for (auto & i : label_)
254 label_ = other.label_;
255 for (size_t i = 0; i != label_.size(); ++i) {
257 label_[i] = new InsetLabel(*label_[i]);
259 preview_.reset(new RenderPreview(*other.preview_, this));
265 void InsetMathHull::setBuffer(Buffer & buffer)
267 InsetMathGrid::setBuffer(buffer);
269 for (size_t i = 0; i != label_.size(); ++i) {
271 label_[i]->setBuffer(buffer);
276 // FIXME This should really be controlled by the TOC level, or
277 // something of the sort.
279 const char * counters_to_save[] = {"section", "chapter"};
280 unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
284 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
287 //FIXME: buffer_ should be set at creation for this inset! Problem is
288 // This inset is created at too many places (see Parser::parse1() in
293 // if any of the equations are numbered, then we want to save the values
294 // of some of the counters.
296 BufferParams const & bp = buffer_->params();
297 string const & lang = it->getParLanguage(bp)->code();
299 buffer_->masterBuffer()->params().documentClass().counters();
301 // right now, we only need to do this at export time
302 if (utype == OutputUpdate) {
303 for (size_t i = 0; i < numcnts; ++i) {
304 docstring const cnt = from_ascii(counters_to_save[i]);
305 if (cnts.hasCounter(cnt))
306 counter_map[cnt] = cnts.value(cnt);
310 // this has to be done separately
311 docstring const eqstr = from_ascii("equation");
312 if (cnts.hasCounter(eqstr)) {
313 if (utype == OutputUpdate)
314 counter_map[eqstr] = cnts.value(eqstr);
315 for (size_t i = 0; i != label_.size(); ++i) {
317 Paragraph const & par = it.paragraph();
318 if (!par.isDeleted(it.pos())) {
319 cnts.step(eqstr, utype);
320 numbers_[i] = cnts.theCounter(eqstr, lang);
322 numbers_[i] = from_ascii("#");
324 numbers_[i] = empty_docstring();
330 for (size_t i = 0; i != label_.size(); ++i) {
332 label_[i]->updateBuffer(it, utype, deleted);
335 InsetMathGrid::updateBuffer(it, utype, deleted);
339 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active,
340 UpdateType utype, TocBackend & backend) const
343 //FIXME: buffer_ should be set at creation for this inset! Problem is
344 // This inset is created at too many places (see Parser::parse1() in
349 TocBuilder & b = backend.builder("equation");
350 // compute first and last item
351 row_type first = nrows();
352 for (row_type row = 0; row != nrows(); ++row)
357 if (first == nrows())
360 row_type last = nrows() - 1;
361 for (; last != 0; --last)
364 // add equation numbers
365 b.pushItem(pit, docstring(), output_active);
367 b.argumentItem(bformat(from_ascii("(%1$s-%2$s)"),
368 numbers_[first], numbers_[last]));
369 for (row_type row = 0; row != nrows(); ++row) {
373 label_[row]->addToToc(pit, output_active, utype, backend);
374 docstring label = nicelabel(row);
376 // this is the only equation
377 b.argumentItem(label);
379 // insert as sub-items
380 b.pushItem(pit, label, output_active);
388 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
390 if (previewState(&cur.bv())) {
394 return InsetMathNest::editXY(cur, x, y);
398 InsetMath::mode_type InsetMathHull::currentMode() const
402 return UNDECIDED_MODE;
404 // definitely math mode ...
424 // FIXME: InsetMathGrid should be changed to let the real column alignment be
425 // given by a virtual method like displayColAlign, because the values produced
426 // by defaultColAlign can be invalidated by lfuns such as add-column. For the
427 // moment the values produced by defaultColAlign are not used, notably because
428 // alignment is not implemented in the LyXHTML output.
429 char InsetMathHull::defaultColAlign(col_type col)
431 return colAlign(type_, col);
435 char InsetMathHull::displayColAlign(idx_type idx) const
439 row_type const r = row(idx);
442 if (r == nrows() - 1)
453 return colAlign(type_, col(idx));
457 return InsetMathGrid::displayColAlign(idx);
461 int InsetMathHull::displayColSpace(col_type col) const
463 return colSpace(type_, col);
467 // FIXME: same comment as for defaultColAlign applies.
468 int InsetMathHull::defaultColSpace(col_type col)
470 return colSpace(type_, col);
474 string InsetMathHull::standardFont() const
480 return "lyxnochange";
487 ColorCode InsetMathHull::standardColor() const
492 return Color_foreground;
500 bool InsetMathHull::previewState(const BufferView *const bv) const
502 if (!editing(bv) && RenderPreview::previewMath()
503 && type_ != hullRegexp)
505 graphics::PreviewImage const * pimage =
506 preview_->getPreviewImage(bv->buffer());
507 return pimage && pimage->image();
514 const int ERROR_FRAME_WIDTH = 2;
516 bool previewTooSmall(Dimension const & dim)
518 return dim.width() <= 10 && dim.height() <= 10;
523 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
525 /* Compute \(above|below)displayskip
526 true value in LaTeX is 10pt plus 2pt minus 5pt (in normal size at 10pt)
527 FIXME: make this dependent of current size? (minor improvement)
528 FIXME: if would be nice if this was not part of the inset, but
529 just increased the row ascent/descent.
530 FIXME: even better would be to handle the short skip case.
532 int const bottom_display_margin = mi.base.inPixels(Length(10, Length::PT));
533 int top_display_margin = bottom_display_margin;
534 // at start of paragraph, add an empty line
536 top_display_margin += theFontMetrics(mi.base.font).maxHeight() + 2;
538 if (previewState(mi.base.bv)) {
539 preview_->metrics(mi, dim);
540 if (previewTooSmall(dim)) {
541 // preview image is too small
542 dim.wid += 2 * ERROR_FRAME_WIDTH;
543 dim.asc += 2 * ERROR_FRAME_WIDTH;
545 // insert a gap in front of the formula
546 // value was hardcoded to 1 pixel
547 dim.wid += mi.base.bv->zoomedPixels(1) ;
549 dim.asc += top_display_margin;
550 dim.des += bottom_display_margin;
557 Changer dummy1 = mi.base.changeFontSet(standardFont());
558 Changer dummy2 = mi.base.font.changeStyle(display() ? DISPLAY_STYLE
561 // let the cells adjust themselves
562 InsetMathGrid::metrics(mi, dim);
565 // Check whether the numbering interferes with the equations
566 if (numberedType()) {
567 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
568 int extra_offset = 0;
569 for (row_type row = 0; row < nrows(); ++row) {
570 rowinfo(row).offset[mi.base.bv] += extra_offset;
573 docstring const nl = nicelabel(row);
575 mathed_string_dim(mi.base.font, nl, dimnl);
576 int const ind = indent(*mi.base.bv);
577 int const x = ind ? ind : (mi.base.textwidth - dim.wid) / 2;
578 // for some reason metrics does not trigger at the
579 // same point as draw, and therefore we use >= instead of >
580 if ((math_number == BufferParams::LEFT && dimnl.wid >= x)
581 || (math_number == BufferParams::RIGHT
582 && dimnl.wid >= mi.base.textwidth - x - dim.wid)) {
583 extra_offset += dimnl.height();
586 dim.des += extra_offset;
591 dim.asc += top_display_margin;
592 dim.des += bottom_display_margin;
595 // reserve some space for marker.
600 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
602 BufferView const * const bv = pi.base.bv;
603 if (previewState(bv)) {
604 Dimension const dim = dimension(*pi.base.bv);
605 if (previewTooSmall(dim))
607 return graphics::PreviewLoader::backgroundColor();
613 void InsetMathHull::drawMarkers(PainterInfo & pi, int x, int y) const
615 ColorCode pen_color = mouseHovered(pi.base.bv) || editing(pi.base.bv)?
616 Color_mathframe : Color_mathcorners;
617 // If the corners have the same color as the background, do not paint them.
618 if (lcolor.getX11HexName(Color_mathbg) == lcolor.getX11HexName(pen_color))
621 Inset::drawMarkers(pi, x, y);
622 Dimension const dim = dimension(*pi.base.bv);
623 int const t = x + dim.width() - 1;
624 int const a = y - dim.ascent();
625 pi.pain.line(x, a + 3, x, a, pen_color);
626 pi.pain.line(t, a + 3, t, a, pen_color);
627 pi.pain.line(x, a, x + 3, a, pen_color);
628 pi.pain.line(t - 3, a, t, a, pen_color);
632 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
634 Dimension const dim = dimension(*pi.base.bv);
635 if (previewTooSmall(dim)) {
636 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
637 dim.wid, dim.asc + dim.des, backgroundColor(pi));
640 // If there are numbers, the margins around the (displayed)
641 // equation have to be cleared.
643 pi.pain.fillRectangle(pi.leftx, y - dim.asc,
644 pi.rightx - pi.leftx, dim.height(), pi.background_color);
645 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
646 dim.asc + dim.des - 1, pi.backgroundColor(this));
650 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
652 BufferView const * const bv = pi.base.bv;
653 Dimension const dim = dimension(*bv);
655 if (type_ == hullRegexp)
656 pi.pain.rectangle(x + 2, y - dim.ascent() + 1,
657 dim.width() - 3, dim.height() - 2, Color_regexpframe);
659 if (previewState(bv)) {
660 // Do not draw change tracking cue if taken care of by RowPainter
662 Changer dummy = !canPaintChange(*bv) ? make_change(pi.change, Change())
664 if (previewTooSmall(dim)) {
665 // we have an extra frame
666 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
668 // one pixel gap in front
669 // value was hardcoded to 1 pixel
670 int const gap = pi.base.bv->zoomedPixels(1) ;
671 preview_->draw(pi, x + gap, y);
676 // First draw the numbers
677 ColorCode color = pi.selected && lyxrc.use_system_colors
678 ? Color_selectiontext : standardColor();
679 bool const really_change_color = pi.base.font.color() == Color_none;
680 Changer dummy0 = really_change_color ? pi.base.font.changeColor(color)
682 if (numberedType()) {
683 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
684 for (row_type row = 0; row < nrows(); ++row) {
685 int yy = y + rowinfo(row).offset[bv];
686 docstring const nl = nicelabel(row);
688 mathed_string_dim(pi.base.font, nl, dimnl);
689 if (math_number == BufferParams::LEFT) {
690 if (dimnl.wid > x - pi.leftx)
691 yy += rowinfo(row).descent + dimnl.asc;
692 pi.draw(pi.leftx, yy, nl);
694 if (dimnl.wid > pi.rightx - x - dim.wid)
695 yy += rowinfo(row).descent + dimnl.asc;
696 pi.draw(pi.rightx - dimnl.wid, yy, nl);
701 // Then the equations
702 Changer dummy1 = pi.base.changeFontSet(standardFont());
703 Changer dummy2 = pi.base.font.changeStyle(display() ? DISPLAY_STYLE
705 InsetMathGrid::draw(pi, x + 1, y);
706 drawMarkers(pi, x, y);
708 // drawing change line
709 if (canPaintChange(*bv)) {
711 int const display_margin = display() ? pi.base.inPixels(Length(12, Length::PT)) : 0;
712 pi.change.paintCue(pi, x + 1, y + 1 - dim.asc + display_margin,
713 x + dim.wid, y + dim.des - display_margin);
718 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
721 InsetMathGrid::metricsT(mi, dim);
724 otexrowstream ots(os);
725 WriteStream wi(ots, false, true, WriteStream::wsDefault);
727 dim.wid = os.str().size();
734 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
737 InsetMathGrid::drawT(pain, x, y);
740 otexrowstream ots(os);
741 WriteStream wi(ots, false, true, WriteStream::wsDefault);
743 pain.draw(x, y, os.str().c_str());
748 static docstring latexString(InsetMathHull const & inset)
751 // This has to be static, because a preview snippet or a math
752 // macro containing math in text mode (such as $\text{$\phi$}$ or
753 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
754 // first time as a whole, and the second time only the inner math.
755 // In this last case inset.buffer() would be invalid.
756 static Encoding const * encoding = 0;
757 if (inset.isBufferValid())
758 encoding = &(inset.buffer().params().encoding());
759 otexrowstream ots(ls);
760 WriteStream wi(ots, false, true, WriteStream::wsPreview, encoding);
766 void InsetMathHull::initUnicodeMath() const
768 // Trigger classification of the unicode symbols in this inset
769 docstring const dummy = latexString(*this);
773 void InsetMathHull::addPreview(DocIterator const & inset_pos,
774 graphics::PreviewLoader & /*ploader*/) const
776 if (RenderPreview::previewMath()) {
777 preparePreview(inset_pos);
782 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
783 MacroNameSet & macros, MacroNameSet & defs) const
785 MacroNameSet::iterator const end = macros.end();
787 for (size_t i = 0; i < md.size(); ++i) {
788 InsetMathMacro const * mi = md[i].nucleus()->asMacro();
789 InsetMathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
790 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
791 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
792 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
793 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
795 // Look for macros in the arguments of this macro.
796 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
797 usedMacros(mi->cell(idx), pos, macros, defs);
798 // Make sure this is a macro defined in the document
799 // (as we also spot the macros in the symbols file)
800 // or that we have not already accounted for it.
801 docstring const name = mi->name();
802 if (macros.find(name) == end)
805 // Look for macros in the definition of this macro.
806 MathData ar(pos.buffer());
807 MacroData const * data =
808 pos.buffer()->getMacro(name, pos, true);
810 odocstringstream macro_def;
811 data->write(macro_def, true);
813 defs.insert(macro_def.str());
814 asArray(data->definition(), ar);
816 usedMacros(ar, pos, macros, defs);
818 MathData ar(pos.buffer());
819 asArray(mt->definition(), ar);
820 usedMacros(ar, pos, macros, defs);
822 if (!si->nuc().empty())
823 usedMacros(si->nuc(), pos, macros, defs);
825 usedMacros(si->down(), pos, macros, defs);
827 usedMacros(si->up(), pos, macros, defs);
828 } else if (fi || gi) {
829 idx_type nidx = fi ? fi->nargs() : gi->nargs();
830 for (idx_type idx = 0; idx < nidx; ++idx)
831 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
834 usedMacros(ni->cell(0), pos, macros, defs);
840 void InsetMathHull::preparePreview(DocIterator const & pos,
841 bool forexport) const
843 // there is no need to do all the macro stuff if we're not
844 // actually going to generate the preview.
845 if (!RenderPreview::previewMath() && !forexport)
848 Buffer const * buffer = pos.buffer();
850 // collect macros at this position
852 buffer->listMacroNames(macros);
854 // collect definitions only for the macros used in this inset
856 for (idx_type idx = 0; idx < nargs(); ++idx)
857 usedMacros(cell(idx), pos, macros, defs);
859 docstring macro_preamble;
860 for (auto const & defvar : defs)
861 macro_preamble.append(defvar);
863 // set the font series and size for this snippet
864 DocIterator dit = pos.getInnerText();
865 Paragraph const & par = dit.paragraph();
866 Font font = par.getFontSettings(buffer->params(), dit.pos());
867 font.fontInfo().realize(par.layout().font);
868 string const lsize = font.latexSize();
871 if (font.fontInfo().series() == BOLD_SERIES) {
872 setfont += from_ascii("\\textbf{");
875 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
876 setfont += from_ascii("\\" + lsize + '\n');
879 if (forexport && haveNumbers()) {
880 docstring eqstr = from_ascii("equation");
881 CounterMap::const_iterator it = counter_map.find(eqstr);
882 if (it != counter_map.end()) {
883 int num = it->second;
885 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
886 '{' + convert<docstring>(num) + '}' + '\n';
888 for (size_t i = 0; i != numcnts; ++i) {
889 docstring cnt = from_ascii(counters_to_save[i]);
890 it = counter_map.find(cnt);
891 if (it == counter_map.end())
893 int num = it->second;
895 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
896 '{' + convert<docstring>(num) + '}';
899 docstring const snippet = macro_preamble + setfont + setcnt
900 + latexString(*this) + endfont;
901 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
902 preview_->addPreview(snippet, *buffer, forexport);
906 void InsetMathHull::reloadPreview(DocIterator const & pos) const
909 preview_->startLoading(*pos.buffer());
913 void InsetMathHull::loadPreview(DocIterator const & pos) const
915 bool const forexport = true;
916 preparePreview(pos, forexport);
917 preview_->startLoading(*pos.buffer(), forexport);
921 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
923 if (RenderPreview::previewMath()) {
925 cur.screenUpdateFlags(Update::Force);
931 docstring InsetMathHull::label(row_type row) const
933 LASSERT(row < nrows(), return docstring());
934 if (InsetLabel * il = label_[row])
935 return il->screenLabel();
940 void InsetMathHull::label(row_type row, docstring const & label)
942 //lyxerr << "setting label '" << label << "' for row " << row << endl;
946 label_[row] = dummy_pointer;
949 label_[row]->updateLabelAndRefs(label);
951 label_[row]->setParam("name", label);
955 InsetCommandParams p(LABEL_CODE);
957 label_[row] = new InsetLabel(buffer_, p);
959 label_[row]->setBuffer(buffer());
963 void InsetMathHull::numbered(row_type row, Numbered num)
965 numbered_[row] = num;
966 if (!numbered(row) && label_[row]) {
973 bool InsetMathHull::numbered(row_type row) const
975 return numbered_[row] == NUMBER;
979 bool InsetMathHull::ams() const
999 for (auto const & row : numbered_)
1006 bool InsetMathHull::outerDisplay() const
1029 Inset::RowFlags InsetMathHull::rowFlags() const
1046 if (buffer().params().is_math_indent)
1047 return Display | AlignLeft;
1056 int InsetMathHull::indent(BufferView const & bv) const
1058 // FIXME: set this in the textclass. This value is what the article class uses.
1059 static Length default_indent(2.5, Length::EM);
1060 if (display() && buffer().params().is_math_indent) {
1061 Length const & len = buffer().params().getMathIndent();
1063 return bv.inPixels(default_indent);
1065 return bv.inPixels(len);
1067 return Inset::indent(bv);
1071 bool InsetMathHull::numberedType() const
1090 for (row_type row = 0; row < nrows(); ++row)
1097 void InsetMathHull::validate(LaTeXFeatures & features) const
1099 if (features.runparams().isLaTeX()) {
1101 features.require("amsmath");
1103 if (type_ == hullRegexp) {
1104 features.require("color");
1105 docstring frcol = from_utf8(lcolor.getLaTeXName(Color_regexpframe));
1106 docstring bgcol = from_ascii("white");
1107 features.addPreambleSnippet(
1108 "\\newcommand{\\regexp}[1]{\\fcolorbox{"
1110 + bgcol + "}{\\ensuremath{\\mathtt{#1}}}}");
1111 features.addPreambleSnippet(
1112 from_ascii("\\newcommand{\\endregexp}{}"));
1113 } else if (outerDisplay() && features.inDeletedInset()) {
1114 features.require("tikz");
1115 features.require("ct-tikz-object-sout");
1118 // Validation is necessary only if not using AMS math.
1119 // To be safe, we will always run mathedvalidate.
1120 //if (features.amsstyle)
1123 //features.binom = true;
1124 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
1125 // it would be better to do this elsewhere, but we can't validate in
1126 // InsetMathMatrix and we have no way, outside MathExtern, to know if
1127 // we even have any matrices.
1128 features.addCSSSnippet(
1129 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
1130 "table.matrix td{padding: 0.25px;}\n"
1131 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
1132 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
1134 InsetMathGrid::validate(features);
1138 OutputParams::CtObject InsetMathHull::CtObject(OutputParams const & runparams) const
1140 OutputParams::CtObject res = OutputParams::CT_NORMAL;
1156 case hullMultline: {
1157 if (runparams.inulemcmd
1158 && (!runparams.local_font || runparams.local_font->fontInfo().strikeout() != FONT_ON))
1159 res = OutputParams::CT_UDISPLAYOBJECT;
1161 res = OutputParams::CT_DISPLAYOBJECT;
1169 void InsetMathHull::header_write(WriteStream & os) const
1171 bool n = numberedType();
1182 if (cell(0).empty())
1187 writeMathdisplayPreamble(os);
1191 os << "\\begin{equation" << star(n) << "}\n";
1201 writeMathdisplayPreamble(os);
1204 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1211 os << "\\begin{" << hullName(type_) << star(n) << '}'
1212 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1218 os << "\\begin{" << hullName(type_) << '}'
1219 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1229 os << "\\begin{unknown" << star(n) << "}\n";
1235 void InsetMathHull::footer_write(WriteStream & os) const
1237 bool n = numberedType();
1254 os << "\\end{equation" << star(n) << "}\n";
1257 writeMathdisplayPostamble(os);
1267 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1268 writeMathdisplayPostamble(os);
1275 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1281 os << "\\end{" << hullName(type_) << "}\n";
1285 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1286 os << "\\endregexp{}}";
1292 os << "\\end{unknown" << star(n) << "}\n";
1298 bool InsetMathHull::allowsTabularFeatures() const
1321 bool InsetMathHull::rowChangeOK() const
1324 type_ == hullEqnArray || type_ == hullAlign ||
1325 type_ == hullFlAlign || type_ == hullAlignAt ||
1326 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1327 type_ == hullGather || type_ == hullMultline;
1331 bool InsetMathHull::colChangeOK() const
1334 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1335 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1339 void InsetMathHull::addRow(row_type row)
1344 bool numbered = numberedType();
1345 // Move the number and raw pointer, do not call label() (bug 7511)
1346 InsetLabel * label = dummy_pointer;
1347 docstring number = empty_docstring();
1348 if (type_ == hullMultline) {
1349 if (row + 1 == nrows()) {
1350 numbered_[row] = NONUMBER;
1351 swap(label, label_[row]);
1352 swap(number, numbers_[row]);
1357 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1358 numbers_.insert(numbers_.begin() + row + 1, number);
1359 label_.insert(label_.begin() + row + 1, label);
1360 InsetMathGrid::addRow(row);
1364 void InsetMathHull::swapRow(row_type row)
1368 if (row + 1 == nrows())
1370 swap(numbered_[row], numbered_[row + 1]);
1371 swap(numbers_[row], numbers_[row + 1]);
1372 swap(label_[row], label_[row + 1]);
1373 InsetMathGrid::swapRow(row);
1377 void InsetMathHull::delRow(row_type row)
1379 if (nrows() <= 1 || !rowChangeOK())
1381 if (row + 1 == nrows() && type_ == hullMultline) {
1382 swap(numbered_[row - 1], numbered_[row]);
1383 swap(numbers_[row - 1], numbers_[row]);
1384 swap(label_[row - 1], label_[row]);
1385 InsetMathGrid::delRow(row);
1388 InsetMathGrid::delRow(row);
1389 // The last dummy row has no number info nor a label.
1390 // Test nrows() + 1 because we have already erased the row.
1391 if (row == nrows() + 1)
1393 numbered_.erase(numbered_.begin() + row);
1394 numbers_.erase(numbers_.begin() + row);
1396 label_.erase(label_.begin() + row);
1400 void InsetMathHull::addCol(col_type col)
1404 InsetMathGrid::addCol(col);
1408 void InsetMathHull::delCol(col_type col)
1410 if (ncols() <= 1 || !colChangeOK())
1412 InsetMathGrid::delCol(col);
1416 docstring InsetMathHull::nicelabel(row_type row) const
1420 docstring const & val = numbers_[row];
1422 return '(' + val + ')';
1423 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1427 void InsetMathHull::glueall(HullType type)
1430 for (idx_type i = 0; i < nargs(); ++i)
1432 InsetLabel * label = 0;
1433 if (type == hullEquation) {
1434 // preserve first non-empty label
1435 for (row_type row = 0; row < nrows(); ++row) {
1437 label = label_[row];
1443 *this = InsetMathHull(buffer_, hullSimple);
1450 void InsetMathHull::splitTo2Cols()
1452 LASSERT(ncols() == 1, return);
1453 InsetMathGrid::addCol(1);
1454 for (row_type row = 0; row < nrows(); ++row) {
1455 idx_type const i = 2 * row;
1456 pos_type pos = firstRelOp(cell(i));
1457 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1458 cell(i).erase(pos, cell(i).size());
1463 void InsetMathHull::splitTo3Cols()
1465 LASSERT(ncols() < 3, return);
1468 InsetMathGrid::addCol(2);
1469 for (row_type row = 0; row < nrows(); ++row) {
1470 idx_type const i = 3 * row + 1;
1471 if (!cell(i).empty()) {
1472 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1473 cell(i).erase(1, cell(i).size());
1479 void InsetMathHull::changeCols(col_type cols)
1481 if (ncols() == cols)
1483 else if (ncols() < cols) {
1489 while (ncols() < cols)
1490 InsetMathGrid::addCol(ncols());
1496 for (row_type row = 0; row < nrows(); ++row) {
1497 idx_type const i = row * ncols();
1498 for (col_type col = cols; col < ncols(); ++col) {
1499 cell(i + cols - 1).append(cell(i + col));
1503 while (ncols() > cols) {
1504 InsetMathGrid::delCol(ncols() - 1);
1509 HullType InsetMathHull::getType() const
1515 void InsetMathHull::setType(HullType type)
1522 bool InsetMathHull::isMutable(HullType type)
1546 void InsetMathHull::mutate(HullType newtype)
1548 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1550 if (newtype == type_)
1553 // This guards the algorithm below it, which is designed with certain types
1555 if (!isMutable(newtype) || !isMutable(type_)) {
1556 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1557 << "' to '" << to_utf8(hullName(newtype))
1558 << "' not implemented" << endl;
1562 // we try to move along the chain
1563 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1565 // +-------------------------------------+
1566 // we use eqnarray as intermediate type for mutations that are not
1567 // directly supported because it handles labels and numbering for
1572 setType(hullSimple);
1578 if (newtype == hullNone) {
1582 setType(hullEquation);
1583 numbered(0, label_[0] != nullptr);
1592 setType(hullSimple);
1597 // split it "nicely" on the first relop
1599 setType(hullEqnArray);
1607 // split it "nicely"
1642 setType(hullEqnArray);
1651 for (row_type row = 0; row < nrows(); ++row)
1652 numbered(row, false);
1662 for (row_type row = 0; row < nrows(); ++row)
1663 numbered(row, false);
1670 setType(hullEqnArray);
1700 for (row_type row = 0; row < nrows(); ++row)
1701 numbered(row, false);
1705 // first we mutate to EqnArray
1707 setType(hullEqnArray);
1714 // we passed the guard so we should not be here
1715 LYXERR0("Mutation not implemented, but should have been.");
1716 LASSERT(false, return);
1722 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1723 bool last_eoln) const
1726 if (numberedType()) {
1727 if (label_[row] && numbered(row)) {
1728 docstring const name =
1729 latex ? escape(label_[row]->getParam("name"))
1730 : label_[row]->getParam("name");
1731 res += "\\label{" + name + '}';
1733 if (type_ != hullMultline) {
1734 if (numbered_[row] == NONUMBER)
1735 res += "\\nonumber ";
1736 else if (numbered_[row] == NOTAG)
1740 // Never add \\ on the last empty line of eqnarray and friends
1742 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1745 void InsetMathHull::write(WriteStream & os) const
1747 ModeSpecifier specifier(os, MATH_MODE);
1749 InsetMathGrid::write(os);
1754 void InsetMathHull::normalize(NormalStream & os) const
1756 os << "[formula " << hullName(type_) << ' ';
1757 InsetMathGrid::normalize(os);
1762 void InsetMathHull::infoize(odocstream & os) const
1764 os << bformat(_("Type: %1$s"), hullName(type_));
1768 void InsetMathHull::check() const
1770 LATTEST(numbered_.size() == nrows());
1771 LATTEST(numbers_.size() == nrows());
1772 LATTEST(label_.size() == nrows());
1776 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1778 //FIXME: sort out whether we want std::string or docstring for those
1779 string const lang = func.getArg(0);
1780 docstring extra = from_utf8(func.getArg(1));
1782 extra = from_ascii("noextra");
1784 // replace selection with result of computation
1785 if (reduceSelectionToOneCell(cur)) {
1787 asArray(grabAndEraseSelection(cur), ar);
1788 lyxerr << "use selection: " << ar << endl;
1789 cur.insert(pipeThroughExtern(lang, extra, ar));
1793 // only inline, display or eqnarray math is allowed
1794 switch (getType()) {
1800 frontend::Alert::warning(_("Bad math environment"),
1801 _("Computation cannot be performed for AMS "
1802 "math environments.\nChange the math "
1803 "formula type and try again."));
1808 eq.push_back(MathAtom(new InsetMathChar('=')));
1810 // go to first item in line
1811 cur.idx() -= cur.idx() % ncols();
1814 if (getType() == hullSimple) {
1815 size_type pos = cur.cell().find_last(eq);
1817 if (pos == cur.cell().size()) {
1819 lyxerr << "use whole cell: " << ar << endl;
1821 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1822 lyxerr << "use partial cell form pos: " << pos << endl;
1824 cur.cell().append(eq);
1825 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1826 cur.pos() = cur.lastpos();
1830 if (getType() == hullEquation) {
1831 lyxerr << "use equation inset" << endl;
1832 mutate(hullEqnArray);
1833 MathData & ar = cur.cell();
1834 lyxerr << "use cell: " << ar << endl;
1838 cur.cell() = pipeThroughExtern(lang, extra, ar);
1839 // move to end of line
1840 cur.pos() = cur.lastpos();
1845 lyxerr << "use eqnarray" << endl;
1846 cur.idx() += 2 - cur.idx() % ncols();
1848 MathData ar = cur.cell();
1849 lyxerr << "use cell: " << ar << endl;
1850 // FIXME: temporarily disabled
1856 cur.cell() = pipeThroughExtern(lang, extra, ar);
1857 cur.pos() = cur.lastpos();
1862 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1864 //lyxerr << "action: " << cmd.action() << endl;
1865 switch (cmd.action()) {
1867 case LFUN_FINISHED_BACKWARD:
1868 case LFUN_FINISHED_FORWARD:
1869 case LFUN_FINISHED_RIGHT:
1870 case LFUN_FINISHED_LEFT:
1871 //lyxerr << "action: " << cmd.action() << endl;
1872 InsetMathGrid::doDispatch(cur, cmd);
1875 case LFUN_PARAGRAPH_BREAK:
1876 // just swallow this
1879 case LFUN_NEWLINE_INSERT:
1880 // some magic for the common case
1881 if (type_ == hullSimple || type_ == hullEquation) {
1882 cur.recordUndoInset();
1884 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1885 mutate(align ? hullAlign : hullEqnArray);
1886 // mutate() may change labels and such.
1887 cur.forceBufferUpdate();
1888 cur.idx() = nrows() * ncols() - 1;
1889 cur.pos() = cur.lastpos();
1891 InsetMathGrid::doDispatch(cur, cmd);
1894 case LFUN_MATH_NUMBER_TOGGLE: {
1895 //lyxerr << "toggling all numbers" << endl;
1896 cur.recordUndoInset();
1897 bool old = numberedType();
1898 if (type_ == hullMultline)
1899 numbered(nrows() - 1, !old);
1901 for (row_type row = 0; row < nrows(); ++row)
1902 numbered(row, !old);
1904 cur.message(old ? _("No number") : _("Number"));
1905 cur.forceBufferUpdate();
1909 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1910 cur.recordUndoInset();
1911 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1912 bool old = numbered(r);
1913 cur.message(old ? _("No number") : _("Number"));
1915 cur.forceBufferUpdate();
1919 case LFUN_LABEL_INSERT: {
1920 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1921 docstring old_label = label(r);
1922 docstring const default_label = from_ascii("eq:");
1923 if (old_label.empty())
1924 old_label = default_label;
1926 InsetCommandParams p(LABEL_CODE);
1927 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1928 string const data = InsetCommand::params2string(p);
1930 if (cmd.argument().empty())
1931 cur.bv().showDialog("label", data);
1933 FuncRequest fr(LFUN_INSET_INSERT, data);
1939 case LFUN_LABEL_COPY_AS_REFERENCE: {
1941 if (cmd.argument().empty() && &cur.inset() == this)
1942 // if there is no argument and we're inside math, we retrieve
1943 // the row number from the cursor position.
1944 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1946 // if there is an argument, find the corresponding label, else
1947 // check whether there is at least one label.
1948 for (row = 0; row != nrows(); ++row)
1949 if (numbered(row) && label_[row]
1950 && (cmd.argument().empty() || label(row) == cmd.argument()))
1957 InsetCommandParams p(REF_CODE, "ref");
1958 p["reference"] = label(row);
1959 cap::clearSelection();
1960 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1964 case LFUN_WORD_DELETE_FORWARD:
1965 case LFUN_CHAR_DELETE_FORWARD:
1966 if (col(cur.idx()) + 1 == ncols()
1967 && cur.pos() == cur.lastpos()
1968 && !cur.selection()) {
1969 if (!label(row(cur.idx())).empty()) {
1970 cur.recordUndoInset();
1971 label(row(cur.idx()), docstring());
1972 } else if (numbered(row(cur.idx()))) {
1973 cur.recordUndoInset();
1974 numbered(row(cur.idx()), false);
1975 cur.forceBufferUpdate();
1977 InsetMathGrid::doDispatch(cur, cmd);
1981 InsetMathGrid::doDispatch(cur, cmd);
1986 case LFUN_INSET_INSERT: {
1987 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1988 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1989 string const name = cmd.getArg(0);
1990 if (name == "label") {
1991 InsetCommandParams p(LABEL_CODE);
1992 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1993 docstring str = p["name"];
1994 cur.recordUndoInset();
1995 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1999 docstring old = label(r);
2002 // The label will take care of the reference update.
2006 // Newly created inset so initialize it.
2007 label_[r]->initView();
2010 cur.forceBufferUpdate();
2013 InsetMathGrid::doDispatch(cur, cmd);
2017 case LFUN_MATH_EXTERN:
2018 cur.recordUndoInset();
2022 case LFUN_MATH_MUTATE: {
2023 cur.recordUndoInset();
2024 row_type row = cur.row();
2025 col_type col = cur.col();
2026 mutate(hullType(cmd.argument()));
2027 cur.idx() = row * ncols() + col;
2028 if (cur.idx() > cur.lastidx()) {
2029 cur.idx() = cur.lastidx();
2030 cur.pos() = cur.lastpos();
2032 if (cur.pos() > cur.lastpos())
2033 cur.pos() = cur.lastpos();
2035 cur.forceBufferUpdate();
2036 // FIXME: find some more clever handling of the selection,
2037 // i.e. preserve it.
2038 cur.clearSelection();
2039 //cur.dispatched(FINISHED);
2043 case LFUN_MATH_DISPLAY: {
2044 cur.recordUndoInset();
2045 mutate(type_ == hullSimple ? hullEquation : hullSimple);
2046 // if the cursor is in a cell that got merged, move it to
2047 // start of the hull inset.
2048 if (cur.idx() > 0) {
2052 if (cur.pos() > cur.lastpos())
2053 cur.pos() = cur.lastpos();
2058 case LFUN_TABULAR_FEATURE:
2059 if (!allowsTabularFeatures())
2062 InsetMathGrid::doDispatch(cur, cmd);
2066 InsetMathGrid::doDispatch(cur, cmd);
2074 bool allowDisplayMath(Cursor const & cur)
2076 LATTEST(cur.depth() > 1);
2077 Cursor tmpcur = cur;
2080 FuncRequest cmd(LFUN_MATH_DISPLAY);
2081 return tmpcur.getStatus(cmd, status) && status.enabled();
2087 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
2088 FuncStatus & status) const
2090 switch (cmd.action()) {
2091 case LFUN_FINISHED_BACKWARD:
2092 case LFUN_FINISHED_FORWARD:
2093 case LFUN_FINISHED_RIGHT:
2094 case LFUN_FINISHED_LEFT:
2097 case LFUN_NEWLINE_INSERT:
2098 case LFUN_MATH_EXTERN:
2100 status.setEnabled(true);
2103 // we never allow this in math, and we want to bind enter
2104 // to another actions in command-alternatives
2105 case LFUN_PARAGRAPH_BREAK:
2106 status.setEnabled(false);
2108 case LFUN_MATH_MUTATE: {
2109 HullType const ht = hullType(cmd.argument());
2110 status.setOnOff(type_ == ht);
2111 status.setEnabled(isMutable(ht) && isMutable(type_));
2113 if (ht != hullSimple && status.enabled())
2114 status.setEnabled(allowDisplayMath(cur));
2117 case LFUN_MATH_DISPLAY: {
2118 status.setEnabled(display() || allowDisplayMath(cur));
2119 status.setOnOff(display());
2123 case LFUN_MATH_NUMBER_TOGGLE:
2124 // FIXME: what is the right test, this or the one of
2126 status.setEnabled(display());
2127 status.setOnOff(numberedType());
2130 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
2131 // FIXME: what is the right test, this or the one of
2133 bool const enable = (type_ == hullMultline)
2134 ? (nrows() - 1 == cur.row())
2136 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2137 status.setEnabled(enable);
2138 status.setOnOff(enable && numbered(r));
2142 case LFUN_LABEL_INSERT:
2143 status.setEnabled(type_ != hullSimple);
2146 case LFUN_LABEL_COPY_AS_REFERENCE: {
2147 bool enabled = false;
2148 if (cmd.argument().empty() && &cur.inset() == this) {
2149 // if there is no argument and we're inside math, we retrieve
2150 // the row number from the cursor position.
2151 row_type row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2152 enabled = numberedType() && label_[row] && numbered(row);
2154 // if there is an argument, find the corresponding label, else
2155 // check whether there is at least one label.
2156 for (row_type row = 0; row != nrows(); ++row) {
2157 if (numbered(row) && label_[row] &&
2158 (cmd.argument().empty() || label(row) == cmd.argument())) {
2164 status.setEnabled(enabled);
2168 case LFUN_INSET_INSERT:
2169 if (cmd.getArg(0) == "label") {
2170 status.setEnabled(type_ != hullSimple);
2173 return InsetMathGrid::getStatus(cur, cmd, status);
2175 case LFUN_TABULAR_FEATURE: {
2176 if (!allowsTabularFeatures())
2178 string s = cmd.getArg(0);
2180 && (s == "append-row"
2181 || s == "delete-row"
2182 || s == "copy-row")) {
2183 status.message(bformat(
2184 from_utf8(N_("Can't change number of rows in '%1$s'")),
2186 status.setEnabled(false);
2190 && (s == "append-column"
2191 || s == "delete-column"
2192 || s == "copy-column")) {
2193 status.message(bformat(
2194 from_utf8(N_("Can't change number of columns in '%1$s'")),
2196 status.setEnabled(false);
2199 if (s == "add-vline-left" || s == "add-vline-right") {
2200 status.message(bformat(
2201 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2203 status.setEnabled(false);
2206 if (s == "valign-top" || s == "valign-middle"
2207 || s == "valign-bottom" || s == "align-left"
2208 || s == "align-center" || s == "align-right") {
2209 status.setEnabled(false);
2212 return InsetMathGrid::getStatus(cur, cmd, status);
2216 return InsetMathGrid::getStatus(cur, cmd, status);
2221 int InsetMathHull::leftMargin() const
2223 return (getType() == hullSimple) ? 0 : InsetMathGrid::leftMargin();
2227 int InsetMathHull::rightMargin() const
2229 return (getType() == hullSimple) ? 0 : InsetMathGrid::rightMargin();
2233 int InsetMathHull::border() const
2235 return (getType() == hullSimple) ? 0 : InsetMathGrid::border();
2239 /////////////////////////////////////////////////////////////////////
2243 // simply scrap this function if you want
2244 void InsetMathHull::mutateToText()
2247 // translate to latex
2249 latex(os, false, false);
2250 string str = os.str();
2253 Text * lt = view_->cursor().innerText();
2254 string::const_iterator cit = str.begin();
2255 string::const_iterator end = str.end();
2256 for (; cit != end; ++cit)
2257 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2260 //dispatch(LFUN_ESCAPE);
2265 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2266 docstring const & font)
2268 // this whole function is a hack and won't work for incremental font
2271 if (cur.inset().asInsetMath()->name() == font)
2272 cur.handleFont(to_utf8(font));
2274 cur.handleNest(createInsetMath(font, cur.buffer()));
2280 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2285 font.fromString(to_utf8(arg), b);
2286 if (font.fontInfo().color() != Color_inherit) {
2287 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2293 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2295 InsetMathNest::edit(cur, front, entry_from);
2296 // The inset formula dimension is not necessarily the same as the
2297 // one of the instant preview image, so we have to indicate to the
2298 // BufferView that a metrics update is needed.
2299 cur.screenUpdateFlags(Update::Force);
2303 /////////////////////////////////////////////////////////////////////
2307 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2310 // FIXME: completely broken
2311 static InsetMathHull * lastformula = 0;
2312 static CursorBase current = DocIterator(ibegin(nucleus()));
2314 static string laststr;
2316 if (lastformula != this || laststr != str) {
2317 //lyxerr << "reset lastformula to " << this << endl;
2320 current = ibegin(nucleus());
2322 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2326 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2328 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2329 CursorSlice & top = it.back();
2330 MathData const & a = top.asInsetMath()->cell(top.idx_);
2331 if (a.matchpart(ar, top.pos_)) {
2332 bv->cursor().setSelection(it, ar.size());
2334 top.pos_ += ar.size();
2340 //lyxerr << "not found!" << endl;
2347 void InsetMathHull::write(ostream & os) const
2349 odocstringstream oss;
2350 otexrowstream ots(oss);
2351 WriteStream wi(ots, false, false, WriteStream::wsDefault);
2354 os << to_utf8(oss.str());
2358 void InsetMathHull::read(Lexer & lex)
2361 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2362 operator=(*at->asHullInset());
2366 bool InsetMathHull::readQuiet(Lexer & lex)
2369 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2371 operator=(*at->asHullInset());
2376 int InsetMathHull::plaintext(odocstringstream & os,
2377 OutputParams const & op, size_t max_length) const
2379 // Try enabling this now that there is a flag as requested at #2275.
2380 if (buffer().isExporting() && display()) {
2384 TextPainter tpain(dim.width(), dim.height());
2385 drawT(tpain, 0, dim.ascent());
2387 // reset metrics cache to "real" values
2389 return tpain.textheight();
2392 odocstringstream oss;
2393 otexrowstream ots(oss);
2394 Encoding const * const enc = encodings.fromLyXName("utf8");
2395 WriteStream wi(ots, false, true, WriteStream::wsDefault, enc);
2398 if (type_ == hullRegexp)
2401 for (row_type r = 0; r < nrows(); ++r) {
2402 for (col_type c = 0; c < ncols(); ++c)
2403 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2404 // if it's for the TOC, we write just the first line
2405 // and do not include the newline.
2406 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2408 if (r < nrows() - 1)
2412 docstring const str = oss.str();
2418 void InsetMathHull::docbook(XMLStream & xs, OutputParams const & runparams) const
2420 // Choose the tag around the MathML equation.
2423 if (getType() == hullSimple)
2424 name = from_ascii("inlineequation");
2426 doCR = true; // This is a block equation, always have <informalequation> on its own line.
2427 name = from_ascii("informalequation");
2430 // DocBook also has <equation>, but it comes with a title.
2431 // TODO: recognise \tag from amsmath? This would allow having <equation> with a proper title.
2434 for (row_type i = 0; i < nrows(); ++i) {
2435 if (!label(i).empty()) {
2436 attr = "xml:id=\"" + xml::cleanID(label(i)) + "\"";
2442 if (!xs.isLastTagCR())
2445 xs << xml::StartTag(name, attr);
2448 // With DocBook 5, MathML must be within its own namespace; defined in Buffer.cpp::writeDocBookSource as "m".
2449 // Output everything in a separate stream so that this does not interfere with the standard flow of DocBook tags.
2450 odocstringstream osmath;
2451 MathStream ms(osmath, "m", true);
2453 // Output the MathML subtree.
2454 odocstringstream ls;
2457 // TeX transcription. Avoid MTag/ETag so that there are no extraneous spaces.
2458 ms << "<" << from_ascii("alt") << " role='tex'" << ">";
2459 // Workaround for db2latex: db2latex always includes equations with
2460 // \ensuremath{} or \begin{display}\end{display}
2461 // so we strip LyX' math environment
2462 WriteStream wi(ols, false, false, WriteStream::wsDefault, runparams.encoding);
2463 InsetMathGrid::write(wi);
2464 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2465 ms << "</" << from_ascii("alt") << ">";
2467 // Actual transformation of the formula into MathML. This translation may fail (for example, due to custom macros).
2468 // The new output stream is required to deal with the errors: first write completely the formula into this
2469 // temporary stream; then, if it is possible without error, then copy it back to the "real" stream. Otherwise,
2470 // some incomplete tags might be put into the real stream.
2472 // First, generate the MathML expression.
2473 odocstringstream ostmp;
2474 MathStream mstmp(ostmp, ms.xmlns(), ms.xmlMode());
2475 InsetMathGrid::mathmlize(mstmp);
2477 // Then, output it (but only if the generation can be done without errors!).
2480 osmath << ostmp.str(); // osmath is not a XMLStream, so no need for XMLStream::ESCAPE_NONE.
2482 } catch (MathExportException const &) {
2484 osmath << "<mathphrase>MathML export failed. Please report this as a bug.</mathphrase>";
2487 // Output the complete formula to the DocBook stream.
2488 xs << XMLStream::ESCAPE_NONE << osmath.str();
2490 xs << xml::EndTag(name);
2496 bool InsetMathHull::haveNumbers() const
2498 bool havenumbers = false;
2499 // inline formulas are never numbered (bug 7351 part 3)
2500 if (getType() == hullSimple)
2502 for (size_t i = 0; i != numbered_.size(); ++i) {
2513 // We need to do something about alignment here.
2515 // This duplicates code from InsetMathGrid, but
2516 // we need access here to number information,
2517 // and we simply do not have that in InsetMathGrid.
2518 void InsetMathHull::htmlize(HtmlStream & os) const
2520 bool const havenumbers = haveNumbers();
2521 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2524 os << cell(index(0, 0));
2528 os << MTag("table", "class='mathtable'");
2529 for (row_type row = 0; row < nrows(); ++row) {
2531 for (col_type col = 0; col < ncols(); ++col) {
2533 os << cell(index(row, col));
2538 docstring const & num = numbers_[row];
2540 os << '(' << num << ')';
2545 os << ETag("table");
2549 // this duplicates code from InsetMathGrid, but
2550 // we need access here to number information,
2551 // and we simply do not have that in InsetMathGrid.
2552 void InsetMathHull::mathmlize(MathStream & ms) const
2554 bool const havenumbers = haveNumbers();
2555 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2558 ms << MTag("mtable");
2559 char const * const celltag = havetable ? "mtd" : "mrow";
2560 // FIXME There does not seem to be wide support at the moment
2561 // for mlabeledtr, so we have to use just mtr for now.
2562 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2563 char const * const rowtag = "mtr";
2564 for (row_type row = 0; row < nrows(); ++row) {
2567 for (col_type col = 0; col < ncols(); ++col) {
2569 << cell(index(row, col))
2575 docstring const & num = numbers_[row];
2577 ms << '(' << num << ')';
2584 ms << ETag("mtable");
2588 void InsetMathHull::mathAsLatex(WriteStream & os) const
2590 MathEnsurer ensurer(os, false);
2591 bool havenumbers = haveNumbers();
2592 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2595 os << cell(index(0, 0));
2599 os << "<table class='mathtable'>";
2600 for (row_type row = 0; row < nrows(); ++row) {
2602 for (col_type col = 0; col < ncols(); ++col) {
2603 os << "<td class='math'>";
2604 os << cell(index(row, col));
2609 docstring const & num = numbers_[row];
2611 os << '(' << num << ')';
2620 docstring InsetMathHull::xhtml(XMLStream & xs, OutputParams const & op) const
2622 BufferParams::MathOutput const mathtype =
2623 buffer().masterBuffer()->params().html_math_output;
2625 bool success = false;
2627 // we output all the labels just at the beginning of the equation.
2628 // this should be fine.
2629 for (size_t i = 0; i != label_.size(); ++i) {
2630 InsetLabel const * const il = label_[i];
2636 // FIXME Eventually we would like to do this inset by inset.
2637 if (mathtype == BufferParams::MathML) {
2638 odocstringstream os;
2643 } catch (MathExportException const &) {}
2645 if (getType() == hullSimple)
2646 xs << xml::StartTag("math",
2647 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2649 xs << xml::StartTag("math",
2650 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2651 xs << XMLStream::ESCAPE_NONE
2653 << xml::EndTag("math");
2655 } else if (mathtype == BufferParams::HTML) {
2656 odocstringstream os;
2661 } catch (MathExportException const &) {}
2663 string const tag = (getType() == hullSimple) ? "span" : "div";
2664 xs << xml::StartTag(tag, "class='formula'", true)
2665 << XMLStream::ESCAPE_NONE
2667 << xml::EndTag(tag);
2671 // what we actually want is this:
2673 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2675 // || mathtype == BufferParams::Images
2677 // but what follows is equivalent, since we'll enter only if either (a) we
2678 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2679 // aren't doing LaTeX.
2681 // so this is for Images.
2682 if (!success && mathtype != BufferParams::LaTeX) {
2683 graphics::PreviewImage const * pimage = 0;
2685 loadPreview(docit_);
2686 pimage = preview_->getPreviewImage(buffer());
2687 // FIXME Do we always have png?
2690 if (pimage || op.dryrun) {
2691 string const filename = pimage ? pimage->filename().onlyFileName()
2692 : "previewimage.png";
2694 // if we are not in the master buffer, then we need to see that the
2695 // generated image is copied there; otherwise, preview fails.
2696 Buffer const * mbuf = buffer().masterBuffer();
2697 if (mbuf != &buffer()) {
2698 string mbtmp = mbuf->temppath();
2699 FileName const mbufimg(support::addName(mbtmp, filename));
2700 pimage->filename().copyTo(mbufimg);
2702 // add the file to the list of files to be exported
2703 op.exportdata->addExternalFile("xhtml", pimage->filename());
2706 string const tag = (getType() == hullSimple) ? "span" : "div";
2708 << xml::StartTag(tag, "style = \"text-align: center;\"")
2709 << xml::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2716 // so we'll pass this test if we've failed everything else, or
2717 // if mathtype was LaTeX, since we won't have entered any of the
2719 if (!success /* || mathtype != BufferParams::LaTeX */) {
2720 // Unfortunately, we cannot use latexString() because we do not want
2721 // $...$ or whatever.
2722 odocstringstream ls;
2723 otexrowstream ots(ls);
2724 WriteStream wi(ots, false, true, WriteStream::wsPreview);
2725 ModeSpecifier specifier(wi, MATH_MODE);
2727 docstring const latex = ls.str();
2729 // class='math' allows for use of jsMath
2730 // http://www.math.union.edu/~dpvc/jsMath/
2732 // probably should allow for some kind of customization here
2733 string const tag = (getType() == hullSimple) ? "span" : "div";
2734 xs << xml::StartTag(tag, "class='math'")
2743 void InsetMathHull::toString(odocstream & os) const
2745 odocstringstream ods;
2746 plaintext(ods, OutputParams(0));
2751 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2753 odocstringstream ods;
2756 // FIXME: this results in spilling TeX into the LyXHTML output since the
2757 // outliner is used to generate the LyXHTML list of figures/etc.
2763 string InsetMathHull::contextMenuName() const
2765 return "context-math";
2769 void InsetMathHull::recordLocation(DocIterator const & di)
2775 bool InsetMathHull::canPaintChange(BufferView const &) const
2777 // We let RowPainter do it seamlessly for inline insets