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"
29 #include "CutAndPaste.h"
32 #include "FuncRequest.h"
33 #include "FuncStatus.h"
35 #include "LaTeXFeatures.h"
37 #include "MacroTable.h"
38 #include "InsetMathMacro.h"
39 #include "InsetMathMacroTemplate.h"
40 #include "MetricsInfo.h"
41 #include "output_xhtml.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/Painter.h"
61 #include "support/convert.h"
62 #include "support/debug.h"
63 #include "support/gettext.h"
64 #include "support/filetools.h"
65 #include "support/lassert.h"
66 #include "support/lstrings.h"
67 #include "support/RefChanger.h"
72 using namespace lyx::support;
76 using cap::grabAndEraseSelection;
77 using cap::reduceSelectionToOneCell;
81 int getCols(HullType type)
106 // returns position of first relation operator in the array
107 // used for "intelligent splitting"
108 size_t firstRelOp(MathData const & ar)
110 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
111 if ((*it)->mathClass() == MC_REL)
112 return it - ar.begin();
117 char const * star(bool numbered)
119 return numbered ? "" : "*";
123 // writes a preamble for underlined or struck out math display
124 void writeMathdisplayPreamble(WriteStream & os)
126 if (os.strikeoutMath())
129 if (os.ulemCmd() == WriteStream::UNDERLINE)
130 os << "\\raisebox{-\\belowdisplayshortskip}{"
131 "\\parbox[b]{\\linewidth}{";
132 else if (os.ulemCmd() == WriteStream::STRIKEOUT)
133 os << "\\parbox{\\linewidth}{";
137 // writes a postamble for underlined or struck out math display
138 void writeMathdisplayPostamble(WriteStream & os)
140 if (os.strikeoutMath())
143 if (os.ulemCmd() == WriteStream::UNDERLINE)
145 else if (os.ulemCmd() == WriteStream::STRIKEOUT)
153 HullType hullType(docstring const & s)
155 if (s == "none") return hullNone;
156 if (s == "simple") return hullSimple;
157 if (s == "equation") return hullEquation;
158 if (s == "eqnarray") return hullEqnArray;
159 if (s == "align") return hullAlign;
160 if (s == "alignat") return hullAlignAt;
161 if (s == "xalignat") return hullXAlignAt;
162 if (s == "xxalignat") return hullXXAlignAt;
163 if (s == "multline") return hullMultline;
164 if (s == "gather") return hullGather;
165 if (s == "flalign") return hullFlAlign;
166 if (s == "regexp") return hullRegexp;
167 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
172 docstring hullName(HullType type)
175 case hullNone: return from_ascii("none");
176 case hullSimple: return from_ascii("simple");
177 case hullEquation: return from_ascii("equation");
178 case hullEqnArray: return from_ascii("eqnarray");
179 case hullAlign: return from_ascii("align");
180 case hullAlignAt: return from_ascii("alignat");
181 case hullXAlignAt: return from_ascii("xalignat");
182 case hullXXAlignAt: return from_ascii("xxalignat");
183 case hullMultline: return from_ascii("multline");
184 case hullGather: return from_ascii("gather");
185 case hullFlAlign: return from_ascii("flalign");
186 case hullRegexp: return from_ascii("regexp");
188 lyxerr << "unknown hull type" << endl;
191 return from_ascii("none");
194 static InsetLabel * dummy_pointer = 0;
196 InsetMathHull::InsetMathHull(Buffer * buf)
197 : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, NONUMBER),
198 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
199 preview_(new RenderPreview(this))
201 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
202 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
203 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
204 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
211 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
212 : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, NONUMBER),
213 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
214 preview_(new RenderPreview(this))
222 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
228 InsetMathHull::~InsetMathHull()
230 for (size_t i = 0; i < label_.size(); ++i)
235 Inset * InsetMathHull::clone() const
237 return new InsetMathHull(*this);
241 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
245 InsetMathGrid::operator=(other);
247 numbered_ = other.numbered_;
248 numbers_ = other.numbers_;
249 buffer_ = other.buffer_;
250 for (size_t i = 0; i < label_.size(); ++i)
252 label_ = other.label_;
253 for (size_t i = 0; i != label_.size(); ++i) {
255 label_[i] = new InsetLabel(*label_[i]);
257 preview_.reset(new RenderPreview(*other.preview_, this));
263 void InsetMathHull::setBuffer(Buffer & buffer)
265 InsetMathGrid::setBuffer(buffer);
267 for (size_t i = 0; i != label_.size(); ++i) {
269 label_[i]->setBuffer(buffer);
274 // FIXME This should really be controlled by the TOC level, or
275 // something of the sort.
277 const char * counters_to_save[] = {"section", "chapter"};
278 unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
282 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
285 //FIXME: buffer_ should be set at creation for this inset! Problem is
286 // This inset is created at too many places (see Parser::parse1() in
291 // if any of the equations are numbered, then we want to save the values
292 // of some of the counters.
294 BufferParams const & bp = buffer_->params();
295 string const & lang = it->getParLanguage(bp)->code();
297 buffer_->masterBuffer()->params().documentClass().counters();
299 // right now, we only need to do this at export time
300 if (utype == OutputUpdate) {
301 for (size_t i = 0; i < numcnts; ++i) {
302 docstring const cnt = from_ascii(counters_to_save[i]);
303 if (cnts.hasCounter(cnt))
304 counter_map[cnt] = cnts.value(cnt);
308 // this has to be done separately
309 docstring const eqstr = from_ascii("equation");
310 if (cnts.hasCounter(eqstr)) {
311 if (utype == OutputUpdate)
312 counter_map[eqstr] = cnts.value(eqstr);
313 for (size_t i = 0; i != label_.size(); ++i) {
315 Paragraph const & par = it.paragraph();
316 if (!par.isDeleted(it.pos())) {
317 cnts.step(eqstr, utype);
318 numbers_[i] = cnts.theCounter(eqstr, lang);
320 numbers_[i] = from_ascii("#");
322 numbers_[i] = empty_docstring();
328 for (size_t i = 0; i != label_.size(); ++i) {
330 label_[i]->updateBuffer(it, utype, deleted);
333 InsetMathGrid::updateBuffer(it, utype, deleted);
337 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active,
338 UpdateType utype, TocBackend & backend) const
341 //FIXME: buffer_ should be set at creation for this inset! Problem is
342 // This inset is created at too many places (see Parser::parse1() in
347 TocBuilder & b = backend.builder("equation");
348 // compute first and last item
349 row_type first = nrows();
350 for (row_type row = 0; row != nrows(); ++row)
355 if (first == nrows())
358 row_type last = nrows() - 1;
359 for (; last != 0; --last)
362 // add equation numbers
363 b.pushItem(pit, docstring(), output_active);
365 b.argumentItem(bformat(from_ascii("(%1$s-%2$s)"),
366 numbers_[first], numbers_[last]));
367 for (row_type row = 0; row != nrows(); ++row) {
371 label_[row]->addToToc(pit, output_active, utype, backend);
372 docstring label = nicelabel(row);
374 // this is the only equation
375 b.argumentItem(label);
377 // insert as sub-items
378 b.pushItem(pit, label, output_active);
386 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
388 if (previewState(&cur.bv())) {
392 return InsetMathNest::editXY(cur, x, y);
396 InsetMath::mode_type InsetMathHull::currentMode() const
400 return UNDECIDED_MODE;
402 // definitely math mode ...
422 // FIXME: InsetMathGrid should be changed to let the real column alignment be
423 // given by a virtual method like displayColAlign, because the values produced
424 // by defaultColAlign can be invalidated by lfuns such as add-column. For the
425 // moment the values produced by defaultColAlign are not used, notably because
426 // alignment is not implemented in the LyXHTML output.
427 char InsetMathHull::defaultColAlign(col_type col)
429 return colAlign(type_, col);
433 char InsetMathHull::displayColAlign(idx_type idx) const
437 row_type const r = row(idx);
440 if (r == nrows() - 1)
451 return colAlign(type_, col(idx));
455 return InsetMathGrid::displayColAlign(idx);
459 int InsetMathHull::displayColSpace(col_type col) const
461 return colSpace(type_, col);
465 // FIXME: same comment as for defaultColAlign applies.
466 int InsetMathHull::defaultColSpace(col_type col)
468 return colSpace(type_, col);
472 string InsetMathHull::standardFont() const
478 return "lyxnochange";
485 ColorCode InsetMathHull::standardColor() const
490 return Color_foreground;
498 bool InsetMathHull::previewState(const BufferView *const bv) const
500 if (!editing(bv) && RenderPreview::previewMath()
501 && type_ != hullRegexp)
503 graphics::PreviewImage const * pimage =
504 preview_->getPreviewImage(bv->buffer());
505 return pimage && pimage->image();
512 const int ERROR_FRAME_WIDTH = 2;
514 bool previewTooSmall(MetricsBase const & mb, Dimension const & dim)
516 // Value was hardcoded to 10 pixels
517 int const minval = mb.bv->zoomedPixels(10);
518 return dim.width() <= minval && dim.height() <= minval;
523 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
525 // true value in LaTeX is 12pt plus 3pt minus 9pt
526 // FIXME: even better would be to handle the short skip case.
527 int const display_margin = display() ? mi.base.inPixels(Length(12, Length::PT)) : 0;
529 if (previewState(mi.base.bv)) {
530 preview_->metrics(mi, dim);
531 if (previewTooSmall(mi.base, dim)) {
532 // preview image is too small
533 dim.wid += 2 * ERROR_FRAME_WIDTH;
534 dim.asc += 2 * ERROR_FRAME_WIDTH;
536 // insert a gap in front of the formula
537 // value was hardcoded to 1 pixel
538 dim.wid += mi.base.bv->zoomedPixels(1) ;
540 dim.asc += display_margin;
541 dim.des += display_margin;
548 Changer dummy1 = mi.base.changeFontSet(standardFont());
549 Changer dummy2 = mi.base.font.changeStyle(display() ? DISPLAY_STYLE
552 // let the cells adjust themselves
553 InsetMathGrid::metrics(mi, dim);
556 // Check whether the numbering interferes with the equations
557 if (numberedType()) {
558 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
559 int extra_offset = 0;
560 for (row_type row = 0; row < nrows(); ++row) {
561 rowinfo(row).offset[mi.base.bv] += extra_offset;
564 docstring const nl = nicelabel(row);
566 mathed_string_dim(mi.base.font, nl, dimnl);
567 int const ind = indent(*mi.base.bv);
568 int const x = ind ? ind : (mi.base.textwidth - dim.wid) / 2;
569 // for some reason metrics does not trigger at the
570 // same point as draw, and therefore we use >= instead of >
571 if ((math_number == BufferParams::LEFT && dimnl.wid >= x)
572 || (math_number == BufferParams::RIGHT
573 && dimnl.wid >= mi.base.textwidth - x - dim.wid)) {
574 extra_offset += dimnl.height();
577 dim.des += extra_offset;
582 dim.asc += display_margin;
583 dim.des += display_margin;
586 // reserve some space for marker.
591 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
593 BufferView const * const bv = pi.base.bv;
594 if (previewState(bv)) {
595 Dimension const dim = dimension(*pi.base.bv);
596 if (previewTooSmall(pi.base, dim))
598 return graphics::PreviewLoader::backgroundColor();
604 void InsetMathHull::drawMarkers(PainterInfo & pi, int x, int y) const
606 ColorCode pen_color = mouseHovered(pi.base.bv) || editing(pi.base.bv)?
607 Color_mathframe : Color_mathcorners;
608 // If the corners have the same color as the background, do not paint them.
609 if (lcolor.getX11Name(Color_mathbg) == lcolor.getX11Name(pen_color))
612 Inset::drawMarkers(pi, x, y);
613 Dimension const dim = dimension(*pi.base.bv);
614 int const t = x + dim.width() - 1;
615 int const a = y - dim.ascent();
616 pi.pain.line(x, a + 3, x, a, pen_color);
617 pi.pain.line(t, a + 3, t, a, pen_color);
618 pi.pain.line(x, a, x + 3, a, pen_color);
619 pi.pain.line(t - 3, a, t, a, pen_color);
623 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
625 Dimension const dim = dimension(*pi.base.bv);
626 if (previewTooSmall(pi.base, dim)) {
627 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
628 dim.wid, dim.asc + dim.des, backgroundColor(pi));
631 // If there are numbers, the margins around the (displayed)
632 // equation have to be cleared.
634 pi.pain.fillRectangle(pi.leftx, y - dim.asc,
635 pi.rightx - pi.leftx, dim.height(), pi.background_color);
636 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
637 dim.asc + dim.des - 1, pi.backgroundColor(this));
641 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
643 BufferView const * const bv = pi.base.bv;
644 Dimension const dim = dimension(*bv);
646 if (type_ == hullRegexp)
647 pi.pain.rectangle(x + 2, y - dim.ascent() + 1,
648 dim.width() - 3, dim.height() - 2, Color_regexpframe);
650 if (previewState(bv)) {
651 // Do not draw change tracking cue if taken care of by RowPainter
653 Changer dummy = !canPaintChange(*bv) ? make_change(pi.change, Change())
655 if (previewTooSmall(pi.base, dim)) {
656 // we have an extra frame
657 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
659 // one pixel gap in front
660 // value was hardcoded to 1 pixel
661 int const gap = pi.base.bv->zoomedPixels(1) ;
662 preview_->draw(pi, x + gap, y);
667 // First draw the numbers
668 ColorCode color = pi.selected && lyxrc.use_system_colors
669 ? Color_selectiontext : standardColor();
670 bool const really_change_color = pi.base.font.color() == Color_none;
671 Changer dummy0 = really_change_color ? pi.base.font.changeColor(color)
673 if (numberedType()) {
674 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
675 for (row_type row = 0; row < nrows(); ++row) {
676 int yy = y + rowinfo(row).offset[bv];
677 docstring const nl = nicelabel(row);
679 mathed_string_dim(pi.base.font, nl, dimnl);
680 if (math_number == BufferParams::LEFT) {
681 if (dimnl.wid > x - pi.leftx)
682 yy += rowinfo(row).descent + dimnl.asc;
683 pi.draw(pi.leftx, yy, nl);
685 if (dimnl.wid > pi.rightx - x - dim.wid)
686 yy += rowinfo(row).descent + dimnl.asc;
687 pi.draw(pi.rightx - dimnl.wid, yy, nl);
692 // Then the equations
693 Changer dummy1 = pi.base.changeFontSet(standardFont());
694 Changer dummy2 = pi.base.font.changeStyle(display() ? DISPLAY_STYLE
696 InsetMathGrid::draw(pi, x + 1, y);
697 drawMarkers(pi, x, y);
699 // drawing change line
700 if (canPaintChange(*bv)) {
702 int const display_margin = display() ? pi.base.inPixels(Length(12, Length::PT)) : 0;
703 pi.change.paintCue(pi, x + 1, y + 1 - dim.asc + display_margin,
704 x + dim.wid, y + dim.des - display_margin);
709 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
712 InsetMathGrid::metricsT(mi, dim);
715 otexrowstream ots(os);
716 WriteStream wi(ots, false, true, WriteStream::wsDefault);
718 dim.wid = os.str().size();
725 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
728 InsetMathGrid::drawT(pain, x, y);
731 otexrowstream ots(os);
732 WriteStream wi(ots, false, true, WriteStream::wsDefault);
734 pain.draw(x, y, os.str().c_str());
739 static docstring latexString(InsetMathHull const & inset)
742 // This has to be static, because a preview snippet or a math
743 // macro containing math in text mode (such as $\text{$\phi$}$ or
744 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
745 // first time as a whole, and the second time only the inner math.
746 // In this last case inset.buffer() would be invalid.
747 static Encoding const * encoding = 0;
748 if (inset.isBufferValid())
749 encoding = &(inset.buffer().params().encoding());
750 otexrowstream ots(ls);
751 WriteStream wi(ots, false, true, WriteStream::wsPreview, encoding);
757 void InsetMathHull::initUnicodeMath() const
759 // Trigger classification of the unicode symbols in this inset
760 docstring const dummy = latexString(*this);
764 void InsetMathHull::addPreview(DocIterator const & inset_pos,
765 graphics::PreviewLoader & /*ploader*/) const
767 if (RenderPreview::previewMath()) {
768 preparePreview(inset_pos);
773 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
774 MacroNameSet & macros, MacroNameSet & defs) const
776 MacroNameSet::iterator const end = macros.end();
778 for (size_t i = 0; i < md.size(); ++i) {
779 InsetMathMacro const * mi = md[i].nucleus()->asMacro();
780 InsetMathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
781 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
782 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
783 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
784 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
786 // Look for macros in the arguments of this macro.
787 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
788 usedMacros(mi->cell(idx), pos, macros, defs);
789 // Make sure this is a macro defined in the document
790 // (as we also spot the macros in the symbols file)
791 // or that we have not already accounted for it.
792 docstring const name = mi->name();
793 if (macros.find(name) == end)
796 // Look for macros in the definition of this macro.
797 MathData ar(pos.buffer());
798 MacroData const * data =
799 pos.buffer()->getMacro(name, pos, true);
801 odocstringstream macro_def;
802 data->write(macro_def, true);
804 defs.insert(macro_def.str());
805 asArray(data->definition(), ar);
807 usedMacros(ar, pos, macros, defs);
809 MathData ar(pos.buffer());
810 asArray(mt->definition(), ar);
811 usedMacros(ar, pos, macros, defs);
813 if (!si->nuc().empty())
814 usedMacros(si->nuc(), pos, macros, defs);
816 usedMacros(si->down(), pos, macros, defs);
818 usedMacros(si->up(), pos, macros, defs);
819 } else if (fi || gi) {
820 idx_type nidx = fi ? fi->nargs() : gi->nargs();
821 for (idx_type idx = 0; idx < nidx; ++idx)
822 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
825 usedMacros(ni->cell(0), pos, macros, defs);
831 void InsetMathHull::preparePreview(DocIterator const & pos,
832 bool forexport) const
834 // there is no need to do all the macro stuff if we're not
835 // actually going to generate the preview.
836 if (!RenderPreview::previewMath() && !forexport)
839 Buffer const * buffer = pos.buffer();
841 // collect macros at this position
843 buffer->listMacroNames(macros);
845 // collect definitions only for the macros used in this inset
847 for (idx_type idx = 0; idx < nargs(); ++idx)
848 usedMacros(cell(idx), pos, macros, defs);
850 docstring macro_preamble;
851 for (auto const & defvar : defs)
852 macro_preamble.append(defvar);
854 // set the font series and size for this snippet
855 DocIterator dit = pos.getInnerText();
856 Paragraph const & par = dit.paragraph();
857 Font font = par.getFontSettings(buffer->params(), dit.pos());
858 font.fontInfo().realize(par.layout().font);
859 string const lsize = font.latexSize();
862 if (font.fontInfo().series() == BOLD_SERIES) {
863 setfont += from_ascii("\\textbf{");
866 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
867 setfont += from_ascii("\\" + lsize + '\n');
870 if (forexport && haveNumbers()) {
871 docstring eqstr = from_ascii("equation");
872 CounterMap::const_iterator it = counter_map.find(eqstr);
873 if (it != counter_map.end()) {
874 int num = it->second;
876 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
877 '{' + convert<docstring>(num) + '}' + '\n';
879 for (size_t i = 0; i != numcnts; ++i) {
880 docstring cnt = from_ascii(counters_to_save[i]);
881 it = counter_map.find(cnt);
882 if (it == counter_map.end())
884 int num = it->second;
886 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
887 '{' + convert<docstring>(num) + '}';
890 docstring const snippet = macro_preamble + setfont + setcnt
891 + latexString(*this) + endfont;
892 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
893 preview_->addPreview(snippet, *buffer, forexport);
897 void InsetMathHull::reloadPreview(DocIterator const & pos) const
900 preview_->startLoading(*pos.buffer());
904 void InsetMathHull::loadPreview(DocIterator const & pos) const
906 bool const forexport = true;
907 preparePreview(pos, forexport);
908 preview_->startLoading(*pos.buffer(), forexport);
912 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
914 if (RenderPreview::previewMath()) {
916 cur.screenUpdateFlags(Update::Force);
922 docstring InsetMathHull::label(row_type row) const
924 LASSERT(row < nrows(), return docstring());
925 if (InsetLabel * il = label_[row])
926 return il->screenLabel();
931 void InsetMathHull::label(row_type row, docstring const & label)
933 //lyxerr << "setting label '" << label << "' for row " << row << endl;
937 label_[row] = dummy_pointer;
940 label_[row]->updateLabelAndRefs(label);
942 label_[row]->setParam("name", label);
946 InsetCommandParams p(LABEL_CODE);
948 label_[row] = new InsetLabel(buffer_, p);
950 label_[row]->setBuffer(buffer());
954 void InsetMathHull::numbered(row_type row, Numbered num)
956 numbered_[row] = num;
957 if (!numbered(row) && label_[row]) {
964 bool InsetMathHull::numbered(row_type row) const
966 return numbered_[row] == NUMBER;
970 bool InsetMathHull::ams() const
990 for (size_t row = 0; row < numbered_.size(); ++row)
991 if (numbered_[row] == NOTAG)
997 bool InsetMathHull::outerDisplay() const
1020 Inset::DisplayType InsetMathHull::display() const
1037 if (buffer().params().is_math_indent)
1047 int InsetMathHull::indent(BufferView const & bv) const
1049 // FIXME: set this in the textclass. This value is what the article class uses.
1050 static Length default_indent(2.5, Length::EM);
1051 if (display() != Inline && buffer().params().is_math_indent) {
1052 Length const & len = buffer().params().getMathIndent();
1054 return bv.inPixels(default_indent);
1056 return bv.inPixels(len);
1058 return Inset::indent(bv);
1062 bool InsetMathHull::numberedType() const
1081 for (row_type row = 0; row < nrows(); ++row)
1088 void InsetMathHull::validate(LaTeXFeatures & features) const
1090 if (features.runparams().isLaTeX()) {
1092 features.require("amsmath");
1094 if (type_ == hullRegexp) {
1095 features.require("color");
1096 docstring frcol = from_utf8(lcolor.getLaTeXName(Color_regexpframe));
1097 docstring bgcol = from_ascii("white");
1098 features.addPreambleSnippet(
1099 "\\newcommand{\\regexp}[1]{\\fcolorbox{"
1101 + bgcol + "}{\\ensuremath{\\mathtt{#1}}}}");
1102 features.addPreambleSnippet(
1103 from_ascii("\\newcommand{\\endregexp}{}"));
1104 } else if (outerDisplay() && features.inDeletedInset()) {
1105 features.require("tikz");
1106 features.require("ct-tikz-object-sout");
1109 // Validation is necessary only if not using AMS math.
1110 // To be safe, we will always run mathedvalidate.
1111 //if (features.amsstyle)
1114 //features.binom = true;
1115 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
1116 // it would be better to do this elsewhere, but we can't validate in
1117 // InsetMathMatrix and we have no way, outside MathExtern, to know if
1118 // we even have any matrices.
1119 features.addCSSSnippet(
1120 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
1121 "table.matrix td{padding: 0.25px;}\n"
1122 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
1123 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
1125 InsetMathGrid::validate(features);
1129 OutputParams::CtObject InsetMathHull::CtObject(OutputParams const & runparams) const
1131 OutputParams::CtObject res = OutputParams::CT_NORMAL;
1147 case hullMultline: {
1148 if (runparams.inulemcmd
1149 && (!runparams.local_font || runparams.local_font->fontInfo().strikeout() != FONT_ON))
1150 res = OutputParams::CT_UDISPLAYOBJECT;
1152 res = OutputParams::CT_DISPLAYOBJECT;
1160 void InsetMathHull::header_write(WriteStream & os) const
1162 bool n = numberedType();
1173 if (cell(0).empty())
1178 writeMathdisplayPreamble(os);
1182 os << "\\begin{equation" << star(n) << "}\n";
1192 writeMathdisplayPreamble(os);
1195 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1202 os << "\\begin{" << hullName(type_) << star(n) << '}'
1203 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1209 os << "\\begin{" << hullName(type_) << '}'
1210 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1220 os << "\\begin{unknown" << star(n) << "}\n";
1226 void InsetMathHull::footer_write(WriteStream & os) const
1228 bool n = numberedType();
1245 os << "\\end{equation" << star(n) << "}\n";
1248 writeMathdisplayPostamble(os);
1258 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1259 writeMathdisplayPostamble(os);
1266 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1272 os << "\\end{" << hullName(type_) << "}\n";
1276 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1277 os << "\\endregexp{}}";
1283 os << "\\end{unknown" << star(n) << "}\n";
1289 bool InsetMathHull::allowsTabularFeatures() const
1312 bool InsetMathHull::rowChangeOK() const
1315 type_ == hullEqnArray || type_ == hullAlign ||
1316 type_ == hullFlAlign || type_ == hullAlignAt ||
1317 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1318 type_ == hullGather || type_ == hullMultline;
1322 bool InsetMathHull::colChangeOK() const
1325 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1326 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1330 void InsetMathHull::addRow(row_type row)
1335 bool numbered = numberedType();
1336 // Move the number and raw pointer, do not call label() (bug 7511)
1337 InsetLabel * label = dummy_pointer;
1338 docstring number = empty_docstring();
1339 if (type_ == hullMultline) {
1340 if (row + 1 == nrows()) {
1341 numbered_[row] = NONUMBER;
1342 swap(label, label_[row]);
1343 swap(number, numbers_[row]);
1348 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1349 numbers_.insert(numbers_.begin() + row + 1, number);
1350 label_.insert(label_.begin() + row + 1, label);
1351 InsetMathGrid::addRow(row);
1355 void InsetMathHull::swapRow(row_type row)
1359 if (row + 1 == nrows())
1361 swap(numbered_[row], numbered_[row + 1]);
1362 swap(numbers_[row], numbers_[row + 1]);
1363 swap(label_[row], label_[row + 1]);
1364 InsetMathGrid::swapRow(row);
1368 void InsetMathHull::delRow(row_type row)
1370 if (nrows() <= 1 || !rowChangeOK())
1372 if (row + 1 == nrows() && type_ == hullMultline) {
1373 swap(numbered_[row - 1], numbered_[row]);
1374 swap(numbers_[row - 1], numbers_[row]);
1375 swap(label_[row - 1], label_[row]);
1376 InsetMathGrid::delRow(row);
1379 InsetMathGrid::delRow(row);
1380 // The last dummy row has no number info nor a label.
1381 // Test nrows() + 1 because we have already erased the row.
1382 if (row == nrows() + 1)
1384 numbered_.erase(numbered_.begin() + row);
1385 numbers_.erase(numbers_.begin() + row);
1387 label_.erase(label_.begin() + row);
1391 void InsetMathHull::addCol(col_type col)
1395 InsetMathGrid::addCol(col);
1399 void InsetMathHull::delCol(col_type col)
1401 if (ncols() <= 1 || !colChangeOK())
1403 InsetMathGrid::delCol(col);
1407 docstring InsetMathHull::nicelabel(row_type row) const
1411 docstring const & val = numbers_[row];
1413 return '(' + val + ')';
1414 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1418 void InsetMathHull::glueall(HullType type)
1421 for (idx_type i = 0; i < nargs(); ++i)
1423 InsetLabel * label = 0;
1424 if (type == hullEquation) {
1425 // preserve first non-empty label
1426 for (row_type row = 0; row < nrows(); ++row) {
1428 label = label_[row];
1434 *this = InsetMathHull(buffer_, hullSimple);
1441 void InsetMathHull::splitTo2Cols()
1443 LASSERT(ncols() == 1, return);
1444 InsetMathGrid::addCol(1);
1445 for (row_type row = 0; row < nrows(); ++row) {
1446 idx_type const i = 2 * row;
1447 pos_type pos = firstRelOp(cell(i));
1448 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1449 cell(i).erase(pos, cell(i).size());
1454 void InsetMathHull::splitTo3Cols()
1456 LASSERT(ncols() < 3, return);
1459 InsetMathGrid::addCol(2);
1460 for (row_type row = 0; row < nrows(); ++row) {
1461 idx_type const i = 3 * row + 1;
1462 if (!cell(i).empty()) {
1463 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1464 cell(i).erase(1, cell(i).size());
1470 void InsetMathHull::changeCols(col_type cols)
1472 if (ncols() == cols)
1474 else if (ncols() < cols) {
1480 while (ncols() < cols)
1481 InsetMathGrid::addCol(ncols());
1487 for (row_type row = 0; row < nrows(); ++row) {
1488 idx_type const i = row * ncols();
1489 for (col_type col = cols; col < ncols(); ++col) {
1490 cell(i + cols - 1).append(cell(i + col));
1494 while (ncols() > cols) {
1495 InsetMathGrid::delCol(ncols() - 1);
1500 HullType InsetMathHull::getType() const
1506 void InsetMathHull::setType(HullType type)
1513 bool InsetMathHull::isMutable(HullType type)
1537 void InsetMathHull::mutate(HullType newtype)
1539 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1541 if (newtype == type_)
1544 // This guards the algorithm below it, which is designed with certain types
1546 if (!isMutable(newtype) || !isMutable(type_)) {
1547 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1548 << "' to '" << to_utf8(hullName(newtype))
1549 << "' not implemented" << endl;
1553 // we try to move along the chain
1554 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1556 // +-------------------------------------+
1557 // we use eqnarray as intermediate type for mutations that are not
1558 // directly supported because it handles labels and numbering for
1563 setType(hullSimple);
1569 if (newtype == hullNone) {
1573 setType(hullEquation);
1574 numbered(0, label_[0] ? true : false);
1583 setType(hullSimple);
1588 // split it "nicely" on the first relop
1590 setType(hullEqnArray);
1598 // split it "nicely"
1633 setType(hullEqnArray);
1642 for (row_type row = 0; row < nrows(); ++row)
1643 numbered(row, false);
1653 for (row_type row = 0; row < nrows(); ++row)
1654 numbered(row, false);
1661 setType(hullEqnArray);
1691 for (row_type row = 0; row < nrows(); ++row)
1692 numbered(row, false);
1696 // first we mutate to EqnArray
1698 setType(hullEqnArray);
1705 // we passed the guard so we should not be here
1706 LYXERR0("Mutation not implemented, but should have been.");
1707 LASSERT(false, return);
1713 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1714 bool last_eoln) const
1717 if (numberedType()) {
1718 if (label_[row] && numbered(row)) {
1719 docstring const name =
1720 latex ? escape(label_[row]->getParam("name"))
1721 : label_[row]->getParam("name");
1722 res += "\\label{" + name + '}';
1724 if (type_ != hullMultline) {
1725 if (numbered_[row] == NONUMBER)
1726 res += "\\nonumber ";
1727 else if (numbered_[row] == NOTAG)
1731 // Never add \\ on the last empty line of eqnarray and friends
1733 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1736 void InsetMathHull::write(WriteStream & os) const
1738 ModeSpecifier specifier(os, MATH_MODE);
1740 InsetMathGrid::write(os);
1745 void InsetMathHull::normalize(NormalStream & os) const
1747 os << "[formula " << hullName(type_) << ' ';
1748 InsetMathGrid::normalize(os);
1753 void InsetMathHull::infoize(odocstream & os) const
1755 os << bformat(_("Type: %1$s"), hullName(type_));
1759 void InsetMathHull::check() const
1761 LATTEST(numbered_.size() == nrows());
1762 LATTEST(numbers_.size() == nrows());
1763 LATTEST(label_.size() == nrows());
1767 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1769 //FIXME: sort out whether we want std::string or docstring for those
1770 string const lang = func.getArg(0);
1771 docstring extra = from_utf8(func.getArg(1));
1773 extra = from_ascii("noextra");
1775 // replace selection with result of computation
1776 if (reduceSelectionToOneCell(cur)) {
1778 asArray(grabAndEraseSelection(cur), ar);
1779 lyxerr << "use selection: " << ar << endl;
1780 cur.insert(pipeThroughExtern(lang, extra, ar));
1784 // only inline, display or eqnarray math is allowed
1785 switch (getType()) {
1791 frontend::Alert::warning(_("Bad math environment"),
1792 _("Computation cannot be performed for AMS "
1793 "math environments.\nChange the math "
1794 "formula type and try again."));
1799 eq.push_back(MathAtom(new InsetMathChar('=')));
1801 // go to first item in line
1802 cur.idx() -= cur.idx() % ncols();
1805 if (getType() == hullSimple) {
1806 size_type pos = cur.cell().find_last(eq);
1808 if (pos == cur.cell().size()) {
1810 lyxerr << "use whole cell: " << ar << endl;
1812 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1813 lyxerr << "use partial cell form pos: " << pos << endl;
1815 cur.cell().append(eq);
1816 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1817 cur.pos() = cur.lastpos();
1821 if (getType() == hullEquation) {
1822 lyxerr << "use equation inset" << endl;
1823 mutate(hullEqnArray);
1824 MathData & ar = cur.cell();
1825 lyxerr << "use cell: " << ar << endl;
1829 cur.cell() = pipeThroughExtern(lang, extra, ar);
1830 // move to end of line
1831 cur.pos() = cur.lastpos();
1836 lyxerr << "use eqnarray" << endl;
1837 cur.idx() += 2 - cur.idx() % ncols();
1839 MathData ar = cur.cell();
1840 lyxerr << "use cell: " << ar << endl;
1841 // FIXME: temporarily disabled
1847 cur.cell() = pipeThroughExtern(lang, extra, ar);
1848 cur.pos() = cur.lastpos();
1853 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1855 //lyxerr << "action: " << cmd.action() << endl;
1856 switch (cmd.action()) {
1858 case LFUN_FINISHED_BACKWARD:
1859 case LFUN_FINISHED_FORWARD:
1860 case LFUN_FINISHED_RIGHT:
1861 case LFUN_FINISHED_LEFT:
1862 //lyxerr << "action: " << cmd.action() << endl;
1863 InsetMathGrid::doDispatch(cur, cmd);
1866 case LFUN_PARAGRAPH_BREAK:
1867 // just swallow this
1870 case LFUN_NEWLINE_INSERT:
1871 // some magic for the common case
1872 if (type_ == hullSimple || type_ == hullEquation) {
1873 cur.recordUndoInset();
1875 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1876 mutate(align ? hullAlign : hullEqnArray);
1877 // mutate() may change labels and such.
1878 cur.forceBufferUpdate();
1879 cur.idx() = nrows() * ncols() - 1;
1880 cur.pos() = cur.lastpos();
1882 InsetMathGrid::doDispatch(cur, cmd);
1885 case LFUN_MATH_NUMBER_TOGGLE: {
1886 //lyxerr << "toggling all numbers" << endl;
1887 cur.recordUndoInset();
1888 bool old = numberedType();
1889 if (type_ == hullMultline)
1890 numbered(nrows() - 1, !old);
1892 for (row_type row = 0; row < nrows(); ++row)
1893 numbered(row, !old);
1895 cur.message(old ? _("No number") : _("Number"));
1896 cur.forceBufferUpdate();
1900 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1901 cur.recordUndoInset();
1902 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1903 bool old = numbered(r);
1904 cur.message(old ? _("No number") : _("Number"));
1906 cur.forceBufferUpdate();
1910 case LFUN_LABEL_INSERT: {
1911 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1912 docstring old_label = label(r);
1913 docstring const default_label = from_ascii("eq:");
1914 if (old_label.empty())
1915 old_label = default_label;
1917 InsetCommandParams p(LABEL_CODE);
1918 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1919 string const data = InsetCommand::params2string(p);
1921 if (cmd.argument().empty())
1922 cur.bv().showDialog("label", data);
1924 FuncRequest fr(LFUN_INSET_INSERT, data);
1930 case LFUN_LABEL_COPY_AS_REFERENCE: {
1932 if (cmd.argument().empty() && &cur.inset() == this)
1933 // if there is no argument and we're inside math, we retrieve
1934 // the row number from the cursor position.
1935 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1937 // if there is an argument, find the corresponding label, else
1938 // check whether there is at least one label.
1939 for (row = 0; row != nrows(); ++row)
1940 if (numbered(row) && label_[row]
1941 && (cmd.argument().empty() || label(row) == cmd.argument()))
1948 InsetCommandParams p(REF_CODE, "ref");
1949 p["reference"] = label(row);
1950 cap::clearSelection();
1951 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1955 case LFUN_WORD_DELETE_FORWARD:
1956 case LFUN_CHAR_DELETE_FORWARD:
1957 if (col(cur.idx()) + 1 == ncols()
1958 && cur.pos() == cur.lastpos()
1959 && !cur.selection()) {
1960 if (!label(row(cur.idx())).empty()) {
1961 cur.recordUndoInset();
1962 label(row(cur.idx()), docstring());
1963 } else if (numbered(row(cur.idx()))) {
1964 cur.recordUndoInset();
1965 numbered(row(cur.idx()), false);
1966 cur.forceBufferUpdate();
1968 InsetMathGrid::doDispatch(cur, cmd);
1972 InsetMathGrid::doDispatch(cur, cmd);
1977 case LFUN_INSET_INSERT: {
1978 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1979 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1980 string const name = cmd.getArg(0);
1981 if (name == "label") {
1982 InsetCommandParams p(LABEL_CODE);
1983 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1984 docstring str = p["name"];
1985 cur.recordUndoInset();
1986 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1990 docstring old = label(r);
1993 // The label will take care of the reference update.
1997 // Newly created inset so initialize it.
1998 label_[r]->initView();
2001 cur.forceBufferUpdate();
2004 InsetMathGrid::doDispatch(cur, cmd);
2008 case LFUN_MATH_EXTERN:
2009 cur.recordUndoInset();
2013 case LFUN_MATH_MUTATE: {
2014 cur.recordUndoInset();
2015 row_type row = cur.row();
2016 col_type col = cur.col();
2017 mutate(hullType(cmd.argument()));
2018 cur.idx() = row * ncols() + col;
2019 if (cur.idx() > cur.lastidx()) {
2020 cur.idx() = cur.lastidx();
2021 cur.pos() = cur.lastpos();
2023 if (cur.pos() > cur.lastpos())
2024 cur.pos() = cur.lastpos();
2026 cur.forceBufferUpdate();
2027 // FIXME: find some more clever handling of the selection,
2028 // i.e. preserve it.
2029 cur.clearSelection();
2030 //cur.dispatched(FINISHED);
2034 case LFUN_MATH_DISPLAY: {
2035 cur.recordUndoInset();
2036 mutate(type_ == hullSimple ? hullEquation : hullSimple);
2037 // if the cursor is in a cell that got merged, move it to
2038 // start of the hull inset.
2039 if (cur.idx() > 0) {
2043 if (cur.pos() > cur.lastpos())
2044 cur.pos() = cur.lastpos();
2049 case LFUN_TABULAR_FEATURE:
2050 if (!allowsTabularFeatures())
2053 InsetMathGrid::doDispatch(cur, cmd);
2057 InsetMathGrid::doDispatch(cur, cmd);
2065 bool allowDisplayMath(Cursor const & cur)
2067 LATTEST(cur.depth() > 1);
2068 Cursor tmpcur = cur;
2071 FuncRequest cmd(LFUN_MATH_DISPLAY);
2072 return tmpcur.getStatus(cmd, status) && status.enabled();
2078 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
2079 FuncStatus & status) const
2081 switch (cmd.action()) {
2082 case LFUN_FINISHED_BACKWARD:
2083 case LFUN_FINISHED_FORWARD:
2084 case LFUN_FINISHED_RIGHT:
2085 case LFUN_FINISHED_LEFT:
2088 case LFUN_NEWLINE_INSERT:
2089 case LFUN_MATH_EXTERN:
2091 status.setEnabled(true);
2094 // we never allow this in math, and we want to bind enter
2095 // to another actions in command-alternatives
2096 case LFUN_PARAGRAPH_BREAK:
2097 status.setEnabled(false);
2099 case LFUN_MATH_MUTATE: {
2100 HullType const ht = hullType(cmd.argument());
2101 status.setOnOff(type_ == ht);
2102 status.setEnabled(isMutable(ht) && isMutable(type_));
2104 if (ht != hullSimple && status.enabled())
2105 status.setEnabled(allowDisplayMath(cur));
2108 case LFUN_MATH_DISPLAY: {
2109 status.setEnabled(display() != Inline || allowDisplayMath(cur));
2110 status.setOnOff(display() != Inline);
2114 case LFUN_MATH_NUMBER_TOGGLE:
2115 // FIXME: what is the right test, this or the one of
2117 status.setEnabled(display() != Inline);
2118 status.setOnOff(numberedType());
2121 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
2122 // FIXME: what is the right test, this or the one of
2124 bool const enable = (type_ == hullMultline)
2125 ? (nrows() - 1 == cur.row())
2126 : display() != Inline;
2127 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2128 status.setEnabled(enable);
2129 status.setOnOff(enable && numbered(r));
2133 case LFUN_LABEL_INSERT:
2134 status.setEnabled(type_ != hullSimple);
2137 case LFUN_LABEL_COPY_AS_REFERENCE: {
2138 bool enabled = false;
2139 if (cmd.argument().empty() && &cur.inset() == this) {
2140 // if there is no argument and we're inside math, we retrieve
2141 // the row number from the cursor position.
2142 row_type row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2143 enabled = numberedType() && label_[row] && numbered(row);
2145 // if there is an argument, find the corresponding label, else
2146 // check whether there is at least one label.
2147 for (row_type row = 0; row != nrows(); ++row) {
2148 if (numbered(row) && label_[row] &&
2149 (cmd.argument().empty() || label(row) == cmd.argument())) {
2155 status.setEnabled(enabled);
2159 case LFUN_INSET_INSERT:
2160 if (cmd.getArg(0) == "label") {
2161 status.setEnabled(type_ != hullSimple);
2164 return InsetMathGrid::getStatus(cur, cmd, status);
2166 case LFUN_TABULAR_FEATURE: {
2167 if (!allowsTabularFeatures())
2169 string s = cmd.getArg(0);
2171 && (s == "append-row"
2172 || s == "delete-row"
2173 || s == "copy-row")) {
2174 status.message(bformat(
2175 from_utf8(N_("Can't change number of rows in '%1$s'")),
2177 status.setEnabled(false);
2181 && (s == "append-column"
2182 || s == "delete-column"
2183 || s == "copy-column")) {
2184 status.message(bformat(
2185 from_utf8(N_("Can't change number of columns in '%1$s'")),
2187 status.setEnabled(false);
2190 if (s == "add-vline-left" || s == "add-vline-right") {
2191 status.message(bformat(
2192 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2194 status.setEnabled(false);
2197 if (s == "valign-top" || s == "valign-middle"
2198 || s == "valign-bottom" || s == "align-left"
2199 || s == "align-center" || s == "align-right") {
2200 status.setEnabled(false);
2203 return InsetMathGrid::getStatus(cur, cmd, status);
2207 return InsetMathGrid::getStatus(cur, cmd, status);
2212 int InsetMathHull::leftMargin() const
2214 return (getType() == hullSimple) ? 0 : InsetMathGrid::leftMargin();
2218 int InsetMathHull::rightMargin() const
2220 return (getType() == hullSimple) ? 0 : InsetMathGrid::rightMargin();
2224 int InsetMathHull::border() const
2226 return (getType() == hullSimple) ? 0 : InsetMathGrid::border();
2230 /////////////////////////////////////////////////////////////////////
2234 // simply scrap this function if you want
2235 void InsetMathHull::mutateToText()
2238 // translate to latex
2240 latex(os, false, false);
2241 string str = os.str();
2244 Text * lt = view_->cursor().innerText();
2245 string::const_iterator cit = str.begin();
2246 string::const_iterator end = str.end();
2247 for (; cit != end; ++cit)
2248 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2251 //dispatch(LFUN_ESCAPE);
2256 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2257 docstring const & font)
2259 // this whole function is a hack and won't work for incremental font
2262 if (cur.inset().asInsetMath()->name() == font)
2263 cur.handleFont(to_utf8(font));
2265 cur.handleNest(createInsetMath(font, cur.buffer()));
2271 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2276 font.fromString(to_utf8(arg), b);
2277 if (font.fontInfo().color() != Color_inherit) {
2278 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2284 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2286 InsetMathNest::edit(cur, front, entry_from);
2287 // The inset formula dimension is not necessarily the same as the
2288 // one of the instant preview image, so we have to indicate to the
2289 // BufferView that a metrics update is needed.
2290 cur.screenUpdateFlags(Update::Force);
2294 /////////////////////////////////////////////////////////////////////
2298 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2301 // FIXME: completely broken
2302 static InsetMathHull * lastformula = 0;
2303 static CursorBase current = DocIterator(ibegin(nucleus()));
2305 static string laststr;
2307 if (lastformula != this || laststr != str) {
2308 //lyxerr << "reset lastformula to " << this << endl;
2311 current = ibegin(nucleus());
2313 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2317 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2319 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2320 CursorSlice & top = it.back();
2321 MathData const & a = top.asInsetMath()->cell(top.idx_);
2322 if (a.matchpart(ar, top.pos_)) {
2323 bv->cursor().setSelection(it, ar.size());
2325 top.pos_ += ar.size();
2331 //lyxerr << "not found!" << endl;
2338 void InsetMathHull::write(ostream & os) const
2340 odocstringstream oss;
2341 otexrowstream ots(oss);
2342 WriteStream wi(ots, false, false, WriteStream::wsDefault);
2345 os << to_utf8(oss.str());
2349 void InsetMathHull::read(Lexer & lex)
2352 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2353 operator=(*at->asHullInset());
2357 bool InsetMathHull::readQuiet(Lexer & lex)
2360 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2362 operator=(*at->asHullInset());
2367 int InsetMathHull::plaintext(odocstringstream & os,
2368 OutputParams const & op, size_t max_length) const
2370 // Try enabling this now that there is a flag as requested at #2275.
2371 if (buffer().isExporting() && display()) {
2375 TextPainter tpain(dim.width(), dim.height());
2376 drawT(tpain, 0, dim.ascent());
2378 // reset metrics cache to "real" values
2380 return tpain.textheight();
2383 odocstringstream oss;
2384 otexrowstream ots(oss);
2385 Encoding const * const enc = encodings.fromLyXName("utf8");
2386 WriteStream wi(ots, false, true, WriteStream::wsDefault, enc);
2389 if (type_ == hullRegexp)
2392 for (row_type r = 0; r < nrows(); ++r) {
2393 for (col_type c = 0; c < ncols(); ++c)
2394 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2395 // if it's for the TOC, we write just the first line
2396 // and do not include the newline.
2397 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2399 if (r < nrows() - 1)
2403 docstring const str = oss.str();
2409 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
2414 if (getType() == hullSimple)
2415 name = from_ascii("inlineequation");
2417 name = from_ascii("informalequation");
2419 docstring bname = name;
2420 if (!label(0).empty())
2421 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
2423 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
2425 odocstringstream ls;
2427 if (runparams.flavor == OutputParams::XML) {
2428 ms << MTag("alt role='tex' ");
2429 // Workaround for db2latex: db2latex always includes equations with
2430 // \ensuremath{} or \begin{display}\end{display}
2431 // so we strip LyX' math environment
2432 WriteStream wi(ols, false, false, WriteStream::wsDefault, runparams.encoding);
2433 InsetMathGrid::write(wi);
2434 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2439 InsetMathGrid::mathmlize(ms);
2442 ms << MTag("alt role='tex'");
2443 latex(ols, runparams);
2444 res = ols.texrow().rows();
2445 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2449 ms << from_ascii("<graphic fileref=\"eqn/");
2450 if (!label(0).empty())
2451 ms << sgml::cleanID(buffer(), runparams, label(0));
2453 ms << sgml::uniqueID(from_ascii("anon"));
2455 if (runparams.flavor == OutputParams::XML)
2456 ms << from_ascii("\"/>");
2458 ms << from_ascii("\">");
2460 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2462 return ms.line() + res;
2466 bool InsetMathHull::haveNumbers() const
2468 bool havenumbers = false;
2469 // inline formulas are never numbered (bug 7351 part 3)
2470 if (getType() == hullSimple)
2472 for (size_t i = 0; i != numbered_.size(); ++i) {
2483 // We need to do something about alignment here.
2485 // This duplicates code from InsetMathGrid, but
2486 // we need access here to number information,
2487 // and we simply do not have that in InsetMathGrid.
2488 void InsetMathHull::htmlize(HtmlStream & os) const
2490 bool const havenumbers = haveNumbers();
2491 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2494 os << cell(index(0, 0));
2498 os << MTag("table", "class='mathtable'");
2499 for (row_type row = 0; row < nrows(); ++row) {
2501 for (col_type col = 0; col < ncols(); ++col) {
2503 os << cell(index(row, col));
2508 docstring const & num = numbers_[row];
2510 os << '(' << num << ')';
2515 os << ETag("table");
2519 // this duplicates code from InsetMathGrid, but
2520 // we need access here to number information,
2521 // and we simply do not have that in InsetMathGrid.
2522 void InsetMathHull::mathmlize(MathStream & os) const
2524 bool const havenumbers = haveNumbers();
2525 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2528 os << MTag("mtable");
2529 char const * const celltag = havetable ? "mtd" : "mrow";
2530 // FIXME There does not seem to be wide support at the moment
2531 // for mlabeledtr, so we have to use just mtr for now.
2532 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2533 char const * const rowtag = "mtr";
2534 for (row_type row = 0; row < nrows(); ++row) {
2537 for (col_type col = 0; col < ncols(); ++col) {
2539 << cell(index(row, col))
2545 docstring const & num = numbers_[row];
2547 os << '(' << num << ')';
2554 os << ETag("mtable");
2558 void InsetMathHull::mathAsLatex(WriteStream & os) const
2560 MathEnsurer ensurer(os, false);
2561 bool havenumbers = haveNumbers();
2562 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2565 os << cell(index(0, 0));
2569 os << "<table class='mathtable'>";
2570 for (row_type row = 0; row < nrows(); ++row) {
2572 for (col_type col = 0; col < ncols(); ++col) {
2573 os << "<td class='math'>";
2574 os << cell(index(row, col));
2579 docstring const & num = numbers_[row];
2581 os << '(' << num << ')';
2590 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2592 BufferParams::MathOutput const mathtype =
2593 buffer().masterBuffer()->params().html_math_output;
2595 bool success = false;
2597 // we output all the labels just at the beginning of the equation.
2598 // this should be fine.
2599 for (size_t i = 0; i != label_.size(); ++i) {
2600 InsetLabel const * const il = label_[i];
2606 // FIXME Eventually we would like to do this inset by inset.
2607 if (mathtype == BufferParams::MathML) {
2608 odocstringstream os;
2613 } catch (MathExportException const &) {}
2615 if (getType() == hullSimple)
2616 xs << html::StartTag("math",
2617 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2619 xs << html::StartTag("math",
2620 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2621 xs << XHTMLStream::ESCAPE_NONE
2623 << html::EndTag("math");
2625 } else if (mathtype == BufferParams::HTML) {
2626 odocstringstream os;
2631 } catch (MathExportException const &) {}
2633 string const tag = (getType() == hullSimple) ? "span" : "div";
2634 xs << html::StartTag(tag, "class='formula'", true)
2635 << XHTMLStream::ESCAPE_NONE
2637 << html::EndTag(tag);
2641 // what we actually want is this:
2643 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2645 // || mathtype == BufferParams::Images
2647 // but what follows is equivalent, since we'll enter only if either (a) we
2648 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2649 // aren't doing LaTeX.
2651 // so this is for Images.
2652 if (!success && mathtype != BufferParams::LaTeX) {
2653 graphics::PreviewImage const * pimage = 0;
2655 loadPreview(docit_);
2656 pimage = preview_->getPreviewImage(buffer());
2657 // FIXME Do we always have png?
2660 if (pimage || op.dryrun) {
2661 string const filename = pimage ? pimage->filename().onlyFileName()
2662 : "previewimage.png";
2664 // if we are not in the master buffer, then we need to see that the
2665 // generated image is copied there; otherwise, preview fails.
2666 Buffer const * mbuf = buffer().masterBuffer();
2667 if (mbuf != &buffer()) {
2668 string mbtmp = mbuf->temppath();
2669 FileName const mbufimg(support::addName(mbtmp, filename));
2670 pimage->filename().copyTo(mbufimg);
2672 // add the file to the list of files to be exported
2673 op.exportdata->addExternalFile("xhtml", pimage->filename());
2676 string const tag = (getType() == hullSimple) ? "span" : "div";
2678 << html::StartTag(tag, "style = \"text-align: center;\"")
2679 << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2680 << html::EndTag(tag)
2686 // so we'll pass this test if we've failed everything else, or
2687 // if mathtype was LaTeX, since we won't have entered any of the
2689 if (!success /* || mathtype != BufferParams::LaTeX */) {
2690 // Unfortunately, we cannot use latexString() because we do not want
2691 // $...$ or whatever.
2692 odocstringstream ls;
2693 otexrowstream ots(ls);
2694 WriteStream wi(ots, false, true, WriteStream::wsPreview);
2695 ModeSpecifier specifier(wi, MATH_MODE);
2697 docstring const latex = ls.str();
2699 // class='math' allows for use of jsMath
2700 // http://www.math.union.edu/~dpvc/jsMath/
2702 // probably should allow for some kind of customization here
2703 string const tag = (getType() == hullSimple) ? "span" : "div";
2704 xs << html::StartTag(tag, "class='math'")
2706 << html::EndTag(tag)
2713 void InsetMathHull::toString(odocstream & os) const
2715 odocstringstream ods;
2716 plaintext(ods, OutputParams(0));
2721 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2723 odocstringstream ods;
2726 // FIXME: this results in spilling TeX into the LyXHTML output since the
2727 // outliner is used to generate the LyXHTML list of figures/etc.
2733 string InsetMathHull::contextMenuName() const
2735 return "context-math";
2739 void InsetMathHull::recordLocation(DocIterator const & di)
2745 bool InsetMathHull::canPaintChange(BufferView const &) const
2747 // We let RowPainter do it seamlessly for inline insets
2748 return display() != Inline;