2 * \file InsetMathHull.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 #include "InsetMathHull.h"
15 #include "InsetMathChar.h"
16 #include "InsetMathColor.h"
17 #include "InsetMathFrac.h"
18 #include "InsetMathNest.h"
19 #include "InsetMathScript.h"
20 #include "MathExtern.h"
21 #include "MathFactory.h"
22 #include "MathStream.h"
23 #include "MathSupport.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
30 #include "CutAndPaste.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
36 #include "LaTeXFeatures.h"
38 #include "MacroTable.h"
39 #include "InsetMathMacro.h"
40 #include "InsetMathMacroTemplate.h"
41 #include "MetricsInfo.h"
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/PreviewImage.h"
55 #include "graphics/PreviewLoader.h"
57 #include "frontends/alert.h"
58 #include "frontends/FontMetrics.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/Changer.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(TeXMathStream & os)
126 if (os.strikeoutMath())
129 if (os.ulemCmd() == TeXMathStream::UNDERLINE)
130 os << "\\raisebox{-\\belowdisplayshortskip}{"
131 "\\parbox[b]{\\linewidth}{";
132 else if (os.ulemCmd() == TeXMathStream::STRIKEOUT)
133 os << "\\parbox{\\linewidth}{";
137 // writes a postamble for underlined or struck out math display
138 void writeMathdisplayPostamble(TeXMathStream & os)
140 if (os.strikeoutMath())
143 if (os.ulemCmd() == TeXMathStream::UNDERLINE)
145 else if (os.ulemCmd() == TeXMathStream::STRIKEOUT)
152 static InsetLabel * dummy_pointer = 0;
154 InsetMathHull::InsetMathHull(Buffer * buf)
155 : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, NONUMBER),
156 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
157 preview_(new RenderPreview(this))
159 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
160 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
161 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
162 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
169 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
170 : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, NONUMBER),
171 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
172 preview_(new RenderPreview(this))
180 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
186 InsetMathHull::~InsetMathHull()
188 for (auto & i : label_)
193 Inset * InsetMathHull::clone() const
195 return new InsetMathHull(*this);
199 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
203 InsetMathGrid::operator=(other);
205 numbered_ = other.numbered_;
206 numbers_ = other.numbers_;
207 buffer_ = other.buffer_;
208 for (auto & i : label_)
210 label_ = other.label_;
211 for (size_t i = 0; i != label_.size(); ++i) {
213 label_[i] = new InsetLabel(*label_[i]);
215 preview_.reset(new RenderPreview(*other.preview_, this));
221 void InsetMathHull::setBuffer(Buffer & buffer)
223 InsetMathGrid::setBuffer(buffer);
225 for (size_t i = 0; i != label_.size(); ++i) {
227 label_[i]->setBuffer(buffer);
232 // FIXME This should really be controlled by the TOC level, or
233 // something of the sort.
235 const char * counters_to_save[] = {"section", "chapter"};
236 unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
240 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
243 //FIXME: buffer_ should be set at creation for this inset! Problem is
244 // This inset is created at too many places (see Parser::parse1() in
249 // if any of the equations are numbered, then we want to save the values
250 // of some of the counters.
252 BufferParams const & bp = buffer_->params();
253 string const & lang = it->getParLanguage(bp)->code();
255 buffer_->masterBuffer()->params().documentClass().counters();
257 // right now, we only need to do this at export time
258 if (utype == OutputUpdate) {
259 for (size_t i = 0; i < numcnts; ++i) {
260 docstring const cnt = from_ascii(counters_to_save[i]);
261 if (cnts.hasCounter(cnt))
262 counter_map[cnt] = cnts.value(cnt);
266 // this has to be done separately
267 docstring const eqstr = from_ascii("equation");
268 if (cnts.hasCounter(eqstr)) {
269 if (utype == OutputUpdate)
270 counter_map[eqstr] = cnts.value(eqstr);
271 for (size_t i = 0; i != label_.size(); ++i) {
273 Paragraph const & par = it.paragraph();
274 if (!par.isDeleted(it.pos())) {
275 cnts.step(eqstr, utype);
276 numbers_[i] = cnts.theCounter(eqstr, lang);
278 numbers_[i] = from_ascii("#");
280 numbers_[i] = empty_docstring();
286 for (size_t i = 0; i != label_.size(); ++i) {
288 label_[i]->updateBuffer(it, utype, deleted);
291 InsetMathGrid::updateBuffer(it, utype, deleted);
295 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active,
296 UpdateType utype, TocBackend & backend) const
299 //FIXME: buffer_ should be set at creation for this inset! Problem is
300 // This inset is created at too many places (see Parser::parse1() in
305 TocBuilder & b = backend.builder("equation");
306 // compute first and last item
307 row_type first = nrows();
308 for (row_type row = 0; row != nrows(); ++row)
313 if (first == nrows())
316 row_type last = nrows() - 1;
317 for (; last != 0; --last)
320 // add equation numbers
321 b.pushItem(pit, docstring(), output_active);
323 b.argumentItem(bformat(from_ascii("(%1$s-%2$s)"),
324 numbers_[first], numbers_[last]));
325 for (row_type row = 0; row != nrows(); ++row) {
329 label_[row]->addToToc(pit, output_active, utype, backend);
330 docstring label = nicelabel(row);
332 // this is the only equation
333 b.argumentItem(label);
335 // insert as sub-items
336 b.pushItem(pit, label, output_active);
344 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
346 if (previewState(&cur.bv())) {
350 return InsetMathNest::editXY(cur, x, y);
354 InsetMath::mode_type InsetMathHull::currentMode() const
358 return UNDECIDED_MODE;
360 // definitely math mode ...
380 // FIXME: InsetMathGrid should be changed to let the real column alignment be
381 // given by a virtual method like displayColAlign, because the values produced
382 // by defaultColAlign can be invalidated by lfuns such as add-column. For the
383 // moment the values produced by defaultColAlign are not used, notably because
384 // alignment is not implemented in the LyXHTML output.
385 char InsetMathHull::defaultColAlign(col_type col)
387 return colAlign(type_, col);
391 char InsetMathHull::displayColAlign(idx_type idx) const
395 row_type const r = row(idx);
398 if (r == nrows() - 1)
409 return colAlign(type_, col(idx));
413 return InsetMathGrid::displayColAlign(idx);
417 int InsetMathHull::displayColSpace(col_type col) const
419 return colSpace(type_, col);
423 // FIXME: same comment as for defaultColAlign applies.
424 int InsetMathHull::defaultColSpace(col_type col)
426 return colSpace(type_, col);
430 string InsetMathHull::standardFont() const
436 return "lyxnochange";
443 ColorCode InsetMathHull::standardColor() const
448 return Color_foreground;
456 bool InsetMathHull::previewState(const BufferView *const bv) const
458 if (!editing(bv) && RenderPreview::previewMath()
459 && type_ != hullRegexp)
461 graphics::PreviewImage const * pimage =
462 preview_->getPreviewImage(bv->buffer());
463 return pimage && pimage->image();
470 const int ERROR_FRAME_WIDTH = 2;
472 bool previewTooSmall(Dimension const & dim)
474 return dim.width() <= 10 && dim.height() <= 10;
479 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
481 /* Compute \(above|below)displayskip
482 true value in LaTeX is 10pt plus 2pt minus 5pt (in normal size at 10pt)
483 FIXME: make this dependent of current size? (minor improvement)
484 FIXME: if would be nice if this was not part of the inset, but
485 just increased the row ascent/descent.
486 FIXME: even better would be to handle the short skip case.
488 int const bottom_display_margin = mi.base.inPixels(Length(10, Length::PT));
489 int top_display_margin = bottom_display_margin;
490 // at start of paragraph, add an empty line
492 top_display_margin += theFontMetrics(mi.base.font).maxHeight() + 2;
494 if (previewState(mi.base.bv)) {
495 preview_->metrics(mi, dim);
496 if (previewTooSmall(dim)) {
497 // preview image is too small
498 dim.wid += 2 * ERROR_FRAME_WIDTH;
499 dim.asc += 2 * ERROR_FRAME_WIDTH;
501 // insert a gap in front of the formula
502 // value was hardcoded to 1 pixel
503 dim.wid += mi.base.bv->zoomedPixels(1) ;
505 dim.asc += top_display_margin;
506 dim.des += bottom_display_margin;
513 Changer dummy1 = mi.base.changeFontSet(standardFont());
514 Changer dummy2 = mi.base.font.changeStyle(display() ? DISPLAY_STYLE
517 // let the cells adjust themselves
518 InsetMathGrid::metrics(mi, dim);
521 // Check whether the numbering interferes with the equations
522 if (numberedType()) {
523 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
524 int extra_offset = 0;
525 for (row_type row = 0; row < nrows(); ++row) {
526 rowinfo(row).offset[mi.base.bv] += extra_offset;
529 docstring const nl = nicelabel(row);
531 mathed_string_dim(mi.base.font, nl, dimnl);
532 int const ind = indent(*mi.base.bv);
533 int const x = ind ? ind : (mi.base.textwidth - dim.wid) / 2;
534 // for some reason metrics does not trigger at the
535 // same point as draw, and therefore we use >= instead of >
536 if ((math_number == BufferParams::LEFT && dimnl.wid >= x)
537 || (math_number == BufferParams::RIGHT
538 && dimnl.wid >= mi.base.textwidth - x - dim.wid)) {
539 extra_offset += dimnl.height();
542 dim.des += extra_offset;
547 dim.asc += top_display_margin;
548 dim.des += bottom_display_margin;
551 // reserve some space for marker.
556 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
558 BufferView const * const bv = pi.base.bv;
559 if (previewState(bv)) {
560 Dimension const dim = dimension(*pi.base.bv);
561 if (previewTooSmall(dim))
563 return graphics::PreviewLoader::backgroundColor();
569 void InsetMathHull::drawMarkers(PainterInfo & pi, int x, int y) const
571 ColorCode pen_color = mouseHovered(pi.base.bv) || editing(pi.base.bv)?
572 Color_mathframe : Color_mathcorners;
573 // If the corners have the same color as the background, do not paint them.
574 if (lcolor.getX11HexName(Color_mathbg) == lcolor.getX11HexName(pen_color))
577 Inset::drawMarkers(pi, x, y);
578 Dimension const dim = dimension(*pi.base.bv);
579 int const t = x + dim.width() - 1;
580 int const a = y - dim.ascent();
581 pi.pain.line(x, a + 3, x, a, pen_color);
582 pi.pain.line(t, a + 3, t, a, pen_color);
583 pi.pain.line(x, a, x + 3, a, pen_color);
584 pi.pain.line(t - 3, a, t, a, pen_color);
588 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
590 Dimension const dim = dimension(*pi.base.bv);
591 if (previewTooSmall(dim)) {
592 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
593 dim.wid, dim.asc + dim.des, backgroundColor(pi));
596 // If there are numbers, the margins around the (displayed)
597 // equation have to be cleared.
599 pi.pain.fillRectangle(pi.leftx, y - dim.asc,
600 pi.rightx - pi.leftx, dim.height(), pi.background_color);
601 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
602 dim.asc + dim.des - 1, pi.backgroundColor(this));
606 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
608 BufferView const * const bv = pi.base.bv;
609 Dimension const dim = dimension(*bv);
611 if (type_ == hullRegexp)
612 pi.pain.rectangle(x + 2, y - dim.ascent() + 1,
613 dim.width() - 3, dim.height() - 2, Color_regexpframe);
615 if (previewState(bv)) {
616 // Do not draw change tracking cue if taken care of by RowPainter
618 Changer dummy = !canPaintChange(*bv) ? changeVar(pi.change, Change())
620 if (previewTooSmall(dim)) {
621 // we have an extra frame
622 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
624 // one pixel gap in front
625 // value was hardcoded to 1 pixel
626 int const gap = pi.base.bv->zoomedPixels(1) ;
627 preview_->draw(pi, x + gap, y);
632 // First draw the numbers
633 ColorCode color = pi.selected && lyxrc.use_system_colors
634 ? Color_selectiontext : standardColor();
635 bool const really_change_color = pi.base.font.color() == Color_none;
636 Changer dummy0 = really_change_color ? pi.base.font.changeColor(color)
638 if (numberedType()) {
639 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
640 for (row_type row = 0; row < nrows(); ++row) {
641 int yy = y + rowinfo(row).offset[bv];
642 docstring const nl = nicelabel(row);
644 mathed_string_dim(pi.base.font, nl, dimnl);
645 if (math_number == BufferParams::LEFT) {
646 if (dimnl.wid > x - pi.leftx)
647 yy += rowinfo(row).descent + dimnl.asc;
648 pi.draw(pi.leftx, yy, nl);
650 if (dimnl.wid > pi.rightx - x - dim.wid)
651 yy += rowinfo(row).descent + dimnl.asc;
652 pi.draw(pi.rightx - dimnl.wid, yy, nl);
657 // Then the equations
658 Changer dummy1 = pi.base.changeFontSet(standardFont());
659 Changer dummy2 = pi.base.font.changeStyle(display() ? DISPLAY_STYLE
661 InsetMathGrid::draw(pi, x + 1, y);
662 drawMarkers(pi, x, y);
664 // drawing change line
665 if (canPaintChange(*bv)) {
667 int const display_margin = display() ? pi.base.inPixels(Length(12, Length::PT)) : 0;
668 pi.change.paintCue(pi, x + 1, y + 1 - dim.asc + display_margin,
669 x + dim.wid, y + dim.des - display_margin);
674 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
677 InsetMathGrid::metricsT(mi, dim);
680 otexrowstream ots(os);
681 TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault);
683 dim.wid = os.str().size();
690 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
693 InsetMathGrid::drawT(pain, x, y);
696 otexrowstream ots(os);
697 TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault);
699 pain.draw(x, y, os.str().c_str());
704 static docstring latexString(InsetMathHull const & inset)
707 // This has to be static, because a preview snippet or a math
708 // macro containing math in text mode (such as $\text{$\phi$}$ or
709 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
710 // first time as a whole, and the second time only the inner math.
711 // In this last case inset.buffer() would be invalid.
712 static Encoding const * encoding = 0;
713 if (inset.isBufferValid())
714 encoding = &(inset.buffer().params().encoding());
715 otexrowstream ots(ls);
716 TeXMathStream wi(ots, false, true, TeXMathStream::wsPreview, encoding);
722 void InsetMathHull::initUnicodeMath() const
724 // Trigger classification of the unicode symbols in this inset
725 docstring const dummy = latexString(*this);
729 void InsetMathHull::addPreview(DocIterator const & inset_pos,
730 graphics::PreviewLoader & /*ploader*/) const
732 if (RenderPreview::previewMath()) {
733 preparePreview(inset_pos);
738 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
739 MacroNameSet & macros, MacroNameSet & defs) const
741 MacroNameSet::iterator const end = macros.end();
743 for (size_t i = 0; i < md.size(); ++i) {
744 InsetMathMacro const * mi = md[i].nucleus()->asMacro();
745 InsetMathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
746 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
747 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
748 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
749 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
751 // Look for macros in the arguments of this macro.
752 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
753 usedMacros(mi->cell(idx), pos, macros, defs);
754 // Make sure this is a macro defined in the document
755 // (as we also spot the macros in the symbols file)
756 // or that we have not already accounted for it.
757 docstring const name = mi->name();
758 if (macros.find(name) == end)
761 // Look for macros in the definition of this macro.
762 MathData ar(pos.buffer());
763 MacroData const * data =
764 pos.buffer()->getMacro(name, pos, true);
766 odocstringstream macro_def;
767 data->write(macro_def, true);
769 defs.insert(macro_def.str());
770 asArray(data->definition(), ar);
772 usedMacros(ar, pos, macros, defs);
774 MathData ar(pos.buffer());
775 asArray(mt->definition(), ar);
776 usedMacros(ar, pos, macros, defs);
778 if (!si->nuc().empty())
779 usedMacros(si->nuc(), pos, macros, defs);
781 usedMacros(si->down(), pos, macros, defs);
783 usedMacros(si->up(), pos, macros, defs);
784 } else if (fi || gi) {
785 idx_type nidx = fi ? fi->nargs() : gi->nargs();
786 for (idx_type idx = 0; idx < nidx; ++idx)
787 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
790 usedMacros(ni->cell(0), pos, macros, defs);
796 void InsetMathHull::preparePreview(DocIterator const & pos,
797 bool forexport) const
799 // there is no need to do all the macro stuff if we're not
800 // actually going to generate the preview.
801 if (!RenderPreview::previewMath() && !forexport)
804 Buffer const * buffer = pos.buffer();
806 // collect macros at this position
808 buffer->listMacroNames(macros);
810 // collect definitions only for the macros used in this inset
812 for (idx_type idx = 0; idx < nargs(); ++idx)
813 usedMacros(cell(idx), pos, macros, defs);
815 docstring macro_preamble;
816 for (auto const & defvar : defs)
817 macro_preamble.append(defvar);
819 // set the font series and size for this snippet
820 DocIterator dit = pos.getInnerText();
821 Paragraph const & par = dit.paragraph();
822 Font font = par.getFontSettings(buffer->params(), dit.pos());
823 font.fontInfo().realize(par.layout().font);
824 string const lsize = font.latexSize();
827 if (font.fontInfo().series() == BOLD_SERIES) {
828 setfont += from_ascii("\\textbf{");
831 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
832 setfont += from_ascii("\\" + lsize + '\n');
835 if (forexport && haveNumbers()) {
836 docstring eqstr = from_ascii("equation");
837 CounterMap::const_iterator it = counter_map.find(eqstr);
838 if (it != counter_map.end()) {
839 int num = it->second;
841 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
842 '{' + convert<docstring>(num) + '}' + '\n';
844 for (size_t i = 0; i != numcnts; ++i) {
845 docstring cnt = from_ascii(counters_to_save[i]);
846 it = counter_map.find(cnt);
847 if (it == counter_map.end())
849 int num = it->second;
851 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
852 '{' + convert<docstring>(num) + '}';
855 docstring const snippet = macro_preamble + setfont + setcnt
856 + latexString(*this) + endfont;
857 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
858 preview_->addPreview(snippet, *buffer, forexport);
862 void InsetMathHull::reloadPreview(DocIterator const & pos) const
865 preview_->startLoading(*pos.buffer());
869 void InsetMathHull::loadPreview(DocIterator const & pos) const
871 bool const forexport = true;
872 preparePreview(pos, forexport);
873 preview_->startLoading(*pos.buffer(), forexport);
877 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
879 if (RenderPreview::previewMath()) {
881 cur.screenUpdateFlags(Update::Force);
887 docstring InsetMathHull::label(row_type row) const
889 LASSERT(row < nrows(), return docstring());
890 if (InsetLabel * il = label_[row])
891 return il->screenLabel();
896 void InsetMathHull::label(row_type row, docstring const & label)
898 //lyxerr << "setting label '" << label << "' for row " << row << endl;
902 label_[row] = dummy_pointer;
905 label_[row]->updateLabelAndRefs(label);
907 label_[row]->setParam("name", label);
911 InsetCommandParams p(LABEL_CODE);
913 label_[row] = new InsetLabel(buffer_, p);
915 label_[row]->setBuffer(buffer());
919 void InsetMathHull::numbered(row_type row, Numbered num)
921 numbered_[row] = num;
922 if (!numbered(row) && label_[row]) {
929 bool InsetMathHull::numbered(row_type row) const
931 return numbered_[row] == NUMBER;
935 bool InsetMathHull::ams() const
955 for (auto const & row : numbered_)
962 bool InsetMathHull::outerDisplay() const
985 Inset::RowFlags InsetMathHull::rowFlags() const
1002 if (buffer().params().is_math_indent)
1003 return Display | AlignLeft;
1012 int InsetMathHull::indent(BufferView const & bv) const
1014 // FIXME: set this in the textclass. This value is what the article class uses.
1015 static Length default_indent(2.5, Length::EM);
1016 if (display() && buffer().params().is_math_indent) {
1017 Length const & len = buffer().params().getMathIndent();
1019 return bv.inPixels(default_indent);
1021 return bv.inPixels(len);
1023 return Inset::indent(bv);
1027 bool InsetMathHull::numberedType() const
1046 for (row_type row = 0; row < nrows(); ++row)
1053 void InsetMathHull::validate(LaTeXFeatures & features) const
1055 if (features.runparams().isLaTeX()) {
1057 features.require("amsmath");
1059 if (type_ == hullRegexp) {
1060 features.require("color");
1061 docstring frcol = from_utf8(lcolor.getLaTeXName(Color_regexpframe));
1062 docstring bgcol = from_ascii("white");
1063 features.addPreambleSnippet(
1064 "\\newcommand{\\regexp}[1]{\\fcolorbox{"
1066 + bgcol + "}{\\ensuremath{\\mathtt{#1}}}}");
1067 features.addPreambleSnippet(
1068 from_ascii("\\newcommand{\\endregexp}{}"));
1069 } else if (outerDisplay() && features.inDeletedInset()) {
1070 features.require("tikz");
1071 features.require("ct-tikz-object-sout");
1074 // Validation is necessary only if not using AMS math.
1075 // To be safe, we will always run mathedvalidate.
1076 //if (features.amsstyle)
1079 //features.binom = true;
1080 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
1081 // it would be better to do this elsewhere, but we can't validate in
1082 // InsetMathMatrix and we have no way, outside MathExtern, to know if
1083 // we even have any matrices.
1084 features.addCSSSnippet(
1085 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
1086 "table.matrix td{padding: 0.25px;}\n"
1087 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
1088 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
1090 InsetMathGrid::validate(features);
1094 CtObject InsetMathHull::getCtObject(OutputParams const & runparams) const
1096 CtObject res = CtObject::Normal;
1112 case hullMultline: {
1113 if (runparams.inulemcmd
1114 && (!runparams.local_font || runparams.local_font->fontInfo().strikeout() != FONT_ON))
1115 res = CtObject::UDisplayObject;
1117 res = CtObject::DisplayObject;
1125 void InsetMathHull::header_write(TeXMathStream & os) const
1127 bool n = numberedType();
1138 if (cell(0).empty())
1143 writeMathdisplayPreamble(os);
1147 os << "\\begin{equation" << star(n) << "}\n";
1157 writeMathdisplayPreamble(os);
1160 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1167 os << "\\begin{" << hullName(type_) << star(n) << '}'
1168 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1174 os << "\\begin{" << hullName(type_) << '}'
1175 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1185 os << "\\begin{unknown" << star(n) << "}\n";
1191 void InsetMathHull::footer_write(TeXMathStream & os) const
1193 bool n = numberedType();
1210 os << "\\end{equation" << star(n) << "}\n";
1213 writeMathdisplayPostamble(os);
1223 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1224 writeMathdisplayPostamble(os);
1231 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1237 os << "\\end{" << hullName(type_) << "}\n";
1241 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1242 os << "\\endregexp{}}";
1248 os << "\\end{unknown" << star(n) << "}\n";
1254 bool InsetMathHull::allowsTabularFeatures() const
1277 bool InsetMathHull::rowChangeOK() const
1280 type_ == hullEqnArray || type_ == hullAlign ||
1281 type_ == hullFlAlign || type_ == hullAlignAt ||
1282 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1283 type_ == hullGather || type_ == hullMultline;
1287 bool InsetMathHull::colChangeOK() const
1290 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1291 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1295 void InsetMathHull::addRow(row_type row)
1300 bool numbered = numberedType();
1301 // Move the number and raw pointer, do not call label() (bug 7511)
1302 InsetLabel * label = dummy_pointer;
1303 docstring number = empty_docstring();
1304 if (type_ == hullMultline) {
1305 if (row + 1 == nrows()) {
1306 numbered_[row] = NONUMBER;
1307 swap(label, label_[row]);
1308 swap(number, numbers_[row]);
1313 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1314 numbers_.insert(numbers_.begin() + row + 1, number);
1315 label_.insert(label_.begin() + row + 1, label);
1316 InsetMathGrid::addRow(row);
1320 void InsetMathHull::swapRow(row_type row)
1324 if (row + 1 == nrows())
1326 swap(numbered_[row], numbered_[row + 1]);
1327 swap(numbers_[row], numbers_[row + 1]);
1328 swap(label_[row], label_[row + 1]);
1329 InsetMathGrid::swapRow(row);
1333 void InsetMathHull::delRow(row_type row)
1335 if (nrows() <= 1 || !rowChangeOK())
1337 if (row + 1 == nrows() && type_ == hullMultline) {
1338 swap(numbered_[row - 1], numbered_[row]);
1339 swap(numbers_[row - 1], numbers_[row]);
1340 swap(label_[row - 1], label_[row]);
1341 InsetMathGrid::delRow(row);
1344 InsetMathGrid::delRow(row);
1345 // The last dummy row has no number info nor a label.
1346 // Test nrows() + 1 because we have already erased the row.
1347 if (row == nrows() + 1)
1349 numbered_.erase(numbered_.begin() + row);
1350 numbers_.erase(numbers_.begin() + row);
1352 label_.erase(label_.begin() + row);
1356 void InsetMathHull::addCol(col_type col)
1360 InsetMathGrid::addCol(col);
1364 void InsetMathHull::delCol(col_type col)
1366 if (ncols() <= 1 || !colChangeOK())
1368 InsetMathGrid::delCol(col);
1372 docstring InsetMathHull::nicelabel(row_type row) const
1376 docstring const & val = numbers_[row];
1378 return '(' + val + ')';
1379 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1383 void InsetMathHull::glueall(HullType type)
1386 for (idx_type i = 0; i < nargs(); ++i)
1388 InsetLabel * label = 0;
1389 if (type == hullEquation) {
1390 // preserve first non-empty label
1391 for (row_type row = 0; row < nrows(); ++row) {
1393 label = label_[row];
1399 *this = InsetMathHull(buffer_, hullSimple);
1406 void InsetMathHull::splitTo2Cols()
1408 LASSERT(ncols() == 1, return);
1409 InsetMathGrid::addCol(1);
1410 for (row_type row = 0; row < nrows(); ++row) {
1411 idx_type const i = 2 * row;
1412 pos_type pos = firstRelOp(cell(i));
1413 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1414 cell(i).erase(pos, cell(i).size());
1419 void InsetMathHull::splitTo3Cols()
1421 LASSERT(ncols() < 3, return);
1424 InsetMathGrid::addCol(2);
1425 for (row_type row = 0; row < nrows(); ++row) {
1426 idx_type const i = 3 * row + 1;
1427 if (!cell(i).empty()) {
1428 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1429 cell(i).erase(1, cell(i).size());
1435 void InsetMathHull::changeCols(col_type cols)
1437 if (ncols() == cols)
1439 else if (ncols() < cols) {
1445 while (ncols() < cols)
1446 InsetMathGrid::addCol(ncols());
1452 for (row_type row = 0; row < nrows(); ++row) {
1453 idx_type const i = row * ncols();
1454 for (col_type col = cols; col < ncols(); ++col) {
1455 cell(i + cols - 1).append(cell(i + col));
1459 while (ncols() > cols) {
1460 InsetMathGrid::delCol(ncols() - 1);
1465 HullType InsetMathHull::getType() const
1471 void InsetMathHull::setType(HullType type)
1478 bool InsetMathHull::isMutable(HullType type)
1502 void InsetMathHull::mutate(HullType newtype)
1504 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1506 if (newtype == type_)
1509 // This guards the algorithm below it, which is designed with certain types
1511 if (!isMutable(newtype) || !isMutable(type_)) {
1512 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1513 << "' to '" << to_utf8(hullName(newtype))
1514 << "' not implemented" << endl;
1518 // we try to move along the chain
1519 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1521 // +-------------------------------------+
1522 // we use eqnarray as intermediate type for mutations that are not
1523 // directly supported because it handles labels and numbering for
1528 setType(hullSimple);
1534 if (newtype == hullNone) {
1538 setType(hullEquation);
1539 numbered(0, label_[0] != nullptr);
1548 setType(hullSimple);
1553 // split it "nicely" on the first relop
1555 setType(hullEqnArray);
1563 // split it "nicely"
1598 setType(hullEqnArray);
1607 for (row_type row = 0; row < nrows(); ++row)
1608 numbered(row, false);
1618 for (row_type row = 0; row < nrows(); ++row)
1619 numbered(row, false);
1626 setType(hullEqnArray);
1656 for (row_type row = 0; row < nrows(); ++row)
1657 numbered(row, false);
1661 // first we mutate to EqnArray
1663 setType(hullEqnArray);
1670 // we passed the guard so we should not be here
1671 LYXERR0("Mutation not implemented, but should have been.");
1672 LASSERT(false, return);
1678 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1679 bool last_eoln) const
1682 if (numberedType()) {
1683 if (label_[row] && numbered(row)) {
1684 docstring const name =
1685 latex ? escape(label_[row]->getParam("name"))
1686 : label_[row]->getParam("name");
1687 res += "\\label{" + name + '}';
1689 if (type_ != hullMultline) {
1690 if (numbered_[row] == NONUMBER)
1691 res += "\\nonumber ";
1692 else if (numbered_[row] == NOTAG)
1696 // Never add \\ on the last empty line of eqnarray and friends
1698 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1701 void InsetMathHull::write(TeXMathStream & os) const
1703 ModeSpecifier specifier(os, MATH_MODE);
1705 InsetMathGrid::write(os);
1710 void InsetMathHull::normalize(NormalStream & os) const
1712 os << "[formula " << hullName(type_) << ' ';
1713 InsetMathGrid::normalize(os);
1718 void InsetMathHull::infoize(odocstream & os) const
1720 os << bformat(_("Type: %1$s"), hullName(type_));
1724 void InsetMathHull::check() const
1726 LATTEST(numbered_.size() == nrows());
1727 LATTEST(numbers_.size() == nrows());
1728 LATTEST(label_.size() == nrows());
1732 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1734 //FIXME: sort out whether we want std::string or docstring for those
1735 string const lang = func.getArg(0);
1736 docstring extra = from_utf8(func.getArg(1));
1738 extra = from_ascii("noextra");
1740 // replace selection with result of computation
1741 if (reduceSelectionToOneCell(cur)) {
1743 asArray(grabAndEraseSelection(cur), ar);
1744 lyxerr << "use selection: " << ar << endl;
1745 cur.insert(pipeThroughExtern(lang, extra, ar));
1749 // only inline, display or eqnarray math is allowed
1750 switch (getType()) {
1756 frontend::Alert::warning(_("Bad math environment"),
1757 _("Computation cannot be performed for AMS "
1758 "math environments.\nChange the math "
1759 "formula type and try again."));
1764 eq.push_back(MathAtom(new InsetMathChar('=')));
1766 // go to first item in line
1767 cur.idx() -= cur.idx() % ncols();
1770 if (getType() == hullSimple) {
1771 size_type pos = cur.cell().find_last(eq);
1773 if (pos == cur.cell().size()) {
1775 lyxerr << "use whole cell: " << ar << endl;
1777 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1778 lyxerr << "use partial cell form pos: " << pos << endl;
1780 cur.cell().append(eq);
1781 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1782 cur.pos() = cur.lastpos();
1786 if (getType() == hullEquation) {
1787 lyxerr << "use equation inset" << endl;
1788 mutate(hullEqnArray);
1789 MathData & ar = cur.cell();
1790 lyxerr << "use cell: " << ar << endl;
1794 cur.cell() = pipeThroughExtern(lang, extra, ar);
1795 // move to end of line
1796 cur.pos() = cur.lastpos();
1801 lyxerr << "use eqnarray" << endl;
1802 cur.idx() += 2 - cur.idx() % ncols();
1804 MathData ar = cur.cell();
1805 lyxerr << "use cell: " << ar << endl;
1806 // FIXME: temporarily disabled
1812 cur.cell() = pipeThroughExtern(lang, extra, ar);
1813 cur.pos() = cur.lastpos();
1818 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1820 //lyxerr << "action: " << cmd.action() << endl;
1821 switch (cmd.action()) {
1823 case LFUN_FINISHED_BACKWARD:
1824 case LFUN_FINISHED_FORWARD:
1825 case LFUN_FINISHED_RIGHT:
1826 case LFUN_FINISHED_LEFT:
1827 //lyxerr << "action: " << cmd.action() << endl;
1828 InsetMathGrid::doDispatch(cur, cmd);
1831 case LFUN_PARAGRAPH_BREAK:
1832 // just swallow this
1835 case LFUN_NEWLINE_INSERT:
1836 // some magic for the common case
1837 if (type_ == hullSimple || type_ == hullEquation) {
1838 cur.recordUndoInset();
1840 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1841 mutate(align ? hullAlign : hullEqnArray);
1842 // mutate() may change labels and such.
1843 cur.forceBufferUpdate();
1844 cur.idx() = nrows() * ncols() - 1;
1845 cur.pos() = cur.lastpos();
1847 InsetMathGrid::doDispatch(cur, cmd);
1850 case LFUN_MATH_NUMBER_TOGGLE: {
1851 //lyxerr << "toggling all numbers" << endl;
1852 cur.recordUndoInset();
1853 bool old = numberedType();
1854 if (type_ == hullMultline)
1855 numbered(nrows() - 1, !old);
1857 for (row_type row = 0; row < nrows(); ++row)
1858 numbered(row, !old);
1860 cur.message(old ? _("No number") : _("Number"));
1861 cur.forceBufferUpdate();
1865 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1866 cur.recordUndoInset();
1867 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1868 bool old = numbered(r);
1869 cur.message(old ? _("No number") : _("Number"));
1871 cur.forceBufferUpdate();
1875 case LFUN_LABEL_INSERT: {
1876 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1877 docstring old_label = label(r);
1878 docstring const default_label = from_ascii("eq:");
1879 if (old_label.empty())
1880 old_label = default_label;
1882 InsetCommandParams p(LABEL_CODE);
1883 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1884 string const data = InsetCommand::params2string(p);
1886 if (cmd.argument().empty())
1887 cur.bv().showDialog("label", data);
1889 FuncRequest fr(LFUN_INSET_INSERT, data);
1895 case LFUN_LABEL_COPY_AS_REFERENCE: {
1897 if (cmd.argument().empty() && &cur.inset() == this)
1898 // if there is no argument and we're inside math, we retrieve
1899 // the row number from the cursor position.
1900 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1902 // if there is an argument, find the corresponding label, else
1903 // check whether there is at least one label.
1904 for (row = 0; row != nrows(); ++row)
1905 if (numbered(row) && label_[row]
1906 && (cmd.argument().empty() || label(row) == cmd.argument()))
1913 InsetCommandParams p(REF_CODE, "ref");
1914 p["reference"] = label(row);
1915 cap::clearSelection();
1916 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1920 case LFUN_WORD_DELETE_FORWARD:
1921 case LFUN_CHAR_DELETE_FORWARD:
1922 if (col(cur.idx()) + 1 == ncols()
1923 && cur.pos() == cur.lastpos()
1924 && !cur.selection()) {
1925 if (!label(row(cur.idx())).empty()) {
1926 cur.recordUndoInset();
1927 label(row(cur.idx()), docstring());
1928 } else if (numbered(row(cur.idx()))) {
1929 cur.recordUndoInset();
1930 numbered(row(cur.idx()), false);
1931 cur.forceBufferUpdate();
1933 InsetMathGrid::doDispatch(cur, cmd);
1937 InsetMathGrid::doDispatch(cur, cmd);
1942 case LFUN_INSET_INSERT: {
1943 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1944 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1945 string const name = cmd.getArg(0);
1946 if (name == "label") {
1947 InsetCommandParams p(LABEL_CODE);
1948 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1949 docstring str = p["name"];
1950 cur.recordUndoInset();
1951 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1955 docstring old = label(r);
1958 // The label will take care of the reference update.
1962 // Newly created inset so initialize it.
1963 label_[r]->initView();
1966 cur.forceBufferUpdate();
1969 InsetMathGrid::doDispatch(cur, cmd);
1973 case LFUN_MATH_EXTERN:
1974 cur.recordUndoInset();
1978 case LFUN_MATH_MUTATE: {
1979 cur.recordUndoInset();
1980 row_type row = cur.row();
1981 col_type col = cur.col();
1982 mutate(hullType(cmd.argument()));
1983 cur.idx() = row * ncols() + col;
1984 if (cur.idx() > cur.lastidx()) {
1985 cur.idx() = cur.lastidx();
1986 cur.pos() = cur.lastpos();
1988 if (cur.pos() > cur.lastpos())
1989 cur.pos() = cur.lastpos();
1991 cur.forceBufferUpdate();
1992 // FIXME: find some more clever handling of the selection,
1993 // i.e. preserve it.
1994 cur.clearSelection();
1995 //cur.dispatched(FINISHED);
1999 case LFUN_MATH_DISPLAY: {
2000 cur.recordUndoInset();
2001 mutate(type_ == hullSimple ? hullEquation : hullSimple);
2002 // if the cursor is in a cell that got merged, move it to
2003 // start of the hull inset.
2004 if (cur.idx() > 0) {
2008 if (cur.pos() > cur.lastpos())
2009 cur.pos() = cur.lastpos();
2014 case LFUN_TABULAR_FEATURE:
2015 if (!allowsTabularFeatures())
2018 InsetMathGrid::doDispatch(cur, cmd);
2022 InsetMathGrid::doDispatch(cur, cmd);
2030 bool allowDisplayMath(Cursor const & cur)
2032 LATTEST(cur.depth() > 1);
2033 Cursor tmpcur = cur;
2036 FuncRequest cmd(LFUN_MATH_DISPLAY);
2037 return tmpcur.getStatus(cmd, status) && status.enabled();
2043 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
2044 FuncStatus & status) const
2046 switch (cmd.action()) {
2047 case LFUN_FINISHED_BACKWARD:
2048 case LFUN_FINISHED_FORWARD:
2049 case LFUN_FINISHED_RIGHT:
2050 case LFUN_FINISHED_LEFT:
2053 case LFUN_NEWLINE_INSERT:
2054 case LFUN_MATH_EXTERN:
2056 status.setEnabled(true);
2059 // we never allow this in math, and we want to bind enter
2060 // to another actions in command-alternatives
2061 case LFUN_PARAGRAPH_BREAK:
2062 status.setEnabled(false);
2064 case LFUN_MATH_MUTATE: {
2065 HullType const ht = hullType(cmd.argument());
2066 status.setOnOff(type_ == ht);
2067 status.setEnabled(isMutable(ht) && isMutable(type_));
2069 if (ht != hullSimple && status.enabled())
2070 status.setEnabled(allowDisplayMath(cur));
2073 case LFUN_MATH_DISPLAY: {
2074 status.setEnabled(display() || allowDisplayMath(cur));
2075 status.setOnOff(display());
2079 case LFUN_MATH_NUMBER_TOGGLE:
2080 // FIXME: what is the right test, this or the one of
2082 status.setEnabled(display());
2083 status.setOnOff(numberedType());
2086 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
2087 // FIXME: what is the right test, this or the one of
2089 bool const enable = (type_ == hullMultline)
2090 ? (nrows() - 1 == cur.row())
2092 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2093 status.setEnabled(enable);
2094 status.setOnOff(enable && numbered(r));
2098 case LFUN_LABEL_INSERT:
2099 status.setEnabled(type_ != hullSimple);
2102 case LFUN_LABEL_COPY_AS_REFERENCE: {
2103 bool enabled = false;
2104 if (cmd.argument().empty() && &cur.inset() == this) {
2105 // if there is no argument and we're inside math, we retrieve
2106 // the row number from the cursor position.
2107 row_type row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2108 enabled = numberedType() && label_[row] && numbered(row);
2110 // if there is an argument, find the corresponding label, else
2111 // check whether there is at least one label.
2112 for (row_type row = 0; row != nrows(); ++row) {
2113 if (numbered(row) && label_[row] &&
2114 (cmd.argument().empty() || label(row) == cmd.argument())) {
2120 status.setEnabled(enabled);
2124 case LFUN_INSET_INSERT:
2125 if (cmd.getArg(0) == "label") {
2126 status.setEnabled(type_ != hullSimple);
2129 return InsetMathGrid::getStatus(cur, cmd, status);
2131 case LFUN_TABULAR_FEATURE: {
2132 if (!allowsTabularFeatures())
2134 string s = cmd.getArg(0);
2136 && (s == "append-row"
2137 || s == "delete-row"
2138 || s == "copy-row")) {
2139 status.message(bformat(
2140 from_utf8(N_("Can't change number of rows in '%1$s'")),
2142 status.setEnabled(false);
2146 && (s == "append-column"
2147 || s == "delete-column"
2148 || s == "copy-column")) {
2149 status.message(bformat(
2150 from_utf8(N_("Can't change number of columns in '%1$s'")),
2152 status.setEnabled(false);
2155 if (s == "add-vline-left" || s == "add-vline-right") {
2156 status.message(bformat(
2157 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2159 status.setEnabled(false);
2162 if (s == "valign-top" || s == "valign-middle"
2163 || s == "valign-bottom" || s == "align-left"
2164 || s == "align-center" || s == "align-right") {
2165 status.setEnabled(false);
2168 return InsetMathGrid::getStatus(cur, cmd, status);
2172 return InsetMathGrid::getStatus(cur, cmd, status);
2177 int InsetMathHull::leftMargin() const
2179 return (getType() == hullSimple) ? 0 : InsetMathGrid::leftMargin();
2183 int InsetMathHull::rightMargin() const
2185 return (getType() == hullSimple) ? 0 : InsetMathGrid::rightMargin();
2189 int InsetMathHull::border() const
2191 return (getType() == hullSimple) ? 0 : InsetMathGrid::border();
2195 /////////////////////////////////////////////////////////////////////
2199 // simply scrap this function if you want
2200 void InsetMathHull::mutateToText()
2203 // translate to latex
2205 latex(os, false, false);
2206 string str = os.str();
2209 Text * lt = view_->cursor().innerText();
2210 string::const_iterator cit = str.begin();
2211 string::const_iterator end = str.end();
2212 for (; cit != end; ++cit)
2213 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2216 //dispatch(LFUN_ESCAPE);
2221 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2222 docstring const & font)
2224 // this whole function is a hack and won't work for incremental font
2227 if (cur.inset().asInsetMath()->name() == font)
2228 cur.handleFont(to_utf8(font));
2230 cur.handleNest(createInsetMath(font, cur.buffer()));
2236 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2241 font.fromString(to_utf8(arg), b);
2242 if (font.fontInfo().color() != Color_inherit) {
2243 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2249 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2251 InsetMathNest::edit(cur, front, entry_from);
2252 // The inset formula dimension is not necessarily the same as the
2253 // one of the instant preview image, so we have to indicate to the
2254 // BufferView that a metrics update is needed.
2255 cur.screenUpdateFlags(Update::Force);
2259 /////////////////////////////////////////////////////////////////////
2263 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2266 // FIXME: completely broken
2267 static InsetMathHull * lastformula = 0;
2268 static CursorBase current = DocIterator(ibegin(nucleus()));
2270 static string laststr;
2272 if (lastformula != this || laststr != str) {
2273 //lyxerr << "reset lastformula to " << this << endl;
2276 current = ibegin(nucleus());
2278 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2282 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2284 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2285 CursorSlice & top = it.back();
2286 MathData const & a = top.asInsetMath()->cell(top.idx_);
2287 if (a.matchpart(ar, top.pos_)) {
2288 bv->cursor().setSelection(it, ar.size());
2290 top.pos_ += ar.size();
2296 //lyxerr << "not found!" << endl;
2303 void InsetMathHull::write(ostream & os) const
2305 odocstringstream oss;
2306 otexrowstream ots(oss);
2307 TeXMathStream wi(ots, false, false, TeXMathStream::wsDefault);
2310 os << to_utf8(oss.str());
2314 void InsetMathHull::read(Lexer & lex)
2317 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2318 operator=(*at->asHullInset());
2322 bool InsetMathHull::readQuiet(Lexer & lex)
2325 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2327 operator=(*at->asHullInset());
2332 int InsetMathHull::plaintext(odocstringstream & os,
2333 OutputParams const & op, size_t max_length) const
2335 // Try enabling this now that there is a flag as requested at #2275.
2336 if (buffer().isExporting() && display()) {
2340 TextPainter tpain(dim.width(), dim.height());
2341 drawT(tpain, 0, dim.ascent());
2343 // reset metrics cache to "real" values
2345 return tpain.textheight();
2348 odocstringstream oss;
2349 otexrowstream ots(oss);
2350 Encoding const * const enc = encodings.fromLyXName("utf8");
2351 TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault, enc);
2354 if (type_ == hullRegexp)
2357 for (row_type r = 0; r < nrows(); ++r) {
2358 for (col_type c = 0; c < ncols(); ++c)
2359 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2360 // if it's for the TOC, we write just the first line
2361 // and do not include the newline.
2362 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2364 if (r < nrows() - 1)
2368 docstring const str = oss.str();
2374 void InsetMathHull::docbook(XMLStream & xs, OutputParams const & runparams) const
2376 // Choose the tag around the MathML equation.
2379 if (getType() == hullSimple)
2380 name = from_ascii("inlineequation");
2382 doCR = true; // This is a block equation, always have <informalequation> on its own line.
2383 name = from_ascii("informalequation");
2386 // DocBook also has <equation>, but it comes with a title.
2387 // TODO: recognise \tag from amsmath? This would allow having <equation> with a proper title.
2390 for (row_type i = 0; i < nrows(); ++i) {
2391 if (!label(i).empty()) {
2392 attr = "xml:id=\"" + xml::cleanID(label(i)) + "\"";
2398 if (!xs.isLastTagCR())
2401 xs << xml::StartTag(name, attr);
2404 // With DocBook 5, MathML must be within its own namespace; defined in Buffer.cpp::writeDocBookSource as "m".
2405 // Output everything in a separate stream so that this does not interfere with the standard flow of DocBook tags.
2406 odocstringstream osmath;
2407 MathMLStream ms(osmath, "m", true);
2409 // Output the MathML subtree.
2410 odocstringstream ls;
2413 // TeX transcription. Avoid MTag/ETag so that there are no extraneous spaces.
2414 ms << "<" << from_ascii("alt") << " role='tex'" << ">";
2415 // Workaround for db2latex: db2latex always includes equations with
2416 // \ensuremath{} or \begin{display}\end{display}
2417 // so we strip LyX' math environment
2418 TeXMathStream wi(ols, false, false, TeXMathStream::wsDefault, runparams.encoding);
2419 InsetMathGrid::write(wi);
2420 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2421 ms << "</" << from_ascii("alt") << ">";
2423 // Actual transformation of the formula into MathML. This translation may fail (for example, due to custom macros).
2424 // The new output stream is required to deal with the errors: first write completely the formula into this
2425 // temporary stream; then, if it is possible without error, then copy it back to the "real" stream. Otherwise,
2426 // some incomplete tags might be put into the real stream.
2428 // First, generate the MathML expression.
2429 odocstringstream ostmp;
2430 MathMLStream mstmp(ostmp, ms.xmlns(), ms.xmlMode());
2431 InsetMathGrid::mathmlize(mstmp);
2433 // Then, output it (but only if the generation can be done without errors!).
2436 osmath << ostmp.str(); // osmath is not a XMLStream, so no need for XMLStream::ESCAPE_NONE.
2438 } catch (MathExportException const &) {
2440 osmath << "<mathphrase>MathML export failed. Please report this as a bug.</mathphrase>";
2443 // Output the complete formula to the DocBook stream.
2444 xs << XMLStream::ESCAPE_NONE << osmath.str();
2446 xs << xml::EndTag(name);
2452 bool InsetMathHull::haveNumbers() const
2454 bool havenumbers = false;
2455 // inline formulas are never numbered (bug 7351 part 3)
2456 if (getType() == hullSimple)
2458 for (size_t i = 0; i != numbered_.size(); ++i) {
2469 // We need to do something about alignment here.
2471 // This duplicates code from InsetMathGrid, but
2472 // we need access here to number information,
2473 // and we simply do not have that in InsetMathGrid.
2474 void InsetMathHull::htmlize(HtmlStream & os) const
2476 bool const havenumbers = haveNumbers();
2477 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2480 os << cell(index(0, 0));
2484 os << MTag("table", "class='mathtable'");
2485 for (row_type row = 0; row < nrows(); ++row) {
2487 for (col_type col = 0; col < ncols(); ++col) {
2489 os << cell(index(row, col));
2494 docstring const & num = numbers_[row];
2496 os << '(' << num << ')';
2501 os << ETag("table");
2505 // this duplicates code from InsetMathGrid, but
2506 // we need access here to number information,
2507 // and we simply do not have that in InsetMathGrid.
2508 void InsetMathHull::mathmlize(MathMLStream & ms) const
2510 bool const havenumbers = haveNumbers();
2511 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2514 ms << MTag("mtable");
2515 char const * const celltag = havetable ? "mtd" : "mrow";
2516 // FIXME There does not seem to be wide support at the moment
2517 // for mlabeledtr, so we have to use just mtr for now.
2518 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2519 char const * const rowtag = "mtr";
2520 for (row_type row = 0; row < nrows(); ++row) {
2523 for (col_type col = 0; col < ncols(); ++col) {
2525 << cell(index(row, col))
2531 docstring const & num = numbers_[row];
2533 ms << '(' << num << ')';
2540 ms << ETag("mtable");
2544 void InsetMathHull::mathAsLatex(TeXMathStream & os) const
2546 MathEnsurer ensurer(os, false);
2547 bool havenumbers = haveNumbers();
2548 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2551 os << cell(index(0, 0));
2555 os << "<table class='mathtable'>";
2556 for (row_type row = 0; row < nrows(); ++row) {
2558 for (col_type col = 0; col < ncols(); ++col) {
2559 os << "<td class='math'>";
2560 os << cell(index(row, col));
2565 docstring const & num = numbers_[row];
2567 os << '(' << num << ')';
2576 docstring InsetMathHull::xhtml(XMLStream & xs, OutputParams const & op) const
2578 BufferParams::MathOutput const mathtype =
2579 buffer().masterBuffer()->params().html_math_output;
2581 bool success = false;
2583 // we output all the labels just at the beginning of the equation.
2584 // this should be fine.
2585 for (size_t i = 0; i != label_.size(); ++i) {
2586 InsetLabel const * const il = label_[i];
2592 // FIXME Eventually we would like to do this inset by inset.
2593 if (mathtype == BufferParams::MathML) {
2594 odocstringstream os;
2595 MathMLStream ms(os);
2599 } catch (MathExportException const &) {}
2601 if (getType() == hullSimple)
2602 xs << xml::StartTag("math",
2603 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2605 xs << xml::StartTag("math",
2606 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2607 xs << XMLStream::ESCAPE_NONE
2609 << xml::EndTag("math");
2611 } else if (mathtype == BufferParams::HTML) {
2612 odocstringstream os;
2617 } catch (MathExportException const &) {}
2619 string const tag = (getType() == hullSimple) ? "span" : "div";
2620 xs << xml::StartTag(tag, "class='formula'", true)
2621 << XMLStream::ESCAPE_NONE
2623 << xml::EndTag(tag);
2627 // what we actually want is this:
2629 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2631 // || mathtype == BufferParams::Images
2633 // but what follows is equivalent, since we'll enter only if either (a) we
2634 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2635 // aren't doing LaTeX.
2637 // so this is for Images.
2638 if (!success && mathtype != BufferParams::LaTeX) {
2639 graphics::PreviewImage const * pimage = 0;
2641 loadPreview(docit_);
2642 pimage = preview_->getPreviewImage(buffer());
2643 // FIXME Do we always have png?
2646 if (pimage || op.dryrun) {
2647 string const filename = pimage ? pimage->filename().onlyFileName()
2648 : "previewimage.png";
2650 // if we are not in the master buffer, then we need to see that the
2651 // generated image is copied there; otherwise, preview fails.
2652 Buffer const * mbuf = buffer().masterBuffer();
2653 if (mbuf != &buffer()) {
2654 string mbtmp = mbuf->temppath();
2655 FileName const mbufimg(support::addName(mbtmp, filename));
2656 pimage->filename().copyTo(mbufimg);
2658 // add the file to the list of files to be exported
2659 op.exportdata->addExternalFile("xhtml", pimage->filename());
2662 string const tag = (getType() == hullSimple) ? "span" : "div";
2664 << xml::StartTag(tag, "style = \"text-align: center;\"")
2665 << xml::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2672 // so we'll pass this test if we've failed everything else, or
2673 // if mathtype was LaTeX, since we won't have entered any of the
2675 if (!success /* || mathtype != BufferParams::LaTeX */) {
2676 // Unfortunately, we cannot use latexString() because we do not want
2677 // $...$ or whatever.
2678 odocstringstream ls;
2679 otexrowstream ots(ls);
2680 TeXMathStream wi(ots, false, true, TeXMathStream::wsPreview);
2681 ModeSpecifier specifier(wi, MATH_MODE);
2683 docstring const latex = ls.str();
2685 // class='math' allows for use of jsMath
2686 // http://www.math.union.edu/~dpvc/jsMath/
2688 // probably should allow for some kind of customization here
2689 string const tag = (getType() == hullSimple) ? "span" : "div";
2690 xs << xml::StartTag(tag, "class='math'")
2699 void InsetMathHull::toString(odocstream & os) const
2701 odocstringstream ods;
2702 plaintext(ods, OutputParams(0));
2707 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2709 odocstringstream ods;
2712 // FIXME: this results in spilling TeX into the LyXHTML output since the
2713 // outliner is used to generate the LyXHTML list of figures/etc.
2719 string InsetMathHull::contextMenuName() const
2721 return "context-math";
2725 void InsetMathHull::recordLocation(DocIterator const & di)
2731 bool InsetMathHull::canPaintChange(BufferView const &) const
2733 // We let RowPainter do it seamlessly for inline insets