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"
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(Dimension const & dim)
516 return dim.width() <= 10 && dim.height() <= 10;
521 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
523 // true value in LaTeX is 12pt plus 3pt minus 9pt
524 // FIXME: even better would be to handle the short skip case.
525 int const display_margin = display() ? mi.base.inPixels(Length(12, Length::PT)) : 0;
527 if (previewState(mi.base.bv)) {
528 preview_->metrics(mi, dim);
529 if (previewTooSmall(dim)) {
530 // preview image is too small
531 dim.wid += 2 * ERROR_FRAME_WIDTH;
532 dim.asc += 2 * ERROR_FRAME_WIDTH;
534 // insert a gap in front of the formula
535 // value was hardcoded to 1 pixel
536 dim.wid += mi.base.bv->zoomedPixels(1) ;
538 dim.asc += display_margin;
539 dim.des += display_margin;
546 Changer dummy1 = mi.base.changeFontSet(standardFont());
547 Changer dummy2 = mi.base.font.changeStyle(display() ? DISPLAY_STYLE
550 // let the cells adjust themselves
551 InsetMathGrid::metrics(mi, dim);
554 // Check whether the numbering interferes with the equations
555 if (numberedType()) {
556 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
557 int extra_offset = 0;
558 for (row_type row = 0; row < nrows(); ++row) {
559 rowinfo(row).offset[mi.base.bv] += extra_offset;
562 docstring const nl = nicelabel(row);
564 mathed_string_dim(mi.base.font, nl, dimnl);
565 int const ind = indent(*mi.base.bv);
566 int const x = ind ? ind : (mi.base.textwidth - dim.wid) / 2;
567 // for some reason metrics does not trigger at the
568 // same point as draw, and therefore we use >= instead of >
569 if ((math_number == BufferParams::LEFT && dimnl.wid >= x)
570 || (math_number == BufferParams::RIGHT
571 && dimnl.wid >= mi.base.textwidth - x - dim.wid)) {
572 extra_offset += dimnl.height();
575 dim.des += extra_offset;
580 dim.asc += display_margin;
581 dim.des += display_margin;
584 // reserve some space for marker.
589 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
591 BufferView const * const bv = pi.base.bv;
592 if (previewState(bv)) {
593 Dimension const dim = dimension(*pi.base.bv);
594 if (previewTooSmall(dim))
596 return graphics::PreviewLoader::backgroundColor();
602 void InsetMathHull::drawMarkers(PainterInfo & pi, int x, int y) const
604 ColorCode pen_color = mouseHovered(pi.base.bv) || editing(pi.base.bv)?
605 Color_mathframe : Color_mathcorners;
606 // If the corners have the same color as the background, do not paint them.
607 if (lcolor.getX11Name(Color_mathbg) == lcolor.getX11Name(pen_color))
610 Inset::drawMarkers(pi, x, y);
611 Dimension const dim = dimension(*pi.base.bv);
612 int const t = x + dim.width() - 1;
613 int const a = y - dim.ascent();
614 pi.pain.line(x, a + 3, x, a, pen_color);
615 pi.pain.line(t, a + 3, t, a, pen_color);
616 pi.pain.line(x, a, x + 3, a, pen_color);
617 pi.pain.line(t - 3, a, t, a, pen_color);
621 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
623 Dimension const dim = dimension(*pi.base.bv);
624 if (previewTooSmall(dim)) {
625 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
626 dim.wid, dim.asc + dim.des, backgroundColor(pi));
629 // If there are numbers, the margins around the (displayed)
630 // equation have to be cleared.
632 pi.pain.fillRectangle(pi.leftx, y - dim.asc,
633 pi.rightx - pi.leftx, dim.height(), pi.background_color);
634 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
635 dim.asc + dim.des - 1, pi.backgroundColor(this));
639 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
641 BufferView const * const bv = pi.base.bv;
642 Dimension const dim = dimension(*bv);
644 if (type_ == hullRegexp)
645 pi.pain.rectangle(x + 2, y - dim.ascent() + 1,
646 dim.width() - 3, dim.height() - 2, Color_regexpframe);
648 if (previewState(bv)) {
649 // Do not draw change tracking cue if taken care of by RowPainter
651 Changer dummy = !canPaintChange(*bv) ? make_change(pi.change, Change())
653 if (previewTooSmall(dim)) {
654 // we have an extra frame
655 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
657 // one pixel gap in front
658 // value was hardcoded to 1 pixel
659 int const gap = pi.base.bv->zoomedPixels(1) ;
660 preview_->draw(pi, x + gap, y);
665 // First draw the numbers
666 ColorCode color = pi.selected && lyxrc.use_system_colors
667 ? Color_selectiontext : standardColor();
668 bool const really_change_color = pi.base.font.color() == Color_none;
669 Changer dummy0 = really_change_color ? pi.base.font.changeColor(color)
671 if (numberedType()) {
672 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
673 for (row_type row = 0; row < nrows(); ++row) {
674 int yy = y + rowinfo(row).offset[bv];
675 docstring const nl = nicelabel(row);
677 mathed_string_dim(pi.base.font, nl, dimnl);
678 if (math_number == BufferParams::LEFT) {
679 if (dimnl.wid > x - pi.leftx)
680 yy += rowinfo(row).descent + dimnl.asc;
681 pi.draw(pi.leftx, yy, nl);
683 if (dimnl.wid > pi.rightx - x - dim.wid)
684 yy += rowinfo(row).descent + dimnl.asc;
685 pi.draw(pi.rightx - dimnl.wid, yy, nl);
690 // Then the equations
691 Changer dummy1 = pi.base.changeFontSet(standardFont());
692 Changer dummy2 = pi.base.font.changeStyle(display() ? DISPLAY_STYLE
694 InsetMathGrid::draw(pi, x + 1, y);
695 drawMarkers(pi, x, y);
697 // drawing change line
698 if (canPaintChange(*bv)) {
700 int const display_margin = display() ? pi.base.inPixels(Length(12, Length::PT)) : 0;
701 pi.change.paintCue(pi, x + 1, y + 1 - dim.asc + display_margin,
702 x + dim.wid, y + dim.des - display_margin);
707 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
710 InsetMathGrid::metricsT(mi, dim);
713 otexrowstream ots(os);
714 WriteStream wi(ots, false, true, WriteStream::wsDefault);
716 dim.wid = os.str().size();
723 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
726 InsetMathGrid::drawT(pain, x, y);
729 otexrowstream ots(os);
730 WriteStream wi(ots, false, true, WriteStream::wsDefault);
732 pain.draw(x, y, os.str().c_str());
737 static docstring latexString(InsetMathHull const & inset)
740 // This has to be static, because a preview snippet or a math
741 // macro containing math in text mode (such as $\text{$\phi$}$ or
742 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
743 // first time as a whole, and the second time only the inner math.
744 // In this last case inset.buffer() would be invalid.
745 static Encoding const * encoding = 0;
746 if (inset.isBufferValid())
747 encoding = &(inset.buffer().params().encoding());
748 otexrowstream ots(ls);
749 WriteStream wi(ots, false, true, WriteStream::wsPreview, encoding);
755 void InsetMathHull::initUnicodeMath() const
757 // Trigger classification of the unicode symbols in this inset
758 docstring const dummy = latexString(*this);
762 void InsetMathHull::addPreview(DocIterator const & inset_pos,
763 graphics::PreviewLoader & /*ploader*/) const
765 if (RenderPreview::previewMath()) {
766 preparePreview(inset_pos);
771 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
772 MacroNameSet & macros, MacroNameSet & defs) const
774 MacroNameSet::iterator const end = macros.end();
776 for (size_t i = 0; i < md.size(); ++i) {
777 InsetMathMacro const * mi = md[i].nucleus()->asMacro();
778 InsetMathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
779 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
780 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
781 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
782 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
784 // Look for macros in the arguments of this macro.
785 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
786 usedMacros(mi->cell(idx), pos, macros, defs);
787 // Make sure this is a macro defined in the document
788 // (as we also spot the macros in the symbols file)
789 // or that we have not already accounted for it.
790 docstring const name = mi->name();
791 if (macros.find(name) == end)
794 // Look for macros in the definition of this macro.
795 MathData ar(pos.buffer());
796 MacroData const * data =
797 pos.buffer()->getMacro(name, pos, true);
799 odocstringstream macro_def;
800 data->write(macro_def, true);
802 defs.insert(macro_def.str());
803 asArray(data->definition(), ar);
805 usedMacros(ar, pos, macros, defs);
807 MathData ar(pos.buffer());
808 asArray(mt->definition(), ar);
809 usedMacros(ar, pos, macros, defs);
811 if (!si->nuc().empty())
812 usedMacros(si->nuc(), pos, macros, defs);
814 usedMacros(si->down(), pos, macros, defs);
816 usedMacros(si->up(), pos, macros, defs);
817 } else if (fi || gi) {
818 idx_type nidx = fi ? fi->nargs() : gi->nargs();
819 for (idx_type idx = 0; idx < nidx; ++idx)
820 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
823 usedMacros(ni->cell(0), pos, macros, defs);
829 void InsetMathHull::preparePreview(DocIterator const & pos,
830 bool forexport) const
832 // there is no need to do all the macro stuff if we're not
833 // actually going to generate the preview.
834 if (!RenderPreview::previewMath() && !forexport)
837 Buffer const * buffer = pos.buffer();
839 // collect macros at this position
841 buffer->listMacroNames(macros);
843 // collect definitions only for the macros used in this inset
845 for (idx_type idx = 0; idx < nargs(); ++idx)
846 usedMacros(cell(idx), pos, macros, defs);
848 docstring macro_preamble;
849 for (auto const & defvar : defs)
850 macro_preamble.append(defvar);
852 // set the font series and size for this snippet
853 DocIterator dit = pos.getInnerText();
854 Paragraph const & par = dit.paragraph();
855 Font font = par.getFontSettings(buffer->params(), dit.pos());
856 font.fontInfo().realize(par.layout().font);
857 string const lsize = font.latexSize();
860 if (font.fontInfo().series() == BOLD_SERIES) {
861 setfont += from_ascii("\\textbf{");
864 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
865 setfont += from_ascii("\\" + lsize + '\n');
868 if (forexport && haveNumbers()) {
869 docstring eqstr = from_ascii("equation");
870 CounterMap::const_iterator it = counter_map.find(eqstr);
871 if (it != counter_map.end()) {
872 int num = it->second;
874 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
875 '{' + convert<docstring>(num) + '}' + '\n';
877 for (size_t i = 0; i != numcnts; ++i) {
878 docstring cnt = from_ascii(counters_to_save[i]);
879 it = counter_map.find(cnt);
880 if (it == counter_map.end())
882 int num = it->second;
884 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
885 '{' + convert<docstring>(num) + '}';
888 docstring const snippet = macro_preamble + setfont + setcnt
889 + latexString(*this) + endfont;
890 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
891 preview_->addPreview(snippet, *buffer, forexport);
895 void InsetMathHull::reloadPreview(DocIterator const & pos) const
898 preview_->startLoading(*pos.buffer());
902 void InsetMathHull::loadPreview(DocIterator const & pos) const
904 bool const forexport = true;
905 preparePreview(pos, forexport);
906 preview_->startLoading(*pos.buffer(), forexport);
910 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
912 if (RenderPreview::previewMath()) {
914 cur.screenUpdateFlags(Update::Force);
920 docstring InsetMathHull::label(row_type row) const
922 LASSERT(row < nrows(), return docstring());
923 if (InsetLabel * il = label_[row])
924 return il->screenLabel();
929 void InsetMathHull::label(row_type row, docstring const & label)
931 //lyxerr << "setting label '" << label << "' for row " << row << endl;
935 label_[row] = dummy_pointer;
938 label_[row]->updateLabelAndRefs(label);
940 label_[row]->setParam("name", label);
944 InsetCommandParams p(LABEL_CODE);
946 label_[row] = new InsetLabel(buffer_, p);
948 label_[row]->setBuffer(buffer());
952 void InsetMathHull::numbered(row_type row, Numbered num)
954 numbered_[row] = num;
955 if (!numbered(row) && label_[row]) {
962 bool InsetMathHull::numbered(row_type row) const
964 return numbered_[row] == NUMBER;
968 bool InsetMathHull::ams() const
988 for (size_t row = 0; row < numbered_.size(); ++row)
989 if (numbered_[row] == NOTAG)
995 bool InsetMathHull::outerDisplay() const
1018 Inset::RowFlags InsetMathHull::rowFlags() const
1035 if (buffer().params().is_math_indent)
1036 return Display | AlignLeft;
1045 int InsetMathHull::indent(BufferView const & bv) const
1047 // FIXME: set this in the textclass. This value is what the article class uses.
1048 static Length default_indent(2.5, Length::EM);
1049 if (display() && buffer().params().is_math_indent) {
1050 Length const & len = buffer().params().getMathIndent();
1052 return bv.inPixels(default_indent);
1054 return bv.inPixels(len);
1056 return Inset::indent(bv);
1060 bool InsetMathHull::numberedType() const
1079 for (row_type row = 0; row < nrows(); ++row)
1086 void InsetMathHull::validate(LaTeXFeatures & features) const
1088 if (features.runparams().isLaTeX()) {
1090 features.require("amsmath");
1092 if (type_ == hullRegexp) {
1093 features.require("color");
1094 docstring frcol = from_utf8(lcolor.getLaTeXName(Color_regexpframe));
1095 docstring bgcol = from_ascii("white");
1096 features.addPreambleSnippet(
1097 "\\newcommand{\\regexp}[1]{\\fcolorbox{"
1099 + bgcol + "}{\\ensuremath{\\mathtt{#1}}}}");
1100 features.addPreambleSnippet(
1101 from_ascii("\\newcommand{\\endregexp}{}"));
1102 } else if (outerDisplay() && features.inDeletedInset()) {
1103 features.require("tikz");
1104 features.require("ct-tikz-object-sout");
1107 // Validation is necessary only if not using AMS math.
1108 // To be safe, we will always run mathedvalidate.
1109 //if (features.amsstyle)
1112 //features.binom = true;
1113 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
1114 // it would be better to do this elsewhere, but we can't validate in
1115 // InsetMathMatrix and we have no way, outside MathExtern, to know if
1116 // we even have any matrices.
1117 features.addCSSSnippet(
1118 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
1119 "table.matrix td{padding: 0.25px;}\n"
1120 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
1121 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
1123 InsetMathGrid::validate(features);
1127 OutputParams::CtObject InsetMathHull::CtObject(OutputParams const & runparams) const
1129 OutputParams::CtObject res = OutputParams::CT_NORMAL;
1145 case hullMultline: {
1146 if (runparams.inulemcmd
1147 && (!runparams.local_font || runparams.local_font->fontInfo().strikeout() != FONT_ON))
1148 res = OutputParams::CT_UDISPLAYOBJECT;
1150 res = OutputParams::CT_DISPLAYOBJECT;
1158 void InsetMathHull::header_write(WriteStream & os) const
1160 bool n = numberedType();
1171 if (cell(0).empty())
1176 writeMathdisplayPreamble(os);
1180 os << "\\begin{equation" << star(n) << "}\n";
1190 writeMathdisplayPreamble(os);
1193 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1200 os << "\\begin{" << hullName(type_) << star(n) << '}'
1201 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1207 os << "\\begin{" << hullName(type_) << '}'
1208 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1218 os << "\\begin{unknown" << star(n) << "}\n";
1224 void InsetMathHull::footer_write(WriteStream & os) const
1226 bool n = numberedType();
1243 os << "\\end{equation" << star(n) << "}\n";
1246 writeMathdisplayPostamble(os);
1256 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1257 writeMathdisplayPostamble(os);
1264 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1270 os << "\\end{" << hullName(type_) << "}\n";
1274 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1275 os << "\\endregexp{}}";
1281 os << "\\end{unknown" << star(n) << "}\n";
1287 bool InsetMathHull::allowsTabularFeatures() const
1310 bool InsetMathHull::rowChangeOK() const
1313 type_ == hullEqnArray || type_ == hullAlign ||
1314 type_ == hullFlAlign || type_ == hullAlignAt ||
1315 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1316 type_ == hullGather || type_ == hullMultline;
1320 bool InsetMathHull::colChangeOK() const
1323 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1324 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1328 void InsetMathHull::addRow(row_type row)
1333 bool numbered = numberedType();
1334 // Move the number and raw pointer, do not call label() (bug 7511)
1335 InsetLabel * label = dummy_pointer;
1336 docstring number = empty_docstring();
1337 if (type_ == hullMultline) {
1338 if (row + 1 == nrows()) {
1339 numbered_[row] = NONUMBER;
1340 swap(label, label_[row]);
1341 swap(number, numbers_[row]);
1346 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1347 numbers_.insert(numbers_.begin() + row + 1, number);
1348 label_.insert(label_.begin() + row + 1, label);
1349 InsetMathGrid::addRow(row);
1353 void InsetMathHull::swapRow(row_type row)
1357 if (row + 1 == nrows())
1359 swap(numbered_[row], numbered_[row + 1]);
1360 swap(numbers_[row], numbers_[row + 1]);
1361 swap(label_[row], label_[row + 1]);
1362 InsetMathGrid::swapRow(row);
1366 void InsetMathHull::delRow(row_type row)
1368 if (nrows() <= 1 || !rowChangeOK())
1370 if (row + 1 == nrows() && type_ == hullMultline) {
1371 swap(numbered_[row - 1], numbered_[row]);
1372 swap(numbers_[row - 1], numbers_[row]);
1373 swap(label_[row - 1], label_[row]);
1374 InsetMathGrid::delRow(row);
1377 InsetMathGrid::delRow(row);
1378 // The last dummy row has no number info nor a label.
1379 // Test nrows() + 1 because we have already erased the row.
1380 if (row == nrows() + 1)
1382 numbered_.erase(numbered_.begin() + row);
1383 numbers_.erase(numbers_.begin() + row);
1385 label_.erase(label_.begin() + row);
1389 void InsetMathHull::addCol(col_type col)
1393 InsetMathGrid::addCol(col);
1397 void InsetMathHull::delCol(col_type col)
1399 if (ncols() <= 1 || !colChangeOK())
1401 InsetMathGrid::delCol(col);
1405 docstring InsetMathHull::nicelabel(row_type row) const
1409 docstring const & val = numbers_[row];
1411 return '(' + val + ')';
1412 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1416 void InsetMathHull::glueall(HullType type)
1419 for (idx_type i = 0; i < nargs(); ++i)
1421 InsetLabel * label = 0;
1422 if (type == hullEquation) {
1423 // preserve first non-empty label
1424 for (row_type row = 0; row < nrows(); ++row) {
1426 label = label_[row];
1432 *this = InsetMathHull(buffer_, hullSimple);
1439 void InsetMathHull::splitTo2Cols()
1441 LASSERT(ncols() == 1, return);
1442 InsetMathGrid::addCol(1);
1443 for (row_type row = 0; row < nrows(); ++row) {
1444 idx_type const i = 2 * row;
1445 pos_type pos = firstRelOp(cell(i));
1446 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1447 cell(i).erase(pos, cell(i).size());
1452 void InsetMathHull::splitTo3Cols()
1454 LASSERT(ncols() < 3, return);
1457 InsetMathGrid::addCol(2);
1458 for (row_type row = 0; row < nrows(); ++row) {
1459 idx_type const i = 3 * row + 1;
1460 if (!cell(i).empty()) {
1461 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1462 cell(i).erase(1, cell(i).size());
1468 void InsetMathHull::changeCols(col_type cols)
1470 if (ncols() == cols)
1472 else if (ncols() < cols) {
1478 while (ncols() < cols)
1479 InsetMathGrid::addCol(ncols());
1485 for (row_type row = 0; row < nrows(); ++row) {
1486 idx_type const i = row * ncols();
1487 for (col_type col = cols; col < ncols(); ++col) {
1488 cell(i + cols - 1).append(cell(i + col));
1492 while (ncols() > cols) {
1493 InsetMathGrid::delCol(ncols() - 1);
1498 HullType InsetMathHull::getType() const
1504 void InsetMathHull::setType(HullType type)
1511 bool InsetMathHull::isMutable(HullType type)
1535 void InsetMathHull::mutate(HullType newtype)
1537 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1539 if (newtype == type_)
1542 // This guards the algorithm below it, which is designed with certain types
1544 if (!isMutable(newtype) || !isMutable(type_)) {
1545 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1546 << "' to '" << to_utf8(hullName(newtype))
1547 << "' not implemented" << endl;
1551 // we try to move along the chain
1552 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1554 // +-------------------------------------+
1555 // we use eqnarray as intermediate type for mutations that are not
1556 // directly supported because it handles labels and numbering for
1561 setType(hullSimple);
1567 if (newtype == hullNone) {
1571 setType(hullEquation);
1572 numbered(0, label_[0] ? true : false);
1581 setType(hullSimple);
1586 // split it "nicely" on the first relop
1588 setType(hullEqnArray);
1596 // split it "nicely"
1631 setType(hullEqnArray);
1640 for (row_type row = 0; row < nrows(); ++row)
1641 numbered(row, false);
1651 for (row_type row = 0; row < nrows(); ++row)
1652 numbered(row, false);
1659 setType(hullEqnArray);
1689 for (row_type row = 0; row < nrows(); ++row)
1690 numbered(row, false);
1694 // first we mutate to EqnArray
1696 setType(hullEqnArray);
1703 // we passed the guard so we should not be here
1704 LYXERR0("Mutation not implemented, but should have been.");
1705 LASSERT(false, return);
1711 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1712 bool last_eoln) const
1715 if (numberedType()) {
1716 if (label_[row] && numbered(row)) {
1717 docstring const name =
1718 latex ? escape(label_[row]->getParam("name"))
1719 : label_[row]->getParam("name");
1720 res += "\\label{" + name + '}';
1722 if (type_ != hullMultline) {
1723 if (numbered_[row] == NONUMBER)
1724 res += "\\nonumber ";
1725 else if (numbered_[row] == NOTAG)
1729 // Never add \\ on the last empty line of eqnarray and friends
1731 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1734 void InsetMathHull::write(WriteStream & os) const
1736 ModeSpecifier specifier(os, MATH_MODE);
1738 InsetMathGrid::write(os);
1743 void InsetMathHull::normalize(NormalStream & os) const
1745 os << "[formula " << hullName(type_) << ' ';
1746 InsetMathGrid::normalize(os);
1751 void InsetMathHull::infoize(odocstream & os) const
1753 os << bformat(_("Type: %1$s"), hullName(type_));
1757 void InsetMathHull::check() const
1759 LATTEST(numbered_.size() == nrows());
1760 LATTEST(numbers_.size() == nrows());
1761 LATTEST(label_.size() == nrows());
1765 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1767 //FIXME: sort out whether we want std::string or docstring for those
1768 string const lang = func.getArg(0);
1769 docstring extra = from_utf8(func.getArg(1));
1771 extra = from_ascii("noextra");
1773 // replace selection with result of computation
1774 if (reduceSelectionToOneCell(cur)) {
1776 asArray(grabAndEraseSelection(cur), ar);
1777 lyxerr << "use selection: " << ar << endl;
1778 cur.insert(pipeThroughExtern(lang, extra, ar));
1782 // only inline, display or eqnarray math is allowed
1783 switch (getType()) {
1789 frontend::Alert::warning(_("Bad math environment"),
1790 _("Computation cannot be performed for AMS "
1791 "math environments.\nChange the math "
1792 "formula type and try again."));
1797 eq.push_back(MathAtom(new InsetMathChar('=')));
1799 // go to first item in line
1800 cur.idx() -= cur.idx() % ncols();
1803 if (getType() == hullSimple) {
1804 size_type pos = cur.cell().find_last(eq);
1806 if (pos == cur.cell().size()) {
1808 lyxerr << "use whole cell: " << ar << endl;
1810 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1811 lyxerr << "use partial cell form pos: " << pos << endl;
1813 cur.cell().append(eq);
1814 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1815 cur.pos() = cur.lastpos();
1819 if (getType() == hullEquation) {
1820 lyxerr << "use equation inset" << endl;
1821 mutate(hullEqnArray);
1822 MathData & ar = cur.cell();
1823 lyxerr << "use cell: " << ar << endl;
1827 cur.cell() = pipeThroughExtern(lang, extra, ar);
1828 // move to end of line
1829 cur.pos() = cur.lastpos();
1834 lyxerr << "use eqnarray" << endl;
1835 cur.idx() += 2 - cur.idx() % ncols();
1837 MathData ar = cur.cell();
1838 lyxerr << "use cell: " << ar << endl;
1839 // FIXME: temporarily disabled
1845 cur.cell() = pipeThroughExtern(lang, extra, ar);
1846 cur.pos() = cur.lastpos();
1851 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1853 //lyxerr << "action: " << cmd.action() << endl;
1854 switch (cmd.action()) {
1856 case LFUN_FINISHED_BACKWARD:
1857 case LFUN_FINISHED_FORWARD:
1858 case LFUN_FINISHED_RIGHT:
1859 case LFUN_FINISHED_LEFT:
1860 //lyxerr << "action: " << cmd.action() << endl;
1861 InsetMathGrid::doDispatch(cur, cmd);
1864 case LFUN_PARAGRAPH_BREAK:
1865 // just swallow this
1868 case LFUN_NEWLINE_INSERT:
1869 // some magic for the common case
1870 if (type_ == hullSimple || type_ == hullEquation) {
1871 cur.recordUndoInset();
1873 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1874 mutate(align ? hullAlign : hullEqnArray);
1875 // mutate() may change labels and such.
1876 cur.forceBufferUpdate();
1877 cur.idx() = nrows() * ncols() - 1;
1878 cur.pos() = cur.lastpos();
1880 InsetMathGrid::doDispatch(cur, cmd);
1883 case LFUN_MATH_NUMBER_TOGGLE: {
1884 //lyxerr << "toggling all numbers" << endl;
1885 cur.recordUndoInset();
1886 bool old = numberedType();
1887 if (type_ == hullMultline)
1888 numbered(nrows() - 1, !old);
1890 for (row_type row = 0; row < nrows(); ++row)
1891 numbered(row, !old);
1893 cur.message(old ? _("No number") : _("Number"));
1894 cur.forceBufferUpdate();
1898 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1899 cur.recordUndoInset();
1900 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1901 bool old = numbered(r);
1902 cur.message(old ? _("No number") : _("Number"));
1904 cur.forceBufferUpdate();
1908 case LFUN_LABEL_INSERT: {
1909 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1910 docstring old_label = label(r);
1911 docstring const default_label = from_ascii("eq:");
1912 if (old_label.empty())
1913 old_label = default_label;
1915 InsetCommandParams p(LABEL_CODE);
1916 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1917 string const data = InsetCommand::params2string(p);
1919 if (cmd.argument().empty())
1920 cur.bv().showDialog("label", data);
1922 FuncRequest fr(LFUN_INSET_INSERT, data);
1928 case LFUN_LABEL_COPY_AS_REFERENCE: {
1930 if (cmd.argument().empty() && &cur.inset() == this)
1931 // if there is no argument and we're inside math, we retrieve
1932 // the row number from the cursor position.
1933 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1935 // if there is an argument, find the corresponding label, else
1936 // check whether there is at least one label.
1937 for (row = 0; row != nrows(); ++row)
1938 if (numbered(row) && label_[row]
1939 && (cmd.argument().empty() || label(row) == cmd.argument()))
1946 InsetCommandParams p(REF_CODE, "ref");
1947 p["reference"] = label(row);
1948 cap::clearSelection();
1949 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1953 case LFUN_WORD_DELETE_FORWARD:
1954 case LFUN_CHAR_DELETE_FORWARD:
1955 if (col(cur.idx()) + 1 == ncols()
1956 && cur.pos() == cur.lastpos()
1957 && !cur.selection()) {
1958 if (!label(row(cur.idx())).empty()) {
1959 cur.recordUndoInset();
1960 label(row(cur.idx()), docstring());
1961 } else if (numbered(row(cur.idx()))) {
1962 cur.recordUndoInset();
1963 numbered(row(cur.idx()), false);
1964 cur.forceBufferUpdate();
1966 InsetMathGrid::doDispatch(cur, cmd);
1970 InsetMathGrid::doDispatch(cur, cmd);
1975 case LFUN_INSET_INSERT: {
1976 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1977 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1978 string const name = cmd.getArg(0);
1979 if (name == "label") {
1980 InsetCommandParams p(LABEL_CODE);
1981 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1982 docstring str = p["name"];
1983 cur.recordUndoInset();
1984 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1988 docstring old = label(r);
1991 // The label will take care of the reference update.
1995 // Newly created inset so initialize it.
1996 label_[r]->initView();
1999 cur.forceBufferUpdate();
2002 InsetMathGrid::doDispatch(cur, cmd);
2006 case LFUN_MATH_EXTERN:
2007 cur.recordUndoInset();
2011 case LFUN_MATH_MUTATE: {
2012 cur.recordUndoInset();
2013 row_type row = cur.row();
2014 col_type col = cur.col();
2015 mutate(hullType(cmd.argument()));
2016 cur.idx() = row * ncols() + col;
2017 if (cur.idx() > cur.lastidx()) {
2018 cur.idx() = cur.lastidx();
2019 cur.pos() = cur.lastpos();
2021 if (cur.pos() > cur.lastpos())
2022 cur.pos() = cur.lastpos();
2024 cur.forceBufferUpdate();
2025 // FIXME: find some more clever handling of the selection,
2026 // i.e. preserve it.
2027 cur.clearSelection();
2028 //cur.dispatched(FINISHED);
2032 case LFUN_MATH_DISPLAY: {
2033 cur.recordUndoInset();
2034 mutate(type_ == hullSimple ? hullEquation : hullSimple);
2035 // if the cursor is in a cell that got merged, move it to
2036 // start of the hull inset.
2037 if (cur.idx() > 0) {
2041 if (cur.pos() > cur.lastpos())
2042 cur.pos() = cur.lastpos();
2047 case LFUN_TABULAR_FEATURE:
2048 if (!allowsTabularFeatures())
2051 InsetMathGrid::doDispatch(cur, cmd);
2055 InsetMathGrid::doDispatch(cur, cmd);
2063 bool allowDisplayMath(Cursor const & cur)
2065 LATTEST(cur.depth() > 1);
2066 Cursor tmpcur = cur;
2069 FuncRequest cmd(LFUN_MATH_DISPLAY);
2070 return tmpcur.getStatus(cmd, status) && status.enabled();
2076 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
2077 FuncStatus & status) const
2079 switch (cmd.action()) {
2080 case LFUN_FINISHED_BACKWARD:
2081 case LFUN_FINISHED_FORWARD:
2082 case LFUN_FINISHED_RIGHT:
2083 case LFUN_FINISHED_LEFT:
2086 case LFUN_NEWLINE_INSERT:
2087 case LFUN_MATH_EXTERN:
2089 status.setEnabled(true);
2092 // we never allow this in math, and we want to bind enter
2093 // to another actions in command-alternatives
2094 case LFUN_PARAGRAPH_BREAK:
2095 status.setEnabled(false);
2097 case LFUN_MATH_MUTATE: {
2098 HullType const ht = hullType(cmd.argument());
2099 status.setOnOff(type_ == ht);
2100 status.setEnabled(isMutable(ht) && isMutable(type_));
2102 if (ht != hullSimple && status.enabled())
2103 status.setEnabled(allowDisplayMath(cur));
2106 case LFUN_MATH_DISPLAY: {
2107 status.setEnabled(display() || allowDisplayMath(cur));
2108 status.setOnOff(display());
2112 case LFUN_MATH_NUMBER_TOGGLE:
2113 // FIXME: what is the right test, this or the one of
2115 status.setEnabled(display());
2116 status.setOnOff(numberedType());
2119 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
2120 // FIXME: what is the right test, this or the one of
2122 bool const enable = (type_ == hullMultline)
2123 ? (nrows() - 1 == cur.row())
2125 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2126 status.setEnabled(enable);
2127 status.setOnOff(enable && numbered(r));
2131 case LFUN_LABEL_INSERT:
2132 status.setEnabled(type_ != hullSimple);
2135 case LFUN_LABEL_COPY_AS_REFERENCE: {
2136 bool enabled = false;
2137 if (cmd.argument().empty() && &cur.inset() == this) {
2138 // if there is no argument and we're inside math, we retrieve
2139 // the row number from the cursor position.
2140 row_type row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2141 enabled = numberedType() && label_[row] && numbered(row);
2143 // if there is an argument, find the corresponding label, else
2144 // check whether there is at least one label.
2145 for (row_type row = 0; row != nrows(); ++row) {
2146 if (numbered(row) && label_[row] &&
2147 (cmd.argument().empty() || label(row) == cmd.argument())) {
2153 status.setEnabled(enabled);
2157 case LFUN_INSET_INSERT:
2158 if (cmd.getArg(0) == "label") {
2159 status.setEnabled(type_ != hullSimple);
2162 return InsetMathGrid::getStatus(cur, cmd, status);
2164 case LFUN_TABULAR_FEATURE: {
2165 if (!allowsTabularFeatures())
2167 string s = cmd.getArg(0);
2169 && (s == "append-row"
2170 || s == "delete-row"
2171 || s == "copy-row")) {
2172 status.message(bformat(
2173 from_utf8(N_("Can't change number of rows in '%1$s'")),
2175 status.setEnabled(false);
2179 && (s == "append-column"
2180 || s == "delete-column"
2181 || s == "copy-column")) {
2182 status.message(bformat(
2183 from_utf8(N_("Can't change number of columns in '%1$s'")),
2185 status.setEnabled(false);
2188 if (s == "add-vline-left" || s == "add-vline-right") {
2189 status.message(bformat(
2190 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2192 status.setEnabled(false);
2195 if (s == "valign-top" || s == "valign-middle"
2196 || s == "valign-bottom" || s == "align-left"
2197 || s == "align-center" || s == "align-right") {
2198 status.setEnabled(false);
2201 return InsetMathGrid::getStatus(cur, cmd, status);
2205 return InsetMathGrid::getStatus(cur, cmd, status);
2210 int InsetMathHull::leftMargin() const
2212 return (getType() == hullSimple) ? 0 : InsetMathGrid::leftMargin();
2216 int InsetMathHull::rightMargin() const
2218 return (getType() == hullSimple) ? 0 : InsetMathGrid::rightMargin();
2222 int InsetMathHull::border() const
2224 return (getType() == hullSimple) ? 0 : InsetMathGrid::border();
2228 /////////////////////////////////////////////////////////////////////
2232 // simply scrap this function if you want
2233 void InsetMathHull::mutateToText()
2236 // translate to latex
2238 latex(os, false, false);
2239 string str = os.str();
2242 Text * lt = view_->cursor().innerText();
2243 string::const_iterator cit = str.begin();
2244 string::const_iterator end = str.end();
2245 for (; cit != end; ++cit)
2246 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2249 //dispatch(LFUN_ESCAPE);
2254 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2255 docstring const & font)
2257 // this whole function is a hack and won't work for incremental font
2260 if (cur.inset().asInsetMath()->name() == font)
2261 cur.handleFont(to_utf8(font));
2263 cur.handleNest(createInsetMath(font, cur.buffer()));
2269 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2274 font.fromString(to_utf8(arg), b);
2275 if (font.fontInfo().color() != Color_inherit) {
2276 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2282 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2284 InsetMathNest::edit(cur, front, entry_from);
2285 // The inset formula dimension is not necessarily the same as the
2286 // one of the instant preview image, so we have to indicate to the
2287 // BufferView that a metrics update is needed.
2288 cur.screenUpdateFlags(Update::Force);
2292 /////////////////////////////////////////////////////////////////////
2296 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2299 // FIXME: completely broken
2300 static InsetMathHull * lastformula = 0;
2301 static CursorBase current = DocIterator(ibegin(nucleus()));
2303 static string laststr;
2305 if (lastformula != this || laststr != str) {
2306 //lyxerr << "reset lastformula to " << this << endl;
2309 current = ibegin(nucleus());
2311 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2315 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2317 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2318 CursorSlice & top = it.back();
2319 MathData const & a = top.asInsetMath()->cell(top.idx_);
2320 if (a.matchpart(ar, top.pos_)) {
2321 bv->cursor().setSelection(it, ar.size());
2323 top.pos_ += ar.size();
2329 //lyxerr << "not found!" << endl;
2336 void InsetMathHull::write(ostream & os) const
2338 odocstringstream oss;
2339 otexrowstream ots(oss);
2340 WriteStream wi(ots, false, false, WriteStream::wsDefault);
2343 os << to_utf8(oss.str());
2347 void InsetMathHull::read(Lexer & lex)
2350 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2351 operator=(*at->asHullInset());
2355 bool InsetMathHull::readQuiet(Lexer & lex)
2358 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2360 operator=(*at->asHullInset());
2365 int InsetMathHull::plaintext(odocstringstream & os,
2366 OutputParams const & op, size_t max_length) const
2368 // Try enabling this now that there is a flag as requested at #2275.
2369 if (buffer().isExporting() && display()) {
2373 TextPainter tpain(dim.width(), dim.height());
2374 drawT(tpain, 0, dim.ascent());
2376 // reset metrics cache to "real" values
2378 return tpain.textheight();
2381 odocstringstream oss;
2382 otexrowstream ots(oss);
2383 Encoding const * const enc = encodings.fromLyXName("utf8");
2384 WriteStream wi(ots, false, true, WriteStream::wsDefault, enc);
2387 if (type_ == hullRegexp)
2390 for (row_type r = 0; r < nrows(); ++r) {
2391 for (col_type c = 0; c < ncols(); ++c)
2392 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2393 // if it's for the TOC, we write just the first line
2394 // and do not include the newline.
2395 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2397 if (r < nrows() - 1)
2401 docstring const str = oss.str();
2407 void InsetMathHull::docbook(XMLStream & xs, OutputParams const & runparams) const
2409 // With DocBook 5, MathML must be within its own namespace; defined in Buffer.cpp::writeDocBookSource as "m".
2410 // Output everything in a separate stream so that this does not interfere with the standard flow of DocBook tags.
2411 odocstringstream osmath;
2412 MathStream ms(osmath, "m", true);
2414 // Choose the tag around the MathML equation.
2416 if (getType() == hullSimple)
2417 name = from_ascii("inlineequation");
2419 name = from_ascii("informalequation");
2421 // DocBook also has <equation>, but it comes with a title.
2423 docstring bname = name;
2424 for (row_type i = 0; i < nrows(); ++i) {
2425 if (!label(i).empty()) {
2426 bname += " xml:id=\"" + xml::cleanID(label(i)) + "\"";
2431 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
2433 // Output the MathML subtree.
2434 odocstringstream ls;
2437 // TeX transcription. Avoid MTag/ETag so that there are no extraneous spaces.
2438 ms << "<" << from_ascii("alt") << " role='tex'" << ">";
2439 // Workaround for db2latex: db2latex always includes equations with
2440 // \ensuremath{} or \begin{display}\end{display}
2441 // so we strip LyX' math environment
2442 WriteStream wi(ols, false, false, WriteStream::wsDefault, runparams.encoding);
2443 InsetMathGrid::write(wi);
2444 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2445 ms << "</" << from_ascii("alt") << ">";
2447 // Actual transformation of the formula into MathML. This translation may fail (for example, due to custom macros).
2448 // The new output stream is required to deal with the errors: first write completely the formula into this
2449 // temporary stream; then, if it is possible without error, then copy it back to the "real" stream. Otherwise,
2450 // some incomplete tags might be put into the real stream.
2452 // First, generate the MathML expression.
2453 odocstringstream ostmp;
2454 MathStream mstmp(ostmp, ms.xmlns(), ms.xmlMode());
2455 InsetMathGrid::mathmlize(mstmp);
2457 // Then, output it (but only if the generation can be done without errors!).
2460 osmath << ostmp.str(); // osmath is not a XMLStream, so no need for XMLStream::ESCAPE_NONE.
2462 } catch (MathExportException const &) {
2463 osmath << "MathML export failed. Please report this as a bug.";
2466 // Close the DocBook tag enclosing the formula.
2467 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2469 // Output the complete tag to the DocBook stream.
2470 xs << XMLStream::ESCAPE_NONE << osmath.str();
2474 bool InsetMathHull::haveNumbers() const
2476 bool havenumbers = false;
2477 // inline formulas are never numbered (bug 7351 part 3)
2478 if (getType() == hullSimple)
2480 for (size_t i = 0; i != numbered_.size(); ++i) {
2491 // We need to do something about alignment here.
2493 // This duplicates code from InsetMathGrid, but
2494 // we need access here to number information,
2495 // and we simply do not have that in InsetMathGrid.
2496 void InsetMathHull::htmlize(HtmlStream & os) const
2498 bool const havenumbers = haveNumbers();
2499 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2502 os << cell(index(0, 0));
2506 os << MTag("table", "class='mathtable'");
2507 for (row_type row = 0; row < nrows(); ++row) {
2509 for (col_type col = 0; col < ncols(); ++col) {
2511 os << cell(index(row, col));
2516 docstring const & num = numbers_[row];
2518 os << '(' << num << ')';
2523 os << ETag("table");
2527 // this duplicates code from InsetMathGrid, but
2528 // we need access here to number information,
2529 // and we simply do not have that in InsetMathGrid.
2530 void InsetMathHull::mathmlize(MathStream & ms) const
2532 bool const havenumbers = haveNumbers();
2533 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2536 ms << MTag("mtable");
2537 char const * const celltag = havetable ? "mtd" : "mrow";
2538 // FIXME There does not seem to be wide support at the moment
2539 // for mlabeledtr, so we have to use just mtr for now.
2540 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2541 char const * const rowtag = "mtr";
2542 for (row_type row = 0; row < nrows(); ++row) {
2545 for (col_type col = 0; col < ncols(); ++col) {
2547 << cell(index(row, col))
2553 docstring const & num = numbers_[row];
2555 ms << '(' << num << ')';
2562 ms << ETag("mtable");
2566 void InsetMathHull::mathAsLatex(WriteStream & os) const
2568 MathEnsurer ensurer(os, false);
2569 bool havenumbers = haveNumbers();
2570 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2573 os << cell(index(0, 0));
2577 os << "<table class='mathtable'>";
2578 for (row_type row = 0; row < nrows(); ++row) {
2580 for (col_type col = 0; col < ncols(); ++col) {
2581 os << "<td class='math'>";
2582 os << cell(index(row, col));
2587 docstring const & num = numbers_[row];
2589 os << '(' << num << ')';
2598 docstring InsetMathHull::xhtml(XMLStream & xs, OutputParams const & op) const
2600 BufferParams::MathOutput const mathtype =
2601 buffer().masterBuffer()->params().html_math_output;
2603 bool success = false;
2605 // we output all the labels just at the beginning of the equation.
2606 // this should be fine.
2607 for (size_t i = 0; i != label_.size(); ++i) {
2608 InsetLabel const * const il = label_[i];
2614 // FIXME Eventually we would like to do this inset by inset.
2615 if (mathtype == BufferParams::MathML) {
2616 odocstringstream os;
2621 } catch (MathExportException const &) {}
2623 if (getType() == hullSimple)
2624 xs << xml::StartTag("math",
2625 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2627 xs << xml::StartTag("math",
2628 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2629 xs << XMLStream::ESCAPE_NONE
2631 << xml::EndTag("math");
2633 } else if (mathtype == BufferParams::HTML) {
2634 odocstringstream os;
2639 } catch (MathExportException const &) {}
2641 string const tag = (getType() == hullSimple) ? "span" : "div";
2642 xs << xml::StartTag(tag, "class='formula'", true)
2643 << XMLStream::ESCAPE_NONE
2645 << xml::EndTag(tag);
2649 // what we actually want is this:
2651 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2653 // || mathtype == BufferParams::Images
2655 // but what follows is equivalent, since we'll enter only if either (a) we
2656 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2657 // aren't doing LaTeX.
2659 // so this is for Images.
2660 if (!success && mathtype != BufferParams::LaTeX) {
2661 graphics::PreviewImage const * pimage = 0;
2663 loadPreview(docit_);
2664 pimage = preview_->getPreviewImage(buffer());
2665 // FIXME Do we always have png?
2668 if (pimage || op.dryrun) {
2669 string const filename = pimage ? pimage->filename().onlyFileName()
2670 : "previewimage.png";
2672 // if we are not in the master buffer, then we need to see that the
2673 // generated image is copied there; otherwise, preview fails.
2674 Buffer const * mbuf = buffer().masterBuffer();
2675 if (mbuf != &buffer()) {
2676 string mbtmp = mbuf->temppath();
2677 FileName const mbufimg(support::addName(mbtmp, filename));
2678 pimage->filename().copyTo(mbufimg);
2680 // add the file to the list of files to be exported
2681 op.exportdata->addExternalFile("xhtml", pimage->filename());
2684 string const tag = (getType() == hullSimple) ? "span" : "div";
2686 << xml::StartTag(tag, "style = \"text-align: center;\"")
2687 << xml::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2694 // so we'll pass this test if we've failed everything else, or
2695 // if mathtype was LaTeX, since we won't have entered any of the
2697 if (!success /* || mathtype != BufferParams::LaTeX */) {
2698 // Unfortunately, we cannot use latexString() because we do not want
2699 // $...$ or whatever.
2700 odocstringstream ls;
2701 otexrowstream ots(ls);
2702 WriteStream wi(ots, false, true, WriteStream::wsPreview);
2703 ModeSpecifier specifier(wi, MATH_MODE);
2705 docstring const latex = ls.str();
2707 // class='math' allows for use of jsMath
2708 // http://www.math.union.edu/~dpvc/jsMath/
2710 // probably should allow for some kind of customization here
2711 string const tag = (getType() == hullSimple) ? "span" : "div";
2712 xs << xml::StartTag(tag, "class='math'")
2721 void InsetMathHull::toString(odocstream & os) const
2723 odocstringstream ods;
2724 plaintext(ods, OutputParams(0));
2729 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2731 odocstringstream ods;
2734 // FIXME: this results in spilling TeX into the LyXHTML output since the
2735 // outliner is used to generate the LyXHTML list of figures/etc.
2741 string InsetMathHull::contextMenuName() const
2743 return "context-math";
2747 void InsetMathHull::recordLocation(DocIterator const & di)
2753 bool InsetMathHull::canPaintChange(BufferView const &) const
2755 // We let RowPainter do it seamlessly for inline insets