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)
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);
333 InsetMathGrid::updateBuffer(it, utype);
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.mustProvide("ct-dvipost")) {
1106 features.require("tikz");
1107 features.require("ct-tikz-object-sout");
1110 // Validation is necessary only if not using AMS math.
1111 // To be safe, we will always run mathedvalidate.
1112 //if (features.amsstyle)
1115 //features.binom = true;
1116 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
1117 // it would be better to do this elsewhere, but we can't validate in
1118 // InsetMathMatrix and we have no way, outside MathExtern, to know if
1119 // we even have any matrices.
1120 features.addCSSSnippet(
1121 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
1122 "table.matrix td{padding: 0.25px;}\n"
1123 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
1124 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
1126 InsetMathGrid::validate(features);
1130 OutputParams::CtObject InsetMathHull::CtObject(OutputParams const & runparams) const
1132 OutputParams::CtObject res = OutputParams::CT_NORMAL;
1148 case hullMultline: {
1149 if (runparams.inulemcmd
1150 && (!runparams.local_font || runparams.local_font->fontInfo().strikeout() != FONT_ON))
1151 res = OutputParams::CT_UDISPLAYOBJECT;
1153 res = OutputParams::CT_DISPLAYOBJECT;
1161 void InsetMathHull::header_write(WriteStream & os) const
1163 bool n = numberedType();
1174 if (cell(0).empty())
1179 writeMathdisplayPreamble(os);
1183 os << "\\begin{equation" << star(n) << "}\n";
1193 writeMathdisplayPreamble(os);
1196 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1203 os << "\\begin{" << hullName(type_) << star(n) << '}'
1204 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1210 os << "\\begin{" << hullName(type_) << '}'
1211 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1221 os << "\\begin{unknown" << star(n) << "}\n";
1227 void InsetMathHull::footer_write(WriteStream & os) const
1229 bool n = numberedType();
1246 os << "\\end{equation" << star(n) << "}\n";
1249 writeMathdisplayPostamble(os);
1259 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1260 writeMathdisplayPostamble(os);
1267 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1273 os << "\\end{" << hullName(type_) << "}\n";
1277 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1278 os << "\\endregexp{}}";
1284 os << "\\end{unknown" << star(n) << "}\n";
1290 bool InsetMathHull::allowsTabularFeatures() const
1313 bool InsetMathHull::rowChangeOK() const
1316 type_ == hullEqnArray || type_ == hullAlign ||
1317 type_ == hullFlAlign || type_ == hullAlignAt ||
1318 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1319 type_ == hullGather || type_ == hullMultline;
1323 bool InsetMathHull::colChangeOK() const
1326 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1327 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1331 void InsetMathHull::addRow(row_type row)
1336 bool numbered = numberedType();
1337 // Move the number and raw pointer, do not call label() (bug 7511)
1338 InsetLabel * label = dummy_pointer;
1339 docstring number = empty_docstring();
1340 if (type_ == hullMultline) {
1341 if (row + 1 == nrows()) {
1342 numbered_[row] = NONUMBER;
1343 swap(label, label_[row]);
1344 swap(number, numbers_[row]);
1349 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1350 numbers_.insert(numbers_.begin() + row + 1, number);
1351 label_.insert(label_.begin() + row + 1, label);
1352 InsetMathGrid::addRow(row);
1356 void InsetMathHull::swapRow(row_type row)
1360 if (row + 1 == nrows())
1362 swap(numbered_[row], numbered_[row + 1]);
1363 swap(numbers_[row], numbers_[row + 1]);
1364 swap(label_[row], label_[row + 1]);
1365 InsetMathGrid::swapRow(row);
1369 void InsetMathHull::delRow(row_type row)
1371 if (nrows() <= 1 || !rowChangeOK())
1373 if (row + 1 == nrows() && type_ == hullMultline) {
1374 swap(numbered_[row - 1], numbered_[row]);
1375 swap(numbers_[row - 1], numbers_[row]);
1376 swap(label_[row - 1], label_[row]);
1377 InsetMathGrid::delRow(row);
1380 InsetMathGrid::delRow(row);
1381 // The last dummy row has no number info nor a label.
1382 // Test nrows() + 1 because we have already erased the row.
1383 if (row == nrows() + 1)
1385 numbered_.erase(numbered_.begin() + row);
1386 numbers_.erase(numbers_.begin() + row);
1388 label_.erase(label_.begin() + row);
1392 void InsetMathHull::addCol(col_type col)
1396 InsetMathGrid::addCol(col);
1400 void InsetMathHull::delCol(col_type col)
1402 if (ncols() <= 1 || !colChangeOK())
1404 InsetMathGrid::delCol(col);
1408 docstring InsetMathHull::nicelabel(row_type row) const
1412 docstring const & val = numbers_[row];
1414 return '(' + val + ')';
1415 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1419 void InsetMathHull::glueall(HullType type)
1422 for (idx_type i = 0; i < nargs(); ++i)
1424 InsetLabel * label = 0;
1425 if (type == hullEquation) {
1426 // preserve first non-empty label
1427 for (row_type row = 0; row < nrows(); ++row) {
1429 label = label_[row];
1435 *this = InsetMathHull(buffer_, hullSimple);
1442 void InsetMathHull::splitTo2Cols()
1444 LASSERT(ncols() == 1, return);
1445 InsetMathGrid::addCol(1);
1446 for (row_type row = 0; row < nrows(); ++row) {
1447 idx_type const i = 2 * row;
1448 pos_type pos = firstRelOp(cell(i));
1449 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1450 cell(i).erase(pos, cell(i).size());
1455 void InsetMathHull::splitTo3Cols()
1457 LASSERT(ncols() < 3, return);
1460 InsetMathGrid::addCol(2);
1461 for (row_type row = 0; row < nrows(); ++row) {
1462 idx_type const i = 3 * row + 1;
1463 if (!cell(i).empty()) {
1464 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1465 cell(i).erase(1, cell(i).size());
1471 void InsetMathHull::changeCols(col_type cols)
1473 if (ncols() == cols)
1475 else if (ncols() < cols) {
1481 while (ncols() < cols)
1482 InsetMathGrid::addCol(ncols());
1488 for (row_type row = 0; row < nrows(); ++row) {
1489 idx_type const i = row * ncols();
1490 for (col_type col = cols; col < ncols(); ++col) {
1491 cell(i + cols - 1).append(cell(i + col));
1495 while (ncols() > cols) {
1496 InsetMathGrid::delCol(ncols() - 1);
1501 HullType InsetMathHull::getType() const
1507 void InsetMathHull::setType(HullType type)
1514 bool InsetMathHull::isMutable(HullType type)
1538 void InsetMathHull::mutate(HullType newtype)
1540 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1542 if (newtype == type_)
1545 // This guards the algorithm below it, which is designed with certain types
1547 if (!isMutable(newtype) || !isMutable(type_)) {
1548 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1549 << "' to '" << to_utf8(hullName(newtype))
1550 << "' not implemented" << endl;
1554 // we try to move along the chain
1555 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1557 // +-------------------------------------+
1558 // we use eqnarray as intermediate type for mutations that are not
1559 // directly supported because it handles labels and numbering for
1564 setType(hullSimple);
1570 if (newtype == hullNone) {
1574 setType(hullEquation);
1575 numbered(0, label_[0] ? true : false);
1584 setType(hullSimple);
1589 // split it "nicely" on the first relop
1591 setType(hullEqnArray);
1599 // split it "nicely"
1634 setType(hullEqnArray);
1643 for (row_type row = 0; row < nrows(); ++row)
1644 numbered(row, false);
1654 for (row_type row = 0; row < nrows(); ++row)
1655 numbered(row, false);
1662 setType(hullEqnArray);
1692 for (row_type row = 0; row < nrows(); ++row)
1693 numbered(row, false);
1697 // first we mutate to EqnArray
1699 setType(hullEqnArray);
1706 // we passed the guard so we should not be here
1707 LYXERR0("Mutation not implemented, but should have been.");
1708 LASSERT(false, return);
1714 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1715 bool last_eoln) const
1718 if (numberedType()) {
1719 if (label_[row] && numbered(row)) {
1720 docstring const name =
1721 latex ? escape(label_[row]->getParam("name"))
1722 : label_[row]->getParam("name");
1723 res += "\\label{" + name + '}';
1725 if (type_ != hullMultline) {
1726 if (numbered_[row] == NONUMBER)
1727 res += "\\nonumber ";
1728 else if (numbered_[row] == NOTAG)
1732 // Never add \\ on the last empty line of eqnarray and friends
1734 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1737 void InsetMathHull::write(WriteStream & os) const
1739 ModeSpecifier specifier(os, MATH_MODE);
1741 InsetMathGrid::write(os);
1746 void InsetMathHull::normalize(NormalStream & os) const
1748 os << "[formula " << hullName(type_) << ' ';
1749 InsetMathGrid::normalize(os);
1754 void InsetMathHull::infoize(odocstream & os) const
1756 os << bformat(_("Type: %1$s"), hullName(type_));
1760 void InsetMathHull::check() const
1762 LATTEST(numbered_.size() == nrows());
1763 LATTEST(numbers_.size() == nrows());
1764 LATTEST(label_.size() == nrows());
1768 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1770 //FIXME: sort out whether we want std::string or docstring for those
1771 string const lang = func.getArg(0);
1772 docstring extra = from_utf8(func.getArg(1));
1774 extra = from_ascii("noextra");
1776 // replace selection with result of computation
1777 if (reduceSelectionToOneCell(cur)) {
1779 asArray(grabAndEraseSelection(cur), ar);
1780 lyxerr << "use selection: " << ar << endl;
1781 cur.insert(pipeThroughExtern(lang, extra, ar));
1785 // only inline, display or eqnarray math is allowed
1786 switch (getType()) {
1792 frontend::Alert::warning(_("Bad math environment"),
1793 _("Computation cannot be performed for AMS "
1794 "math environments.\nChange the math "
1795 "formula type and try again."));
1800 eq.push_back(MathAtom(new InsetMathChar('=')));
1802 // go to first item in line
1803 cur.idx() -= cur.idx() % ncols();
1806 if (getType() == hullSimple) {
1807 size_type pos = cur.cell().find_last(eq);
1809 if (pos == cur.cell().size()) {
1811 lyxerr << "use whole cell: " << ar << endl;
1813 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1814 lyxerr << "use partial cell form pos: " << pos << endl;
1816 cur.cell().append(eq);
1817 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1818 cur.pos() = cur.lastpos();
1822 if (getType() == hullEquation) {
1823 lyxerr << "use equation inset" << endl;
1824 mutate(hullEqnArray);
1825 MathData & ar = cur.cell();
1826 lyxerr << "use cell: " << ar << endl;
1830 cur.cell() = pipeThroughExtern(lang, extra, ar);
1831 // move to end of line
1832 cur.pos() = cur.lastpos();
1837 lyxerr << "use eqnarray" << endl;
1838 cur.idx() += 2 - cur.idx() % ncols();
1840 MathData ar = cur.cell();
1841 lyxerr << "use cell: " << ar << endl;
1842 // FIXME: temporarily disabled
1848 cur.cell() = pipeThroughExtern(lang, extra, ar);
1849 cur.pos() = cur.lastpos();
1854 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1856 //lyxerr << "action: " << cmd.action() << endl;
1857 switch (cmd.action()) {
1859 case LFUN_FINISHED_BACKWARD:
1860 case LFUN_FINISHED_FORWARD:
1861 case LFUN_FINISHED_RIGHT:
1862 case LFUN_FINISHED_LEFT:
1863 //lyxerr << "action: " << cmd.action() << endl;
1864 InsetMathGrid::doDispatch(cur, cmd);
1867 case LFUN_PARAGRAPH_BREAK:
1868 // just swallow this
1871 case LFUN_NEWLINE_INSERT:
1872 // some magic for the common case
1873 if (type_ == hullSimple || type_ == hullEquation) {
1874 cur.recordUndoInset();
1876 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1877 mutate(align ? hullAlign : hullEqnArray);
1878 // mutate() may change labels and such.
1879 cur.forceBufferUpdate();
1880 cur.idx() = nrows() * ncols() - 1;
1881 cur.pos() = cur.lastpos();
1883 InsetMathGrid::doDispatch(cur, cmd);
1886 case LFUN_MATH_NUMBER_TOGGLE: {
1887 //lyxerr << "toggling all numbers" << endl;
1888 cur.recordUndoInset();
1889 bool old = numberedType();
1890 if (type_ == hullMultline)
1891 numbered(nrows() - 1, !old);
1893 for (row_type row = 0; row < nrows(); ++row)
1894 numbered(row, !old);
1896 cur.message(old ? _("No number") : _("Number"));
1897 cur.forceBufferUpdate();
1901 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1902 cur.recordUndoInset();
1903 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1904 bool old = numbered(r);
1905 cur.message(old ? _("No number") : _("Number"));
1907 cur.forceBufferUpdate();
1911 case LFUN_LABEL_INSERT: {
1912 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1913 docstring old_label = label(r);
1914 docstring const default_label = from_ascii("eq:");
1915 if (old_label.empty())
1916 old_label = default_label;
1918 InsetCommandParams p(LABEL_CODE);
1919 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1920 string const data = InsetCommand::params2string(p);
1922 if (cmd.argument().empty())
1923 cur.bv().showDialog("label", data);
1925 FuncRequest fr(LFUN_INSET_INSERT, data);
1931 case LFUN_LABEL_COPY_AS_REFERENCE: {
1933 if (cmd.argument().empty() && &cur.inset() == this)
1934 // if there is no argument and we're inside math, we retrieve
1935 // the row number from the cursor position.
1936 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1938 // if there is an argument, find the corresponding label, else
1939 // check whether there is at least one label.
1940 for (row = 0; row != nrows(); ++row)
1941 if (numbered(row) && label_[row]
1942 && (cmd.argument().empty() || label(row) == cmd.argument()))
1949 InsetCommandParams p(REF_CODE, "ref");
1950 p["reference"] = label(row);
1951 cap::clearSelection();
1952 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1956 case LFUN_WORD_DELETE_FORWARD:
1957 case LFUN_CHAR_DELETE_FORWARD:
1958 if (col(cur.idx()) + 1 == ncols()
1959 && cur.pos() == cur.lastpos()
1960 && !cur.selection()) {
1961 if (!label(row(cur.idx())).empty()) {
1962 cur.recordUndoInset();
1963 label(row(cur.idx()), docstring());
1964 } else if (numbered(row(cur.idx()))) {
1965 cur.recordUndoInset();
1966 numbered(row(cur.idx()), false);
1967 cur.forceBufferUpdate();
1969 InsetMathGrid::doDispatch(cur, cmd);
1973 InsetMathGrid::doDispatch(cur, cmd);
1978 case LFUN_INSET_INSERT: {
1979 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1980 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1981 string const name = cmd.getArg(0);
1982 if (name == "label") {
1983 InsetCommandParams p(LABEL_CODE);
1984 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1985 docstring str = p["name"];
1986 cur.recordUndoInset();
1987 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1991 docstring old = label(r);
1994 // The label will take care of the reference update.
1998 // Newly created inset so initialize it.
1999 label_[r]->initView();
2002 cur.forceBufferUpdate();
2005 InsetMathGrid::doDispatch(cur, cmd);
2009 case LFUN_MATH_EXTERN:
2010 cur.recordUndoInset();
2014 case LFUN_MATH_MUTATE: {
2015 cur.recordUndoInset();
2016 row_type row = cur.row();
2017 col_type col = cur.col();
2018 mutate(hullType(cmd.argument()));
2019 cur.idx() = row * ncols() + col;
2020 if (cur.idx() > cur.lastidx()) {
2021 cur.idx() = cur.lastidx();
2022 cur.pos() = cur.lastpos();
2024 if (cur.pos() > cur.lastpos())
2025 cur.pos() = cur.lastpos();
2027 cur.forceBufferUpdate();
2028 // FIXME: find some more clever handling of the selection,
2029 // i.e. preserve it.
2030 cur.clearSelection();
2031 //cur.dispatched(FINISHED);
2035 case LFUN_MATH_DISPLAY: {
2036 cur.recordUndoInset();
2037 mutate(type_ == hullSimple ? hullEquation : hullSimple);
2038 // if the cursor is in a cell that got merged, move it to
2039 // start of the hull inset.
2040 if (cur.idx() > 0) {
2044 if (cur.pos() > cur.lastpos())
2045 cur.pos() = cur.lastpos();
2050 case LFUN_TABULAR_FEATURE:
2051 if (!allowsTabularFeatures())
2054 InsetMathGrid::doDispatch(cur, cmd);
2058 InsetMathGrid::doDispatch(cur, cmd);
2066 bool allowDisplayMath(Cursor const & cur)
2068 LATTEST(cur.depth() > 1);
2069 Cursor tmpcur = cur;
2072 FuncRequest cmd(LFUN_MATH_DISPLAY);
2073 return tmpcur.getStatus(cmd, status) && status.enabled();
2079 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
2080 FuncStatus & status) const
2082 switch (cmd.action()) {
2083 case LFUN_FINISHED_BACKWARD:
2084 case LFUN_FINISHED_FORWARD:
2085 case LFUN_FINISHED_RIGHT:
2086 case LFUN_FINISHED_LEFT:
2089 case LFUN_NEWLINE_INSERT:
2090 case LFUN_MATH_EXTERN:
2092 status.setEnabled(true);
2095 // we never allow this in math, and we want to bind enter
2096 // to another actions in command-alternatives
2097 case LFUN_PARAGRAPH_BREAK:
2098 status.setEnabled(false);
2100 case LFUN_MATH_MUTATE: {
2101 HullType const ht = hullType(cmd.argument());
2102 status.setOnOff(type_ == ht);
2103 status.setEnabled(isMutable(ht) && isMutable(type_));
2105 if (ht != hullSimple && status.enabled())
2106 status.setEnabled(allowDisplayMath(cur));
2109 case LFUN_MATH_DISPLAY: {
2110 status.setEnabled(display() != Inline || allowDisplayMath(cur));
2111 status.setOnOff(display() != Inline);
2115 case LFUN_MATH_NUMBER_TOGGLE:
2116 // FIXME: what is the right test, this or the one of
2118 status.setEnabled(display() != Inline);
2119 status.setOnOff(numberedType());
2122 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
2123 // FIXME: what is the right test, this or the one of
2125 bool const enable = (type_ == hullMultline)
2126 ? (nrows() - 1 == cur.row())
2127 : display() != Inline;
2128 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2129 status.setEnabled(enable);
2130 status.setOnOff(enable && numbered(r));
2134 case LFUN_LABEL_INSERT:
2135 status.setEnabled(type_ != hullSimple);
2138 case LFUN_LABEL_COPY_AS_REFERENCE: {
2139 bool enabled = false;
2140 if (cmd.argument().empty() && &cur.inset() == this) {
2141 // if there is no argument and we're inside math, we retrieve
2142 // the row number from the cursor position.
2143 row_type row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2144 enabled = numberedType() && label_[row] && numbered(row);
2146 // if there is an argument, find the corresponding label, else
2147 // check whether there is at least one label.
2148 for (row_type row = 0; row != nrows(); ++row) {
2149 if (numbered(row) && label_[row] &&
2150 (cmd.argument().empty() || label(row) == cmd.argument())) {
2156 status.setEnabled(enabled);
2160 case LFUN_INSET_INSERT:
2161 if (cmd.getArg(0) == "label") {
2162 status.setEnabled(type_ != hullSimple);
2165 return InsetMathGrid::getStatus(cur, cmd, status);
2167 case LFUN_TABULAR_FEATURE: {
2168 if (!allowsTabularFeatures())
2170 string s = cmd.getArg(0);
2172 && (s == "append-row"
2173 || s == "delete-row"
2174 || s == "copy-row")) {
2175 status.message(bformat(
2176 from_utf8(N_("Can't change number of rows in '%1$s'")),
2178 status.setEnabled(false);
2182 && (s == "append-column"
2183 || s == "delete-column"
2184 || s == "copy-column")) {
2185 status.message(bformat(
2186 from_utf8(N_("Can't change number of columns in '%1$s'")),
2188 status.setEnabled(false);
2191 if (s == "add-vline-left" || s == "add-vline-right") {
2192 status.message(bformat(
2193 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2195 status.setEnabled(false);
2198 if (s == "valign-top" || s == "valign-middle"
2199 || s == "valign-bottom" || s == "align-left"
2200 || s == "align-center" || s == "align-right") {
2201 status.setEnabled(false);
2204 return InsetMathGrid::getStatus(cur, cmd, status);
2208 return InsetMathGrid::getStatus(cur, cmd, status);
2213 int InsetMathHull::leftMargin() const
2215 return (getType() == hullSimple) ? 0 : InsetMathGrid::leftMargin();
2219 int InsetMathHull::rightMargin() const
2221 return (getType() == hullSimple) ? 0 : InsetMathGrid::rightMargin();
2225 int InsetMathHull::border() const
2227 return (getType() == hullSimple) ? 0 : InsetMathGrid::border();
2231 /////////////////////////////////////////////////////////////////////
2235 // simply scrap this function if you want
2236 void InsetMathHull::mutateToText()
2239 // translate to latex
2241 latex(os, false, false);
2242 string str = os.str();
2245 Text * lt = view_->cursor().innerText();
2246 string::const_iterator cit = str.begin();
2247 string::const_iterator end = str.end();
2248 for (; cit != end; ++cit)
2249 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2252 //dispatch(LFUN_ESCAPE);
2257 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2258 docstring const & font)
2260 // this whole function is a hack and won't work for incremental font
2263 if (cur.inset().asInsetMath()->name() == font)
2264 cur.handleFont(to_utf8(font));
2266 cur.handleNest(createInsetMath(font, cur.buffer()));
2272 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2277 font.fromString(to_utf8(arg), b);
2278 if (font.fontInfo().color() != Color_inherit) {
2279 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2285 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2287 InsetMathNest::edit(cur, front, entry_from);
2288 // The inset formula dimension is not necessarily the same as the
2289 // one of the instant preview image, so we have to indicate to the
2290 // BufferView that a metrics update is needed.
2291 cur.screenUpdateFlags(Update::Force);
2295 /////////////////////////////////////////////////////////////////////
2299 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2302 // FIXME: completely broken
2303 static InsetMathHull * lastformula = 0;
2304 static CursorBase current = DocIterator(ibegin(nucleus()));
2306 static string laststr;
2308 if (lastformula != this || laststr != str) {
2309 //lyxerr << "reset lastformula to " << this << endl;
2312 current = ibegin(nucleus());
2314 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2318 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2320 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2321 CursorSlice & top = it.back();
2322 MathData const & a = top.asInsetMath()->cell(top.idx_);
2323 if (a.matchpart(ar, top.pos_)) {
2324 bv->cursor().setSelection(it, ar.size());
2326 top.pos_ += ar.size();
2332 //lyxerr << "not found!" << endl;
2339 void InsetMathHull::write(ostream & os) const
2341 odocstringstream oss;
2342 otexrowstream ots(oss);
2343 WriteStream wi(ots, false, false, WriteStream::wsDefault);
2346 os << to_utf8(oss.str());
2350 void InsetMathHull::read(Lexer & lex)
2353 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2354 operator=(*at->asHullInset());
2358 bool InsetMathHull::readQuiet(Lexer & lex)
2361 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2363 operator=(*at->asHullInset());
2368 int InsetMathHull::plaintext(odocstringstream & os,
2369 OutputParams const & op, size_t max_length) const
2371 // Try enabling this now that there is a flag as requested at #2275.
2372 if (buffer().isExporting() && display()) {
2376 TextPainter tpain(dim.width(), dim.height());
2377 drawT(tpain, 0, dim.ascent());
2379 // reset metrics cache to "real" values
2381 return tpain.textheight();
2384 odocstringstream oss;
2385 otexrowstream ots(oss);
2386 Encoding const * const enc = encodings.fromLyXName("utf8");
2387 WriteStream wi(ots, false, true, WriteStream::wsDefault, enc);
2390 if (type_ == hullRegexp)
2393 for (row_type r = 0; r < nrows(); ++r) {
2394 for (col_type c = 0; c < ncols(); ++c)
2395 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2396 // if it's for the TOC, we write just the first line
2397 // and do not include the newline.
2398 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2400 if (r < nrows() - 1)
2404 docstring const str = oss.str();
2410 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
2415 if (getType() == hullSimple)
2416 name = from_ascii("inlineequation");
2418 name = from_ascii("informalequation");
2420 docstring bname = name;
2421 if (!label(0).empty())
2422 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
2424 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
2426 odocstringstream ls;
2428 if (runparams.flavor == OutputParams::XML) {
2429 ms << MTag("alt role='tex' ");
2430 // Workaround for db2latex: db2latex always includes equations with
2431 // \ensuremath{} or \begin{display}\end{display}
2432 // so we strip LyX' math environment
2433 WriteStream wi(ols, false, false, WriteStream::wsDefault, runparams.encoding);
2434 InsetMathGrid::write(wi);
2435 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2440 InsetMathGrid::mathmlize(ms);
2443 ms << MTag("alt role='tex'");
2444 latex(ols, runparams);
2445 res = ols.texrow().rows();
2446 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2450 ms << from_ascii("<graphic fileref=\"eqn/");
2451 if (!label(0).empty())
2452 ms << sgml::cleanID(buffer(), runparams, label(0));
2454 ms << sgml::uniqueID(from_ascii("anon"));
2456 if (runparams.flavor == OutputParams::XML)
2457 ms << from_ascii("\"/>");
2459 ms << from_ascii("\">");
2461 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2463 return ms.line() + res;
2467 bool InsetMathHull::haveNumbers() const
2469 bool havenumbers = false;
2470 // inline formulas are never numbered (bug 7351 part 3)
2471 if (getType() == hullSimple)
2473 for (size_t i = 0; i != numbered_.size(); ++i) {
2484 // We need to do something about alignment here.
2486 // This duplicates code from InsetMathGrid, but
2487 // we need access here to number information,
2488 // and we simply do not have that in InsetMathGrid.
2489 void InsetMathHull::htmlize(HtmlStream & os) const
2491 bool const havenumbers = haveNumbers();
2492 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2495 os << cell(index(0, 0));
2499 os << MTag("table", "class='mathtable'");
2500 for (row_type row = 0; row < nrows(); ++row) {
2502 for (col_type col = 0; col < ncols(); ++col) {
2504 os << cell(index(row, col));
2509 docstring const & num = numbers_[row];
2511 os << '(' << num << ')';
2516 os << ETag("table");
2520 // this duplicates code from InsetMathGrid, but
2521 // we need access here to number information,
2522 // and we simply do not have that in InsetMathGrid.
2523 void InsetMathHull::mathmlize(MathStream & os) const
2525 bool const havenumbers = haveNumbers();
2526 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2529 os << MTag("mtable");
2530 char const * const celltag = havetable ? "mtd" : "mrow";
2531 // FIXME There does not seem to be wide support at the moment
2532 // for mlabeledtr, so we have to use just mtr for now.
2533 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2534 char const * const rowtag = "mtr";
2535 for (row_type row = 0; row < nrows(); ++row) {
2538 for (col_type col = 0; col < ncols(); ++col) {
2540 << cell(index(row, col))
2546 docstring const & num = numbers_[row];
2548 os << '(' << num << ')';
2555 os << ETag("mtable");
2559 void InsetMathHull::mathAsLatex(WriteStream & os) const
2561 MathEnsurer ensurer(os, false);
2562 bool havenumbers = haveNumbers();
2563 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2566 os << cell(index(0, 0));
2570 os << "<table class='mathtable'>";
2571 for (row_type row = 0; row < nrows(); ++row) {
2573 for (col_type col = 0; col < ncols(); ++col) {
2574 os << "<td class='math'>";
2575 os << cell(index(row, col));
2580 docstring const & num = numbers_[row];
2582 os << '(' << num << ')';
2591 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2593 BufferParams::MathOutput const mathtype =
2594 buffer().masterBuffer()->params().html_math_output;
2596 bool success = false;
2598 // we output all the labels just at the beginning of the equation.
2599 // this should be fine.
2600 for (size_t i = 0; i != label_.size(); ++i) {
2601 InsetLabel const * const il = label_[i];
2607 // FIXME Eventually we would like to do this inset by inset.
2608 if (mathtype == BufferParams::MathML) {
2609 odocstringstream os;
2614 } catch (MathExportException const &) {}
2616 if (getType() == hullSimple)
2617 xs << html::StartTag("math",
2618 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2620 xs << html::StartTag("math",
2621 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2622 xs << XHTMLStream::ESCAPE_NONE
2624 << html::EndTag("math");
2626 } else if (mathtype == BufferParams::HTML) {
2627 odocstringstream os;
2632 } catch (MathExportException const &) {}
2634 string const tag = (getType() == hullSimple) ? "span" : "div";
2635 xs << html::StartTag(tag, "class='formula'", true)
2636 << XHTMLStream::ESCAPE_NONE
2638 << html::EndTag(tag);
2642 // what we actually want is this:
2644 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2646 // || mathtype == BufferParams::Images
2648 // but what follows is equivalent, since we'll enter only if either (a) we
2649 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2650 // aren't doing LaTeX.
2652 // so this is for Images.
2653 if (!success && mathtype != BufferParams::LaTeX) {
2654 graphics::PreviewImage const * pimage = 0;
2656 loadPreview(docit_);
2657 pimage = preview_->getPreviewImage(buffer());
2658 // FIXME Do we always have png?
2661 if (pimage || op.dryrun) {
2662 string const filename = pimage ? pimage->filename().onlyFileName()
2663 : "previewimage.png";
2665 // if we are not in the master buffer, then we need to see that the
2666 // generated image is copied there; otherwise, preview fails.
2667 Buffer const * mbuf = buffer().masterBuffer();
2668 if (mbuf != &buffer()) {
2669 string mbtmp = mbuf->temppath();
2670 FileName const mbufimg(support::addName(mbtmp, filename));
2671 pimage->filename().copyTo(mbufimg);
2673 // add the file to the list of files to be exported
2674 op.exportdata->addExternalFile("xhtml", pimage->filename());
2677 string const tag = (getType() == hullSimple) ? "span" : "div";
2679 << html::StartTag(tag, "style = \"text-align: center;\"")
2680 << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2681 << html::EndTag(tag)
2687 // so we'll pass this test if we've failed everything else, or
2688 // if mathtype was LaTeX, since we won't have entered any of the
2690 if (!success /* || mathtype != BufferParams::LaTeX */) {
2691 // Unfortunately, we cannot use latexString() because we do not want
2692 // $...$ or whatever.
2693 odocstringstream ls;
2694 otexrowstream ots(ls);
2695 WriteStream wi(ots, false, true, WriteStream::wsPreview);
2696 ModeSpecifier specifier(wi, MATH_MODE);
2698 docstring const latex = ls.str();
2700 // class='math' allows for use of jsMath
2701 // http://www.math.union.edu/~dpvc/jsMath/
2703 // probably should allow for some kind of customization here
2704 string const tag = (getType() == hullSimple) ? "span" : "div";
2705 xs << html::StartTag(tag, "class='math'")
2707 << html::EndTag(tag)
2714 void InsetMathHull::toString(odocstream & os) const
2716 odocstringstream ods;
2717 plaintext(ods, OutputParams(0));
2722 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2724 odocstringstream ods;
2727 // FIXME: this results in spilling TeX into the LyXHTML output since the
2728 // outliner is used to generate the LyXHTML list of figures/etc.
2734 string InsetMathHull::contextMenuName() const
2736 return "context-math";
2740 void InsetMathHull::recordLocation(DocIterator const & di)
2746 bool InsetMathHull::canPaintChange(BufferView const &) const
2748 // We let RowPainter do it seamlessly for inline insets
2749 return display() != Inline;