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()) {
127 if (os.ulemCmd() == WriteStream::UNDERLINE)
128 os << "\\raisebox{-\\belowdisplayshortskip}{"
129 "\\lyxmathsout{\\parbox[b]{\\linewidth}{";
131 os << "\\lyxmathsout{\\parbox{\\linewidth}{";
132 } else if (os.ulemCmd() == WriteStream::UNDERLINE)
133 os << "\\raisebox{-\\belowdisplayshortskip}{"
134 "\\parbox[b]{\\linewidth}{";
135 else if (os.ulemCmd() == WriteStream::STRIKEOUT)
136 os << "\\parbox{\\linewidth}{";
140 // writes a postamble for underlined or struck out math display
141 void writeMathdisplayPostamble(WriteStream & os)
143 if (os.strikeoutMath()) {
144 if (os.ulemCmd() == WriteStream::UNDERLINE)
147 } else if (os.ulemCmd() == WriteStream::UNDERLINE)
149 else if (os.ulemCmd() == WriteStream::STRIKEOUT)
157 HullType hullType(docstring const & s)
159 if (s == "none") return hullNone;
160 if (s == "simple") return hullSimple;
161 if (s == "equation") return hullEquation;
162 if (s == "eqnarray") return hullEqnArray;
163 if (s == "align") return hullAlign;
164 if (s == "alignat") return hullAlignAt;
165 if (s == "xalignat") return hullXAlignAt;
166 if (s == "xxalignat") return hullXXAlignAt;
167 if (s == "multline") return hullMultline;
168 if (s == "gather") return hullGather;
169 if (s == "flalign") return hullFlAlign;
170 if (s == "regexp") return hullRegexp;
171 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
176 docstring hullName(HullType type)
179 case hullNone: return from_ascii("none");
180 case hullSimple: return from_ascii("simple");
181 case hullEquation: return from_ascii("equation");
182 case hullEqnArray: return from_ascii("eqnarray");
183 case hullAlign: return from_ascii("align");
184 case hullAlignAt: return from_ascii("alignat");
185 case hullXAlignAt: return from_ascii("xalignat");
186 case hullXXAlignAt: return from_ascii("xxalignat");
187 case hullMultline: return from_ascii("multline");
188 case hullGather: return from_ascii("gather");
189 case hullFlAlign: return from_ascii("flalign");
190 case hullRegexp: return from_ascii("regexp");
192 lyxerr << "unknown hull type" << endl;
195 return from_ascii("none");
198 static InsetLabel * dummy_pointer = 0;
200 InsetMathHull::InsetMathHull(Buffer * buf)
201 : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, NONUMBER),
202 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
203 preview_(new RenderPreview(this))
205 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
206 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
207 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
208 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
215 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
216 : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, NONUMBER),
217 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
218 preview_(new RenderPreview(this))
226 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
232 InsetMathHull::~InsetMathHull()
234 for (size_t i = 0; i < label_.size(); ++i)
239 Inset * InsetMathHull::clone() const
241 return new InsetMathHull(*this);
245 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
249 InsetMathGrid::operator=(other);
251 numbered_ = other.numbered_;
252 numbers_ = other.numbers_;
253 buffer_ = other.buffer_;
254 for (size_t i = 0; i < label_.size(); ++i)
256 label_ = other.label_;
257 for (size_t i = 0; i != label_.size(); ++i) {
259 label_[i] = new InsetLabel(*label_[i]);
261 preview_.reset(new RenderPreview(*other.preview_, this));
267 void InsetMathHull::setBuffer(Buffer & buffer)
269 InsetMathGrid::setBuffer(buffer);
271 for (size_t i = 0; i != label_.size(); ++i) {
273 label_[i]->setBuffer(buffer);
278 // FIXME This should really be controlled by the TOC level, or
279 // something of the sort.
281 const char * counters_to_save[] = {"section", "chapter"};
282 unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
286 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
289 //FIXME: buffer_ should be set at creation for this inset! Problem is
290 // This inset is created at too many places (see Parser::parse1() in
295 // if any of the equations are numbered, then we want to save the values
296 // of some of the counters.
298 BufferParams const & bp = buffer_->params();
299 string const & lang = it->getParLanguage(bp)->code();
301 buffer_->masterBuffer()->params().documentClass().counters();
303 // right now, we only need to do this at export time
304 if (utype == OutputUpdate) {
305 for (size_t i = 0; i < numcnts; ++i) {
306 docstring const cnt = from_ascii(counters_to_save[i]);
307 if (cnts.hasCounter(cnt))
308 counter_map[cnt] = cnts.value(cnt);
312 // this has to be done separately
313 docstring const eqstr = from_ascii("equation");
314 if (cnts.hasCounter(eqstr)) {
315 if (utype == OutputUpdate)
316 counter_map[eqstr] = cnts.value(eqstr);
317 for (size_t i = 0; i != label_.size(); ++i) {
319 Paragraph const & par = it.paragraph();
320 if (!par.isDeleted(it.pos())) {
321 cnts.step(eqstr, utype);
322 numbers_[i] = cnts.theCounter(eqstr, lang);
324 numbers_[i] = from_ascii("#");
326 numbers_[i] = empty_docstring();
332 for (size_t i = 0; i != label_.size(); ++i) {
334 label_[i]->updateBuffer(it, utype);
337 InsetMathGrid::updateBuffer(it, utype);
341 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active,
342 UpdateType utype, TocBackend & backend) const
345 //FIXME: buffer_ should be set at creation for this inset! Problem is
346 // This inset is created at too many places (see Parser::parse1() in
351 TocBuilder & b = backend.builder("equation");
352 // compute first and last item
353 row_type first = nrows();
354 for (row_type row = 0; row != nrows(); ++row)
359 if (first == nrows())
362 row_type last = nrows() - 1;
363 for (; last != 0; --last)
366 // add equation numbers
367 b.pushItem(pit, docstring(), output_active);
369 b.argumentItem(bformat(from_ascii("(%1$s-%2$s)"),
370 numbers_[first], numbers_[last]));
371 for (row_type row = 0; row != nrows(); ++row) {
375 label_[row]->addToToc(pit, output_active, utype, backend);
376 docstring label = nicelabel(row);
378 // this is the only equation
379 b.argumentItem(label);
381 // insert as sub-items
382 b.pushItem(pit, label, output_active);
390 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
392 if (previewState(&cur.bv())) {
396 return InsetMathNest::editXY(cur, x, y);
400 InsetMath::mode_type InsetMathHull::currentMode() const
404 return UNDECIDED_MODE;
406 // definitely math mode ...
426 // FIXME: InsetMathGrid should be changed to let the real column alignment be
427 // given by a virtual method like displayColAlign, because the values produced
428 // by defaultColAlign can be invalidated by lfuns such as add-column. For the
429 // moment the values produced by defaultColAlign are not used, notably because
430 // alignment is not implemented in the LyXHTML output.
431 char InsetMathHull::defaultColAlign(col_type col)
433 return colAlign(type_, col, buffer().params());
437 char InsetMathHull::displayColAlign(idx_type idx) const
441 row_type const r = row(idx);
444 if (r == nrows() - 1)
455 return colAlign(type_, col(idx), buffer().params());
459 return InsetMathGrid::displayColAlign(idx);
463 int InsetMathHull::displayColSpace(col_type col) const
465 return colSpace(type_, col);
469 // FIXME: same comment as for defaultColAlign applies.
470 int InsetMathHull::defaultColSpace(col_type col)
472 return colSpace(type_, col);
476 string InsetMathHull::standardFont() const
482 return "lyxnochange";
489 ColorCode InsetMathHull::standardColor() const
494 return Color_foreground;
502 bool InsetMathHull::previewState(const BufferView *const bv) const
504 if (!editing(bv) && RenderPreview::previewMath()
505 && type_ != hullRegexp)
507 graphics::PreviewImage const * pimage =
508 preview_->getPreviewImage(bv->buffer());
509 return pimage && pimage->image();
516 const int ERROR_FRAME_WIDTH = 2;
518 bool previewTooSmall(MetricsBase const & mb, Dimension const & dim)
520 // Value was hardcoded to 10 pixels
521 int const minval = mb.bv->zoomedPixels(10);
522 return dim.width() <= minval && dim.height() <= minval;
527 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
529 // true value in LaTeX is 12pt plus 3pt minus 9pt
530 // FIXME: even better would be to handle the short skip case.
531 int const display_margin = display() ? mi.base.inPixels(Length(12, Length::PT)) : 0;
533 if (previewState(mi.base.bv)) {
534 preview_->metrics(mi, dim);
535 if (previewTooSmall(mi.base, dim)) {
536 // preview image is too small
537 dim.wid += 2 * ERROR_FRAME_WIDTH;
538 dim.asc += 2 * ERROR_FRAME_WIDTH;
540 // insert a gap in front of the formula
541 // value was hardcoded to 1 pixel
542 dim.wid += mi.base.bv->zoomedPixels(1) ;
544 dim.asc += display_margin;
545 dim.des += display_margin;
552 Changer dummy1 = mi.base.changeFontSet(standardFont());
553 Changer dummy2 = mi.base.font.changeStyle(display() ? DISPLAY_STYLE
556 // let the cells adjust themselves
557 InsetMathGrid::metrics(mi, dim);
560 // Check whether the numbering interferes with the equations
561 if (numberedType()) {
562 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
563 int extra_offset = 0;
564 for (row_type row = 0; row < nrows(); ++row) {
565 rowinfo(row).offset[mi.base.bv] += extra_offset;
568 docstring const nl = nicelabel(row);
570 mathed_string_dim(mi.base.font, nl, dimnl);
571 int const ind = indent(*mi.base.bv);
572 int const x = ind ? ind : (mi.base.textwidth - dim.wid) / 2;
573 // for some reason metrics does not trigger at the
574 // same point as draw, and therefore we use >= instead of >
575 if ((math_number == BufferParams::LEFT && dimnl.wid >= x)
576 || (math_number == BufferParams::RIGHT
577 && dimnl.wid >= mi.base.textwidth - x - dim.wid)) {
578 extra_offset += dimnl.height();
581 dim.des += extra_offset;
586 dim.asc += display_margin;
587 dim.des += display_margin;
590 // reserve some space for marker.
595 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
597 BufferView const * const bv = pi.base.bv;
598 if (previewState(bv)) {
599 Dimension const dim = dimension(*pi.base.bv);
600 if (previewTooSmall(pi.base, dim))
602 return graphics::PreviewLoader::backgroundColor();
608 void InsetMathHull::drawMarkers(PainterInfo & pi, int x, int y) const
610 ColorCode pen_color = mouseHovered(pi.base.bv) || editing(pi.base.bv)?
611 Color_mathframe : Color_mathcorners;
612 // If the corners have the same color as the background, do not paint them.
613 if (lcolor.getX11Name(Color_mathbg) == lcolor.getX11Name(pen_color))
616 Inset::drawMarkers(pi, x, y);
617 Dimension const dim = dimension(*pi.base.bv);
618 int const t = x + dim.width() - 1;
619 int const a = y - dim.ascent();
620 pi.pain.line(x, a + 3, x, a, pen_color);
621 pi.pain.line(t, a + 3, t, a, pen_color);
622 pi.pain.line(x, a, x + 3, a, pen_color);
623 pi.pain.line(t - 3, a, t, a, pen_color);
627 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
629 Dimension const dim = dimension(*pi.base.bv);
630 if (previewTooSmall(pi.base, dim)) {
631 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
632 dim.wid, dim.asc + dim.des, backgroundColor(pi));
635 // If there are numbers, the margins around the (displayed)
636 // equation have to be cleared.
638 pi.pain.fillRectangle(pi.leftx, y - dim.asc,
639 pi.rightx - pi.leftx, dim.height(), pi.background_color);
640 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
641 dim.asc + dim.des - 1, pi.backgroundColor(this));
645 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
647 BufferView const * const bv = pi.base.bv;
648 Dimension const dim = dimension(*bv);
650 if (type_ == hullRegexp)
651 pi.pain.rectangle(x + 2, y - dim.ascent() + 1,
652 dim.width() - 3, dim.height() - 2, Color_regexpframe);
654 if (previewState(bv)) {
655 // Do not draw change tracking cue if taken care of by RowPainter
657 Changer dummy = !canPaintChange(*bv) ? make_change(pi.change_, Change())
659 if (previewTooSmall(pi.base, dim)) {
660 // we have an extra frame
661 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
663 // one pixel gap in front
664 // value was hardcoded to 1 pixel
665 int const gap = pi.base.bv->zoomedPixels(1) ;
666 preview_->draw(pi, x + gap, y);
671 // First draw the numbers
672 ColorCode color = pi.selected && lyxrc.use_system_colors
673 ? Color_selectiontext : standardColor();
674 bool const really_change_color = pi.base.font.color() == Color_none;
675 Changer dummy0 = really_change_color ? pi.base.font.changeColor(color)
677 if (numberedType()) {
678 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
679 for (row_type row = 0; row < nrows(); ++row) {
680 int yy = y + rowinfo(row).offset[bv];
681 docstring const nl = nicelabel(row);
683 mathed_string_dim(pi.base.font, nl, dimnl);
684 if (math_number == BufferParams::LEFT) {
685 if (dimnl.wid > x - pi.leftx)
686 yy += rowinfo(row).descent + dimnl.asc;
687 pi.draw(pi.leftx, yy, nl);
689 if (dimnl.wid > pi.rightx - x - dim.wid)
690 yy += rowinfo(row).descent + dimnl.asc;
691 pi.draw(pi.rightx - dimnl.wid, yy, nl);
696 // Then the equations
697 Changer dummy1 = pi.base.changeFontSet(standardFont());
698 Changer dummy2 = pi.base.font.changeStyle(display() ? DISPLAY_STYLE
700 InsetMathGrid::draw(pi, x + 1, y);
701 drawMarkers(pi, x, y);
703 // drawing change line
704 if (canPaintChange(*bv))
705 pi.change_.paintCue(pi, x + 1, y + 1 - dim.asc,
706 x + dim.wid, y + dim.des);
710 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
713 InsetMathGrid::metricsT(mi, dim);
716 otexrowstream ots(os);
717 WriteStream wi(ots, false, true, WriteStream::wsDefault);
719 dim.wid = os.str().size();
726 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
729 InsetMathGrid::drawT(pain, x, y);
732 otexrowstream ots(os);
733 WriteStream wi(ots, false, true, WriteStream::wsDefault);
735 pain.draw(x, y, os.str().c_str());
740 static docstring latexString(InsetMathHull const & inset)
743 // This has to be static, because a preview snippet or a math
744 // macro containing math in text mode (such as $\text{$\phi$}$ or
745 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
746 // first time as a whole, and the second time only the inner math.
747 // In this last case inset.buffer() would be invalid.
748 static Encoding const * encoding = 0;
749 if (inset.isBufferValid())
750 encoding = &(inset.buffer().params().encoding());
751 otexrowstream ots(ls);
752 WriteStream wi(ots, false, true, WriteStream::wsPreview, encoding);
758 void InsetMathHull::initUnicodeMath() const
760 // Trigger classification of the unicode symbols in this inset
761 docstring const dummy = latexString(*this);
765 void InsetMathHull::addPreview(DocIterator const & inset_pos,
766 graphics::PreviewLoader & /*ploader*/) const
768 if (RenderPreview::previewMath()) {
769 preparePreview(inset_pos);
774 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
775 MacroNameSet & macros, MacroNameSet & defs) const
777 MacroNameSet::iterator const end = macros.end();
779 for (size_t i = 0; i < md.size(); ++i) {
780 InsetMathMacro const * mi = md[i].nucleus()->asMacro();
781 InsetMathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
782 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
783 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
784 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
785 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
787 // Look for macros in the arguments of this macro.
788 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
789 usedMacros(mi->cell(idx), pos, macros, defs);
790 // Make sure this is a macro defined in the document
791 // (as we also spot the macros in the symbols file)
792 // or that we have not already accounted for it.
793 docstring const name = mi->name();
794 if (macros.find(name) == end)
797 // Look for macros in the definition of this macro.
798 MathData ar(pos.buffer());
799 MacroData const * data =
800 pos.buffer()->getMacro(name, pos, true);
802 odocstringstream macro_def;
803 data->write(macro_def, true);
805 defs.insert(macro_def.str());
806 asArray(data->definition(), ar);
808 usedMacros(ar, pos, macros, defs);
810 MathData ar(pos.buffer());
811 asArray(mt->definition(), ar);
812 usedMacros(ar, pos, macros, defs);
814 if (!si->nuc().empty())
815 usedMacros(si->nuc(), pos, macros, defs);
817 usedMacros(si->down(), pos, macros, defs);
819 usedMacros(si->up(), pos, macros, defs);
820 } else if (fi || gi) {
821 idx_type nidx = fi ? fi->nargs() : gi->nargs();
822 for (idx_type idx = 0; idx < nidx; ++idx)
823 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
826 usedMacros(ni->cell(0), pos, macros, defs);
832 void InsetMathHull::preparePreview(DocIterator const & pos,
833 bool forexport) const
835 // there is no need to do all the macro stuff if we're not
836 // actually going to generate the preview.
837 if (!RenderPreview::previewMath() && !forexport)
840 Buffer const * buffer = pos.buffer();
842 // collect macros at this position
844 buffer->listMacroNames(macros);
846 // collect definitions only for the macros used in this inset
848 for (idx_type idx = 0; idx < nargs(); ++idx)
849 usedMacros(cell(idx), pos, macros, defs);
851 docstring macro_preamble;
852 for (auto const & defvar : defs)
853 macro_preamble.append(defvar);
855 // set the font series and size for this snippet
856 DocIterator dit = pos.getInnerText();
857 Paragraph const & par = dit.paragraph();
858 Font font = par.getFontSettings(buffer->params(), dit.pos());
859 font.fontInfo().realize(par.layout().font);
860 string const lsize = font.latexSize();
863 if (font.fontInfo().series() == BOLD_SERIES) {
864 setfont += from_ascii("\\textbf{");
867 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
868 setfont += from_ascii("\\" + lsize + '\n');
871 if (forexport && haveNumbers()) {
872 docstring eqstr = from_ascii("equation");
873 CounterMap::const_iterator it = counter_map.find(eqstr);
874 if (it != counter_map.end()) {
875 int num = it->second;
877 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
878 '{' + convert<docstring>(num) + '}' + '\n';
880 for (size_t i = 0; i != numcnts; ++i) {
881 docstring cnt = from_ascii(counters_to_save[i]);
882 it = counter_map.find(cnt);
883 if (it == counter_map.end())
885 int num = it->second;
887 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
888 '{' + convert<docstring>(num) + '}';
891 docstring const snippet = macro_preamble + setfont + setcnt
892 + latexString(*this) + endfont;
893 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
894 preview_->addPreview(snippet, *buffer, forexport);
898 void InsetMathHull::reloadPreview(DocIterator const & pos) const
901 preview_->startLoading(*pos.buffer());
905 void InsetMathHull::loadPreview(DocIterator const & pos) const
907 bool const forexport = true;
908 preparePreview(pos, forexport);
909 preview_->startLoading(*pos.buffer(), forexport);
913 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
915 if (RenderPreview::previewMath()) {
917 cur.screenUpdateFlags(Update::Force);
923 docstring InsetMathHull::label(row_type row) const
925 LASSERT(row < nrows(), return docstring());
926 if (InsetLabel * il = label_[row])
927 return il->screenLabel();
932 void InsetMathHull::label(row_type row, docstring const & label)
934 //lyxerr << "setting label '" << label << "' for row " << row << endl;
938 label_[row] = dummy_pointer;
941 label_[row]->updateLabelAndRefs(label);
943 label_[row]->setParam("name", label);
947 InsetCommandParams p(LABEL_CODE);
949 label_[row] = new InsetLabel(buffer_, p);
951 label_[row]->setBuffer(buffer());
955 void InsetMathHull::numbered(row_type row, Numbered num)
957 numbered_[row] = num;
958 if (!numbered(row) && label_[row]) {
965 bool InsetMathHull::numbered(row_type row) const
967 return numbered_[row] == NUMBER;
971 bool InsetMathHull::ams() const
991 for (size_t row = 0; row < numbered_.size(); ++row)
992 if (numbered_[row] == NOTAG)
998 bool InsetMathHull::outerDisplay() const
1021 Inset::DisplayType InsetMathHull::display() const
1038 if (buffer().params().is_math_indent)
1048 int InsetMathHull::indent(BufferView const & bv) const
1050 // FIXME: set this in the textclass. This value is what the article class uses.
1051 static Length default_indent(2.5, Length::EM);
1052 if (display() != Inline && buffer().params().is_math_indent) {
1053 Length const & len = buffer().params().getMathIndent();
1055 return bv.inPixels(default_indent);
1057 return bv.inPixels(len);
1059 return Inset::indent(bv);
1063 bool InsetMathHull::numberedType() const
1082 for (row_type row = 0; row < nrows(); ++row)
1089 void InsetMathHull::validate(LaTeXFeatures & features) const
1091 if (features.runparams().isLaTeX()) {
1093 features.require("amsmath");
1095 if (type_ == hullRegexp) {
1096 features.require("color");
1097 docstring frcol = from_utf8(lcolor.getLaTeXName(Color_regexpframe));
1098 docstring bgcol = from_ascii("white");
1099 features.addPreambleSnippet(
1100 "\\newcommand{\\regexp}[1]{\\fcolorbox{"
1102 + bgcol + "}{\\ensuremath{\\mathtt{#1}}}}");
1103 features.addPreambleSnippet(
1104 from_ascii("\\newcommand{\\endregexp}{}"));
1105 } else if (outerDisplay() && features.inDeletedInset()
1106 && !features.mustProvide("ct-dvipost")) {
1107 features.require("ct-tikz-math-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 void InsetMathHull::header_write(WriteStream & os) const
1132 bool n = numberedType();
1143 if (cell(0).empty())
1148 writeMathdisplayPreamble(os);
1152 os << "\\begin{equation" << star(n) << "}\n";
1162 writeMathdisplayPreamble(os);
1165 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1172 os << "\\begin{" << hullName(type_) << star(n) << '}'
1173 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1179 os << "\\begin{" << hullName(type_) << '}'
1180 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1190 os << "\\begin{unknown" << star(n) << "}\n";
1196 void InsetMathHull::footer_write(WriteStream & os) const
1198 bool n = numberedType();
1215 os << "\\end{equation" << star(n) << "}\n";
1218 writeMathdisplayPostamble(os);
1228 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1229 writeMathdisplayPostamble(os);
1236 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1242 os << "\\end{" << hullName(type_) << "}\n";
1246 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1247 os << "\\endregexp{}}";
1253 os << "\\end{unknown" << star(n) << "}\n";
1259 bool InsetMathHull::allowsTabularFeatures() const
1282 bool InsetMathHull::rowChangeOK() const
1285 type_ == hullEqnArray || type_ == hullAlign ||
1286 type_ == hullFlAlign || type_ == hullAlignAt ||
1287 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1288 type_ == hullGather || type_ == hullMultline;
1292 bool InsetMathHull::colChangeOK() const
1295 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1296 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1300 void InsetMathHull::addRow(row_type row)
1305 bool numbered = numberedType();
1306 // Move the number and raw pointer, do not call label() (bug 7511)
1307 InsetLabel * label = dummy_pointer;
1308 docstring number = empty_docstring();
1309 if (type_ == hullMultline) {
1310 if (row + 1 == nrows()) {
1311 numbered_[row] = NONUMBER;
1312 swap(label, label_[row]);
1313 swap(number, numbers_[row]);
1318 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1319 numbers_.insert(numbers_.begin() + row + 1, number);
1320 label_.insert(label_.begin() + row + 1, label);
1321 InsetMathGrid::addRow(row);
1325 void InsetMathHull::swapRow(row_type row)
1329 if (row + 1 == nrows())
1331 swap(numbered_[row], numbered_[row + 1]);
1332 swap(numbers_[row], numbers_[row + 1]);
1333 swap(label_[row], label_[row + 1]);
1334 InsetMathGrid::swapRow(row);
1338 void InsetMathHull::delRow(row_type row)
1340 if (nrows() <= 1 || !rowChangeOK())
1342 if (row + 1 == nrows() && type_ == hullMultline) {
1343 swap(numbered_[row - 1], numbered_[row]);
1344 swap(numbers_[row - 1], numbers_[row]);
1345 swap(label_[row - 1], label_[row]);
1346 InsetMathGrid::delRow(row);
1349 InsetMathGrid::delRow(row);
1350 // The last dummy row has no number info nor a label.
1351 // Test nrows() + 1 because we have already erased the row.
1352 if (row == nrows() + 1)
1354 numbered_.erase(numbered_.begin() + row);
1355 numbers_.erase(numbers_.begin() + row);
1357 label_.erase(label_.begin() + row);
1361 void InsetMathHull::addCol(col_type col)
1365 InsetMathGrid::addCol(col);
1369 void InsetMathHull::delCol(col_type col)
1371 if (ncols() <= 1 || !colChangeOK())
1373 InsetMathGrid::delCol(col);
1377 docstring InsetMathHull::nicelabel(row_type row) const
1381 docstring const & val = numbers_[row];
1383 return '(' + val + ')';
1384 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1388 void InsetMathHull::glueall(HullType type)
1391 for (idx_type i = 0; i < nargs(); ++i)
1393 InsetLabel * label = 0;
1394 if (type == hullEquation) {
1395 // preserve first non-empty label
1396 for (row_type row = 0; row < nrows(); ++row) {
1398 label = label_[row];
1404 *this = InsetMathHull(buffer_, hullSimple);
1411 void InsetMathHull::splitTo2Cols()
1413 LASSERT(ncols() == 1, return);
1414 InsetMathGrid::addCol(1);
1415 for (row_type row = 0; row < nrows(); ++row) {
1416 idx_type const i = 2 * row;
1417 pos_type pos = firstRelOp(cell(i));
1418 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1419 cell(i).erase(pos, cell(i).size());
1424 void InsetMathHull::splitTo3Cols()
1426 LASSERT(ncols() < 3, return);
1429 InsetMathGrid::addCol(2);
1430 for (row_type row = 0; row < nrows(); ++row) {
1431 idx_type const i = 3 * row + 1;
1432 if (!cell(i).empty()) {
1433 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1434 cell(i).erase(1, cell(i).size());
1440 void InsetMathHull::changeCols(col_type cols)
1442 if (ncols() == cols)
1444 else if (ncols() < cols) {
1450 while (ncols() < cols)
1451 InsetMathGrid::addCol(ncols());
1457 for (row_type row = 0; row < nrows(); ++row) {
1458 idx_type const i = row * ncols();
1459 for (col_type col = cols; col < ncols(); ++col) {
1460 cell(i + cols - 1).append(cell(i + col));
1464 while (ncols() > cols) {
1465 InsetMathGrid::delCol(ncols() - 1);
1470 HullType InsetMathHull::getType() const
1476 void InsetMathHull::setType(HullType type)
1483 bool InsetMathHull::isMutable(HullType type)
1507 void InsetMathHull::mutate(HullType newtype)
1509 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1511 if (newtype == type_)
1514 // This guards the algorithm below it, which is designed with certain types
1516 if (!isMutable(newtype) || !isMutable(type_)) {
1517 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1518 << "' to '" << to_utf8(hullName(newtype))
1519 << "' not implemented" << endl;
1523 // we try to move along the chain
1524 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1526 // +-------------------------------------+
1527 // we use eqnarray as intermediate type for mutations that are not
1528 // directly supported because it handles labels and numbering for
1533 setType(hullSimple);
1539 if (newtype == hullNone) {
1543 setType(hullEquation);
1544 numbered(0, label_[0] ? true : false);
1553 setType(hullSimple);
1558 // split it "nicely" on the first relop
1560 setType(hullEqnArray);
1568 // split it "nicely"
1603 setType(hullEqnArray);
1612 for (row_type row = 0; row < nrows(); ++row)
1613 numbered(row, false);
1623 for (row_type row = 0; row < nrows(); ++row)
1624 numbered(row, false);
1631 setType(hullEqnArray);
1661 for (row_type row = 0; row < nrows(); ++row)
1662 numbered(row, false);
1666 // first we mutate to EqnArray
1668 setType(hullEqnArray);
1675 // we passed the guard so we should not be here
1676 LYXERR0("Mutation not implemented, but should have been.");
1677 LASSERT(false, return);
1683 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1684 bool last_eoln) const
1687 if (numberedType()) {
1688 if (label_[row] && numbered(row)) {
1689 docstring const name =
1690 latex ? escape(label_[row]->getParam("name"))
1691 : label_[row]->getParam("name");
1692 res += "\\label{" + name + '}';
1694 if (type_ != hullMultline) {
1695 if (numbered_[row] == NONUMBER)
1696 res += "\\nonumber ";
1697 else if (numbered_[row] == NOTAG)
1701 // Never add \\ on the last empty line of eqnarray and friends
1703 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1706 void InsetMathHull::write(WriteStream & os) const
1708 ModeSpecifier specifier(os, MATH_MODE);
1710 InsetMathGrid::write(os);
1715 void InsetMathHull::normalize(NormalStream & os) const
1717 os << "[formula " << hullName(type_) << ' ';
1718 InsetMathGrid::normalize(os);
1723 void InsetMathHull::infoize(odocstream & os) const
1725 os << bformat(_("Type: %1$s"), hullName(type_));
1729 void InsetMathHull::check() const
1731 LATTEST(numbered_.size() == nrows());
1732 LATTEST(numbers_.size() == nrows());
1733 LATTEST(label_.size() == nrows());
1737 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1739 //FIXME: sort out whether we want std::string or docstring for those
1740 string const lang = func.getArg(0);
1741 docstring extra = from_utf8(func.getArg(1));
1743 extra = from_ascii("noextra");
1745 // replace selection with result of computation
1746 if (reduceSelectionToOneCell(cur)) {
1748 asArray(grabAndEraseSelection(cur), ar);
1749 lyxerr << "use selection: " << ar << endl;
1750 cur.insert(pipeThroughExtern(lang, extra, ar));
1754 // only inline, display or eqnarray math is allowed
1755 switch (getType()) {
1761 frontend::Alert::warning(_("Bad math environment"),
1762 _("Computation cannot be performed for AMS "
1763 "math environments.\nChange the math "
1764 "formula type and try again."));
1769 eq.push_back(MathAtom(new InsetMathChar('=')));
1771 // go to first item in line
1772 cur.idx() -= cur.idx() % ncols();
1775 if (getType() == hullSimple) {
1776 size_type pos = cur.cell().find_last(eq);
1778 if (pos == cur.cell().size()) {
1780 lyxerr << "use whole cell: " << ar << endl;
1782 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1783 lyxerr << "use partial cell form pos: " << pos << endl;
1785 cur.cell().append(eq);
1786 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1787 cur.pos() = cur.lastpos();
1791 if (getType() == hullEquation) {
1792 lyxerr << "use equation inset" << endl;
1793 mutate(hullEqnArray);
1794 MathData & ar = cur.cell();
1795 lyxerr << "use cell: " << ar << endl;
1799 cur.cell() = pipeThroughExtern(lang, extra, ar);
1800 // move to end of line
1801 cur.pos() = cur.lastpos();
1806 lyxerr << "use eqnarray" << endl;
1807 cur.idx() += 2 - cur.idx() % ncols();
1809 MathData ar = cur.cell();
1810 lyxerr << "use cell: " << ar << endl;
1811 // FIXME: temporarily disabled
1817 cur.cell() = pipeThroughExtern(lang, extra, ar);
1818 cur.pos() = cur.lastpos();
1823 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1825 //lyxerr << "action: " << cmd.action() << endl;
1826 switch (cmd.action()) {
1828 case LFUN_FINISHED_BACKWARD:
1829 case LFUN_FINISHED_FORWARD:
1830 case LFUN_FINISHED_RIGHT:
1831 case LFUN_FINISHED_LEFT:
1832 //lyxerr << "action: " << cmd.action() << endl;
1833 InsetMathGrid::doDispatch(cur, cmd);
1836 case LFUN_PARAGRAPH_BREAK:
1837 // just swallow this
1840 case LFUN_NEWLINE_INSERT:
1841 // some magic for the common case
1842 if (type_ == hullSimple || type_ == hullEquation) {
1843 cur.recordUndoInset();
1845 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1846 mutate(align ? hullAlign : hullEqnArray);
1847 // mutate() may change labels and such.
1848 cur.forceBufferUpdate();
1849 cur.idx() = nrows() * ncols() - 1;
1850 cur.pos() = cur.lastpos();
1852 InsetMathGrid::doDispatch(cur, cmd);
1855 case LFUN_MATH_NUMBER_TOGGLE: {
1856 //lyxerr << "toggling all numbers" << endl;
1857 cur.recordUndoInset();
1858 bool old = numberedType();
1859 if (type_ == hullMultline)
1860 numbered(nrows() - 1, !old);
1862 for (row_type row = 0; row < nrows(); ++row)
1863 numbered(row, !old);
1865 cur.message(old ? _("No number") : _("Number"));
1866 cur.forceBufferUpdate();
1870 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1871 cur.recordUndoInset();
1872 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1873 bool old = numbered(r);
1874 cur.message(old ? _("No number") : _("Number"));
1876 cur.forceBufferUpdate();
1880 case LFUN_LABEL_INSERT: {
1881 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1882 docstring old_label = label(r);
1883 docstring const default_label = from_ascii("eq:");
1884 if (old_label.empty())
1885 old_label = default_label;
1887 InsetCommandParams p(LABEL_CODE);
1888 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1889 string const data = InsetCommand::params2string(p);
1891 if (cmd.argument().empty())
1892 cur.bv().showDialog("label", data);
1894 FuncRequest fr(LFUN_INSET_INSERT, data);
1900 case LFUN_LABEL_COPY_AS_REFERENCE: {
1902 if (cmd.argument().empty() && &cur.inset() == this)
1903 // if there is no argument and we're inside math, we retrieve
1904 // the row number from the cursor position.
1905 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1907 // if there is an argument, find the corresponding label, else
1908 // check whether there is at least one label.
1909 for (row = 0; row != nrows(); ++row)
1910 if (numbered(row) && label_[row]
1911 && (cmd.argument().empty() || label(row) == cmd.argument()))
1918 InsetCommandParams p(REF_CODE, "ref");
1919 p["reference"] = label(row);
1920 cap::clearSelection();
1921 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1925 case LFUN_WORD_DELETE_FORWARD:
1926 case LFUN_CHAR_DELETE_FORWARD:
1927 if (col(cur.idx()) + 1 == ncols()
1928 && cur.pos() == cur.lastpos()
1929 && !cur.selection()) {
1930 if (!label(row(cur.idx())).empty()) {
1931 cur.recordUndoInset();
1932 label(row(cur.idx()), docstring());
1933 } else if (numbered(row(cur.idx()))) {
1934 cur.recordUndoInset();
1935 numbered(row(cur.idx()), false);
1936 cur.forceBufferUpdate();
1938 InsetMathGrid::doDispatch(cur, cmd);
1942 InsetMathGrid::doDispatch(cur, cmd);
1947 case LFUN_INSET_INSERT: {
1948 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1949 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1950 string const name = cmd.getArg(0);
1951 if (name == "label") {
1952 InsetCommandParams p(LABEL_CODE);
1953 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1954 docstring str = p["name"];
1955 cur.recordUndoInset();
1956 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1960 docstring old = label(r);
1963 // The label will take care of the reference update.
1967 // Newly created inset so initialize it.
1968 label_[r]->initView();
1971 cur.forceBufferUpdate();
1974 InsetMathGrid::doDispatch(cur, cmd);
1978 case LFUN_MATH_EXTERN:
1979 cur.recordUndoInset();
1983 case LFUN_MATH_MUTATE: {
1984 cur.recordUndoInset();
1985 row_type row = cur.row();
1986 col_type col = cur.col();
1987 mutate(hullType(cmd.argument()));
1988 cur.idx() = row * ncols() + col;
1989 if (cur.idx() > cur.lastidx()) {
1990 cur.idx() = cur.lastidx();
1991 cur.pos() = cur.lastpos();
1993 if (cur.pos() > cur.lastpos())
1994 cur.pos() = cur.lastpos();
1996 cur.forceBufferUpdate();
1997 // FIXME: find some more clever handling of the selection,
1998 // i.e. preserve it.
1999 cur.clearSelection();
2000 //cur.dispatched(FINISHED);
2004 case LFUN_MATH_DISPLAY: {
2005 cur.recordUndoInset();
2006 mutate(type_ == hullSimple ? hullEquation : hullSimple);
2007 // if the cursor is in a cell that got merged, move it to
2008 // start of the hull inset.
2009 if (cur.idx() > 0) {
2013 if (cur.pos() > cur.lastpos())
2014 cur.pos() = cur.lastpos();
2019 case LFUN_TABULAR_FEATURE:
2020 if (!allowsTabularFeatures())
2023 InsetMathGrid::doDispatch(cur, cmd);
2027 InsetMathGrid::doDispatch(cur, cmd);
2035 bool allowDisplayMath(Cursor const & cur)
2037 LATTEST(cur.depth() > 1);
2038 Cursor tmpcur = cur;
2041 FuncRequest cmd(LFUN_MATH_DISPLAY);
2042 return tmpcur.getStatus(cmd, status) && status.enabled();
2048 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
2049 FuncStatus & status) const
2051 switch (cmd.action()) {
2052 case LFUN_FINISHED_BACKWARD:
2053 case LFUN_FINISHED_FORWARD:
2054 case LFUN_FINISHED_RIGHT:
2055 case LFUN_FINISHED_LEFT:
2058 case LFUN_NEWLINE_INSERT:
2059 case LFUN_MATH_EXTERN:
2061 status.setEnabled(true);
2064 // we never allow this in math, and we want to bind enter
2065 // to another actions in command-alternatives
2066 case LFUN_PARAGRAPH_BREAK:
2067 status.setEnabled(false);
2069 case LFUN_MATH_MUTATE: {
2070 HullType const ht = hullType(cmd.argument());
2071 status.setOnOff(type_ == ht);
2072 status.setEnabled(isMutable(ht) && isMutable(type_));
2074 if (ht != hullSimple && status.enabled())
2075 status.setEnabled(allowDisplayMath(cur));
2078 case LFUN_MATH_DISPLAY: {
2079 status.setEnabled(display() != Inline || allowDisplayMath(cur));
2080 status.setOnOff(display() != Inline);
2084 case LFUN_MATH_NUMBER_TOGGLE:
2085 // FIXME: what is the right test, this or the one of
2087 status.setEnabled(display() != Inline);
2088 status.setOnOff(numberedType());
2091 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
2092 // FIXME: what is the right test, this or the one of
2094 bool const enable = (type_ == hullMultline)
2095 ? (nrows() - 1 == cur.row())
2096 : display() != Inline;
2097 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2098 status.setEnabled(enable);
2099 status.setOnOff(enable && numbered(r));
2103 case LFUN_LABEL_INSERT:
2104 status.setEnabled(type_ != hullSimple);
2107 case LFUN_LABEL_COPY_AS_REFERENCE: {
2108 bool enabled = false;
2109 if (cmd.argument().empty() && &cur.inset() == this) {
2110 // if there is no argument and we're inside math, we retrieve
2111 // the row number from the cursor position.
2112 row_type row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2113 enabled = numberedType() && label_[row] && numbered(row);
2115 // if there is an argument, find the corresponding label, else
2116 // check whether there is at least one label.
2117 for (row_type row = 0; row != nrows(); ++row) {
2118 if (numbered(row) && label_[row] &&
2119 (cmd.argument().empty() || label(row) == cmd.argument())) {
2125 status.setEnabled(enabled);
2129 case LFUN_INSET_INSERT:
2130 if (cmd.getArg(0) == "label") {
2131 status.setEnabled(type_ != hullSimple);
2134 return InsetMathGrid::getStatus(cur, cmd, status);
2136 case LFUN_TABULAR_FEATURE: {
2137 if (!allowsTabularFeatures())
2139 string s = cmd.getArg(0);
2141 && (s == "append-row"
2142 || s == "delete-row"
2143 || s == "copy-row")) {
2144 status.message(bformat(
2145 from_utf8(N_("Can't change number of rows in '%1$s'")),
2147 status.setEnabled(false);
2151 && (s == "append-column"
2152 || s == "delete-column"
2153 || s == "copy-column")) {
2154 status.message(bformat(
2155 from_utf8(N_("Can't change number of columns in '%1$s'")),
2157 status.setEnabled(false);
2160 if (s == "add-vline-left" || s == "add-vline-right") {
2161 status.message(bformat(
2162 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2164 status.setEnabled(false);
2167 if (s == "valign-top" || s == "valign-middle"
2168 || s == "valign-bottom" || s == "align-left"
2169 || s == "align-center" || s == "align-right") {
2170 status.setEnabled(false);
2173 return InsetMathGrid::getStatus(cur, cmd, status);
2177 return InsetMathGrid::getStatus(cur, cmd, status);
2182 int InsetMathHull::leftMargin() const
2184 return (getType() == hullSimple) ? 0 : InsetMathGrid::leftMargin();
2188 int InsetMathHull::rightMargin() const
2190 return (getType() == hullSimple) ? 0 : InsetMathGrid::rightMargin();
2194 int InsetMathHull::border() const
2196 return (getType() == hullSimple) ? 0 : InsetMathGrid::border();
2200 /////////////////////////////////////////////////////////////////////
2204 // simply scrap this function if you want
2205 void InsetMathHull::mutateToText()
2208 // translate to latex
2210 latex(os, false, false);
2211 string str = os.str();
2214 Text * lt = view_->cursor().innerText();
2215 string::const_iterator cit = str.begin();
2216 string::const_iterator end = str.end();
2217 for (; cit != end; ++cit)
2218 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2221 //dispatch(LFUN_ESCAPE);
2226 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2227 docstring const & font)
2229 // this whole function is a hack and won't work for incremental font
2232 if (cur.inset().asInsetMath()->name() == font)
2233 cur.handleFont(to_utf8(font));
2235 cur.handleNest(createInsetMath(font, cur.buffer()));
2241 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2246 font.fromString(to_utf8(arg), b);
2247 if (font.fontInfo().color() != Color_inherit) {
2248 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2254 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2256 InsetMathNest::edit(cur, front, entry_from);
2257 // The inset formula dimension is not necessarily the same as the
2258 // one of the instant preview image, so we have to indicate to the
2259 // BufferView that a metrics update is needed.
2260 cur.screenUpdateFlags(Update::Force);
2264 /////////////////////////////////////////////////////////////////////
2268 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2271 // FIXME: completely broken
2272 static InsetMathHull * lastformula = 0;
2273 static CursorBase current = DocIterator(ibegin(nucleus()));
2275 static string laststr;
2277 if (lastformula != this || laststr != str) {
2278 //lyxerr << "reset lastformula to " << this << endl;
2281 current = ibegin(nucleus());
2283 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2287 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2289 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2290 CursorSlice & top = it.back();
2291 MathData const & a = top.asInsetMath()->cell(top.idx_);
2292 if (a.matchpart(ar, top.pos_)) {
2293 bv->cursor().setSelection(it, ar.size());
2295 top.pos_ += ar.size();
2301 //lyxerr << "not found!" << endl;
2308 void InsetMathHull::write(ostream & os) const
2310 odocstringstream oss;
2311 otexrowstream ots(oss);
2312 WriteStream wi(ots, false, false, WriteStream::wsDefault);
2315 os << to_utf8(oss.str());
2319 void InsetMathHull::read(Lexer & lex)
2322 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2323 operator=(*at->asHullInset());
2327 bool InsetMathHull::readQuiet(Lexer & lex)
2330 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2332 operator=(*at->asHullInset());
2337 int InsetMathHull::plaintext(odocstringstream & os,
2338 OutputParams const & op, size_t max_length) const
2340 // Try enabling this now that there is a flag as requested at #2275.
2341 if (buffer().isExporting() && display()) {
2345 TextPainter tpain(dim.width(), dim.height());
2346 drawT(tpain, 0, dim.ascent());
2348 // reset metrics cache to "real" values
2350 return tpain.textheight();
2353 odocstringstream oss;
2354 otexrowstream ots(oss);
2355 Encoding const * const enc = encodings.fromLyXName("utf8");
2356 WriteStream wi(ots, false, true, WriteStream::wsDefault, enc);
2359 if (type_ == hullRegexp)
2362 for (row_type r = 0; r < nrows(); ++r) {
2363 for (col_type c = 0; c < ncols(); ++c)
2364 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2365 // if it's for the TOC, we write just the first line
2366 // and do not include the newline.
2367 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2369 if (r < nrows() - 1)
2373 docstring const str = oss.str();
2379 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
2384 if (getType() == hullSimple)
2385 name = from_ascii("inlineequation");
2387 name = from_ascii("informalequation");
2389 docstring bname = name;
2390 if (!label(0).empty())
2391 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
2393 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
2395 odocstringstream ls;
2397 if (runparams.flavor == OutputParams::XML) {
2398 ms << MTag("alt role='tex' ");
2399 // Workaround for db2latex: db2latex always includes equations with
2400 // \ensuremath{} or \begin{display}\end{display}
2401 // so we strip LyX' math environment
2402 WriteStream wi(ols, false, false, WriteStream::wsDefault, runparams.encoding);
2403 InsetMathGrid::write(wi);
2404 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2409 InsetMathGrid::mathmlize(ms);
2412 ms << MTag("alt role='tex'");
2413 latex(ols, runparams);
2414 res = ols.texrow().rows();
2415 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2419 ms << from_ascii("<graphic fileref=\"eqn/");
2420 if (!label(0).empty())
2421 ms << sgml::cleanID(buffer(), runparams, label(0));
2423 ms << sgml::uniqueID(from_ascii("anon"));
2425 if (runparams.flavor == OutputParams::XML)
2426 ms << from_ascii("\"/>");
2428 ms << from_ascii("\">");
2430 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2432 return ms.line() + res;
2436 bool InsetMathHull::haveNumbers() const
2438 bool havenumbers = false;
2439 // inline formulas are never numbered (bug 7351 part 3)
2440 if (getType() == hullSimple)
2442 for (size_t i = 0; i != numbered_.size(); ++i) {
2453 // We need to do something about alignment here.
2455 // This duplicates code from InsetMathGrid, but
2456 // we need access here to number information,
2457 // and we simply do not have that in InsetMathGrid.
2458 void InsetMathHull::htmlize(HtmlStream & os) const
2460 bool const havenumbers = haveNumbers();
2461 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2464 os << cell(index(0, 0));
2468 os << MTag("table", "class='mathtable'");
2469 for (row_type row = 0; row < nrows(); ++row) {
2471 for (col_type col = 0; col < ncols(); ++col) {
2473 os << cell(index(row, col));
2478 docstring const & num = numbers_[row];
2480 os << '(' << num << ')';
2485 os << ETag("table");
2489 // this duplicates code from InsetMathGrid, but
2490 // we need access here to number information,
2491 // and we simply do not have that in InsetMathGrid.
2492 void InsetMathHull::mathmlize(MathStream & os) const
2494 bool const havenumbers = haveNumbers();
2495 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2498 os << MTag("mtable");
2499 char const * const celltag = havetable ? "mtd" : "mrow";
2500 // FIXME There does not seem to be wide support at the moment
2501 // for mlabeledtr, so we have to use just mtr for now.
2502 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2503 char const * const rowtag = "mtr";
2504 for (row_type row = 0; row < nrows(); ++row) {
2507 for (col_type col = 0; col < ncols(); ++col) {
2509 << cell(index(row, col))
2515 docstring const & num = numbers_[row];
2517 os << '(' << num << ')';
2524 os << ETag("mtable");
2528 void InsetMathHull::mathAsLatex(WriteStream & os) const
2530 MathEnsurer ensurer(os, false);
2531 bool havenumbers = haveNumbers();
2532 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2535 os << cell(index(0, 0));
2539 os << "<table class='mathtable'>";
2540 for (row_type row = 0; row < nrows(); ++row) {
2542 for (col_type col = 0; col < ncols(); ++col) {
2543 os << "<td class='math'>";
2544 os << cell(index(row, col));
2549 docstring const & num = numbers_[row];
2551 os << '(' << num << ')';
2560 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2562 BufferParams::MathOutput const mathtype =
2563 buffer().masterBuffer()->params().html_math_output;
2565 bool success = false;
2567 // we output all the labels just at the beginning of the equation.
2568 // this should be fine.
2569 for (size_t i = 0; i != label_.size(); ++i) {
2570 InsetLabel const * const il = label_[i];
2576 // FIXME Eventually we would like to do this inset by inset.
2577 if (mathtype == BufferParams::MathML) {
2578 odocstringstream os;
2583 } catch (MathExportException const &) {}
2585 if (getType() == hullSimple)
2586 xs << html::StartTag("math",
2587 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2589 xs << html::StartTag("math",
2590 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2591 xs << XHTMLStream::ESCAPE_NONE
2593 << html::EndTag("math");
2595 } else if (mathtype == BufferParams::HTML) {
2596 odocstringstream os;
2601 } catch (MathExportException const &) {}
2603 string const tag = (getType() == hullSimple) ? "span" : "div";
2604 xs << html::StartTag(tag, "class='formula'", true)
2605 << XHTMLStream::ESCAPE_NONE
2607 << html::EndTag(tag);
2611 // what we actually want is this:
2613 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2615 // || mathtype == BufferParams::Images
2617 // but what follows is equivalent, since we'll enter only if either (a) we
2618 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2619 // aren't doing LaTeX.
2621 // so this is for Images.
2622 if (!success && mathtype != BufferParams::LaTeX) {
2623 graphics::PreviewImage const * pimage = 0;
2625 loadPreview(docit_);
2626 pimage = preview_->getPreviewImage(buffer());
2627 // FIXME Do we always have png?
2630 if (pimage || op.dryrun) {
2631 string const filename = pimage ? pimage->filename().onlyFileName()
2632 : "previewimage.png";
2634 // if we are not in the master buffer, then we need to see that the
2635 // generated image is copied there; otherwise, preview fails.
2636 Buffer const * mbuf = buffer().masterBuffer();
2637 if (mbuf != &buffer()) {
2638 string mbtmp = mbuf->temppath();
2639 FileName const mbufimg(support::addName(mbtmp, filename));
2640 pimage->filename().copyTo(mbufimg);
2642 // add the file to the list of files to be exported
2643 op.exportdata->addExternalFile("xhtml", pimage->filename());
2646 string const tag = (getType() == hullSimple) ? "span" : "div";
2648 << html::StartTag(tag, "style = \"text-align: center;\"")
2649 << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2650 << html::EndTag(tag)
2656 // so we'll pass this test if we've failed everything else, or
2657 // if mathtype was LaTeX, since we won't have entered any of the
2659 if (!success /* || mathtype != BufferParams::LaTeX */) {
2660 // Unfortunately, we cannot use latexString() because we do not want
2661 // $...$ or whatever.
2662 odocstringstream ls;
2663 otexrowstream ots(ls);
2664 WriteStream wi(ots, false, true, WriteStream::wsPreview);
2665 ModeSpecifier specifier(wi, MATH_MODE);
2667 docstring const latex = ls.str();
2669 // class='math' allows for use of jsMath
2670 // http://www.math.union.edu/~dpvc/jsMath/
2672 // probably should allow for some kind of customization here
2673 string const tag = (getType() == hullSimple) ? "span" : "div";
2674 xs << html::StartTag(tag, "class='math'")
2676 << html::EndTag(tag)
2683 void InsetMathHull::toString(odocstream & os) const
2685 odocstringstream ods;
2686 plaintext(ods, OutputParams(0));
2691 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2693 odocstringstream ods;
2696 // FIXME: this results in spilling TeX into the LyXHTML output since the
2697 // outliner is used to generate the LyXHTML list of figures/etc.
2703 string InsetMathHull::contextMenuName() const
2705 return "context-math";
2709 void InsetMathHull::recordLocation(DocIterator const & di)
2715 bool InsetMathHull::canPaintChange(BufferView const &) const
2717 // We let RowPainter do it seamlessly for inline insets
2718 return display() != Inline;