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 We use the 'mean' value (12 + 5) / 2 = 8.5pt.
484 FIXME: make this dependent of current size? (minor improvement)
485 FIXME: if would be nice if this was not part of the inset, but
486 just increased the row ascent/descent.
487 FIXME: even better would be to handle the short skip case.
489 int const bottom_display_margin = mi.base.inPixels(Length(8.5, Length::PT));
490 int top_display_margin = bottom_display_margin;
491 // at start of paragraph, add an empty line
493 top_display_margin += theFontMetrics(mi.base.font).maxHeight() + 2;
495 if (previewState(mi.base.bv)) {
496 preview_->metrics(mi, dim);
497 if (previewTooSmall(dim)) {
498 // preview image is too small
499 dim.wid += 2 * ERROR_FRAME_WIDTH;
500 dim.asc += 2 * ERROR_FRAME_WIDTH;
502 // insert a gap in front of the formula
503 // value was hardcoded to 1 pixel
504 dim.wid += mi.base.bv->zoomedPixels(1) ;
506 dim.asc += top_display_margin;
507 dim.des += bottom_display_margin;
514 Changer dummy1 = mi.base.changeFontSet(standardFont());
515 Changer dummy2 = mi.base.font.changeStyle(display() ? DISPLAY_STYLE
518 // let the cells adjust themselves
519 InsetMathGrid::metrics(mi, dim);
522 // Check whether the numbering interferes with the equations
523 if (numberedType()) {
524 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
525 int extra_offset = 0;
526 for (row_type row = 0; row < nrows(); ++row) {
527 rowinfo(row).offset[mi.base.bv] += extra_offset;
530 docstring const nl = nicelabel(row);
532 mathed_string_dim(mi.base.font, nl, dimnl);
533 int const ind = indent(*mi.base.bv);
534 int const x = ind ? ind : (mi.base.textwidth - dim.wid) / 2;
535 // for some reason metrics does not trigger at the
536 // same point as draw, and therefore we use >= instead of >
537 if ((math_number == BufferParams::LEFT && dimnl.wid >= x)
538 || (math_number == BufferParams::RIGHT
539 && dimnl.wid >= mi.base.textwidth - x - dim.wid)) {
540 extra_offset += dimnl.height();
543 dim.des += extra_offset;
548 dim.asc += top_display_margin;
549 dim.des += bottom_display_margin;
552 // reserve some space for marker.
557 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
559 BufferView const * const bv = pi.base.bv;
560 if (previewState(bv)) {
561 Dimension const dim = dimension(*pi.base.bv);
562 if (previewTooSmall(dim))
564 return graphics::PreviewLoader::backgroundColor();
570 void InsetMathHull::drawMarkers(PainterInfo & pi, int x, int y) const
572 ColorCode pen_color = mouseHovered(pi.base.bv) || editing(pi.base.bv)?
573 Color_mathframe : Color_mathcorners;
574 // If the corners have the same color as the background, do not paint them.
575 if (lcolor.getX11HexName(Color_mathbg) == lcolor.getX11HexName(pen_color))
578 Inset::drawMarkers(pi, x, y);
579 Dimension const dim = dimension(*pi.base.bv);
580 int const t = x + dim.width() - 1;
581 int const a = y - dim.ascent();
582 pi.pain.line(x, a + 3, x, a, pen_color);
583 pi.pain.line(t, a + 3, t, a, pen_color);
584 pi.pain.line(x, a, x + 3, a, pen_color);
585 pi.pain.line(t - 3, a, t, a, pen_color);
589 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
591 Dimension const dim = dimension(*pi.base.bv);
592 if (previewTooSmall(dim)) {
593 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
594 dim.wid, dim.asc + dim.des, backgroundColor(pi));
597 // If there are numbers, the margins around the (displayed)
598 // equation have to be cleared.
600 pi.pain.fillRectangle(pi.leftx, y - dim.asc,
601 pi.rightx - pi.leftx, dim.height(), pi.background_color);
602 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
603 dim.asc + dim.des - 1, pi.backgroundColor(this));
607 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
609 BufferView const * const bv = pi.base.bv;
610 Dimension const dim = dimension(*bv);
612 if (type_ == hullRegexp)
613 pi.pain.rectangle(x + 2, y - dim.ascent() + 1,
614 dim.width() - 3, dim.height() - 2, Color_regexpframe);
616 if (previewState(bv)) {
617 // Do not draw change tracking cue if taken care of by RowPainter
619 Changer dummy = !canPaintChange(*bv) ? changeVar(pi.change, Change())
621 if (previewTooSmall(dim)) {
622 // we have an extra frame
623 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
625 // one pixel gap in front
626 // value was hardcoded to 1 pixel
627 int const gap = pi.base.bv->zoomedPixels(1) ;
628 preview_->draw(pi, x + gap, y);
633 // First draw the numbers
634 ColorCode color = pi.selected && lyxrc.use_system_colors
635 ? Color_selectiontext : standardColor();
636 bool const really_change_color = pi.base.font.color() == Color_none;
637 Changer dummy0 = really_change_color ? pi.base.font.changeColor(color)
639 if (numberedType()) {
640 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
641 for (row_type row = 0; row < nrows(); ++row) {
642 int yy = y + rowinfo(row).offset[bv];
643 docstring const nl = nicelabel(row);
645 mathed_string_dim(pi.base.font, nl, dimnl);
646 if (math_number == BufferParams::LEFT) {
647 if (dimnl.wid > x - pi.leftx)
648 yy += rowinfo(row).descent + dimnl.asc;
649 pi.draw(pi.leftx, yy, nl);
651 if (dimnl.wid > pi.rightx - x - dim.wid)
652 yy += rowinfo(row).descent + dimnl.asc;
653 pi.draw(pi.rightx - dimnl.wid, yy, nl);
658 // Then the equations
659 Changer dummy1 = pi.base.changeFontSet(standardFont());
660 Changer dummy2 = pi.base.font.changeStyle(display() ? DISPLAY_STYLE
662 InsetMathGrid::draw(pi, x + 1, y);
663 drawMarkers(pi, x, y);
665 // drawing change line
666 if (canPaintChange(*bv)) {
668 int const display_margin = display() ? pi.base.inPixels(Length(12, Length::PT)) : 0;
669 pi.change.paintCue(pi, x + 1, y + 1 - dim.asc + display_margin,
670 x + dim.wid, y + dim.des - display_margin);
675 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
678 InsetMathGrid::metricsT(mi, dim);
681 otexrowstream ots(os);
682 TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault);
684 dim.wid = os.str().size();
691 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
694 InsetMathGrid::drawT(pain, x, y);
697 otexrowstream ots(os);
698 TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault);
700 pain.draw(x, y, os.str().c_str());
705 static docstring latexString(InsetMathHull const & inset)
708 // This has to be static, because a preview snippet or a math
709 // macro containing math in text mode (such as $\text{$\phi$}$ or
710 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
711 // first time as a whole, and the second time only the inner math.
712 // In this last case inset.buffer() would be invalid.
713 static Encoding const * encoding = 0;
714 if (inset.isBufferValid())
715 encoding = &(inset.buffer().params().encoding());
716 otexrowstream ots(ls);
717 TeXMathStream wi(ots, false, true, TeXMathStream::wsPreview, encoding);
723 void InsetMathHull::initUnicodeMath() const
725 // Trigger classification of the unicode symbols in this inset
726 docstring const dummy = latexString(*this);
730 void InsetMathHull::addPreview(DocIterator const & inset_pos,
731 graphics::PreviewLoader & /*ploader*/) const
733 if (RenderPreview::previewMath()) {
734 preparePreview(inset_pos);
739 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
740 MacroNameSet & macros, MacroNameSet & defs) const
742 MacroNameSet::iterator const end = macros.end();
744 for (size_t i = 0; i < md.size(); ++i) {
745 InsetMathMacro const * mi = md[i].nucleus()->asMacro();
746 InsetMathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
747 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
748 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
749 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
750 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
752 // Look for macros in the arguments of this macro.
753 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
754 usedMacros(mi->cell(idx), pos, macros, defs);
755 // Make sure this is a macro defined in the document
756 // (as we also spot the macros in the symbols file)
757 // or that we have not already accounted for it.
758 docstring const name = mi->name();
759 if (macros.find(name) == end)
762 // Look for macros in the definition of this macro.
763 MathData ar(pos.buffer());
764 MacroData const * data =
765 pos.buffer()->getMacro(name, pos, true);
767 odocstringstream macro_def;
768 data->write(macro_def, true);
770 defs.insert(macro_def.str());
771 asArray(data->definition(), ar);
773 usedMacros(ar, pos, macros, defs);
775 MathData ar(pos.buffer());
776 asArray(mt->definition(), ar);
777 usedMacros(ar, pos, macros, defs);
779 if (!si->nuc().empty())
780 usedMacros(si->nuc(), pos, macros, defs);
782 usedMacros(si->down(), pos, macros, defs);
784 usedMacros(si->up(), pos, macros, defs);
785 } else if (fi || gi) {
786 idx_type nidx = fi ? fi->nargs() : gi->nargs();
787 for (idx_type idx = 0; idx < nidx; ++idx)
788 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
791 usedMacros(ni->cell(0), pos, macros, defs);
797 void InsetMathHull::preparePreview(DocIterator const & pos,
798 bool forexport) const
800 // there is no need to do all the macro stuff if we're not
801 // actually going to generate the preview.
802 if (!RenderPreview::previewMath() && !forexport)
805 Buffer const * buffer = pos.buffer();
807 // collect macros at this position
809 buffer->listMacroNames(macros);
811 // collect definitions only for the macros used in this inset
813 for (idx_type idx = 0; idx < nargs(); ++idx)
814 usedMacros(cell(idx), pos, macros, defs);
816 docstring macro_preamble;
817 for (auto const & defvar : defs)
818 macro_preamble.append(defvar);
820 // set the font series and size for this snippet
821 DocIterator dit = pos.getInnerText();
822 Paragraph const & par = dit.paragraph();
823 Font font = par.getFontSettings(buffer->params(), dit.pos());
824 font.fontInfo().realize(par.layout().font);
825 string const lsize = font.latexSize();
828 if (font.fontInfo().series() == BOLD_SERIES) {
829 setfont += from_ascii("\\textbf{");
832 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
833 setfont += from_ascii("\\" + lsize + '\n');
836 if (forexport && haveNumbers()) {
837 docstring eqstr = from_ascii("equation");
838 CounterMap::const_iterator it = counter_map.find(eqstr);
839 if (it != counter_map.end()) {
840 int num = it->second;
842 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
843 '{' + convert<docstring>(num) + '}' + '\n';
845 for (size_t i = 0; i != numcnts; ++i) {
846 docstring cnt = from_ascii(counters_to_save[i]);
847 it = counter_map.find(cnt);
848 if (it == counter_map.end())
850 int num = it->second;
852 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
853 '{' + convert<docstring>(num) + '}';
856 docstring const snippet = macro_preamble + setfont + setcnt
857 + latexString(*this) + endfont;
858 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
859 preview_->addPreview(snippet, *buffer, forexport);
863 void InsetMathHull::reloadPreview(DocIterator const & pos) const
866 preview_->startLoading(*pos.buffer());
870 void InsetMathHull::loadPreview(DocIterator const & pos) const
872 bool const forexport = true;
873 preparePreview(pos, forexport);
874 preview_->startLoading(*pos.buffer(), forexport);
878 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
880 if (RenderPreview::previewMath()) {
882 cur.screenUpdateFlags(Update::Force);
888 docstring InsetMathHull::label(row_type row) const
890 LASSERT(row < nrows(), return docstring());
891 if (InsetLabel * il = label_[row])
892 return il->screenLabel();
897 void InsetMathHull::label(row_type row, docstring const & label)
899 //lyxerr << "setting label '" << label << "' for row " << row << endl;
903 label_[row] = dummy_pointer;
906 label_[row]->updateLabelAndRefs(label);
908 label_[row]->setParam("name", label);
912 InsetCommandParams p(LABEL_CODE);
914 label_[row] = new InsetLabel(buffer_, p);
916 label_[row]->setBuffer(buffer());
920 void InsetMathHull::numbered(row_type row, Numbered num)
922 numbered_[row] = num;
923 if (!numbered(row) && label_[row]) {
930 bool InsetMathHull::numbered(row_type row) const
932 return numbered_[row] == NUMBER;
936 bool InsetMathHull::ams() const
956 for (auto const & row : numbered_)
963 bool InsetMathHull::outerDisplay() const
986 Inset::RowFlags InsetMathHull::rowFlags() const
1003 if (buffer().params().is_math_indent)
1004 return Display | AlignLeft;
1013 int InsetMathHull::indent(BufferView const & bv) const
1015 // FIXME: set this in the textclass. This value is what the article class uses.
1016 static Length default_indent(2.5, Length::EM);
1017 if (display() && buffer().params().is_math_indent) {
1018 Length const & len = buffer().params().getMathIndent();
1020 return bv.inPixels(default_indent);
1022 return bv.inPixels(len);
1024 return Inset::indent(bv);
1028 bool InsetMathHull::numberedType() const
1047 for (row_type row = 0; row < nrows(); ++row)
1054 void InsetMathHull::validate(LaTeXFeatures & features) const
1056 if (features.runparams().isLaTeX()) {
1058 features.require("amsmath");
1060 if (type_ == hullRegexp) {
1061 features.require("color");
1062 docstring frcol = from_utf8(lcolor.getLaTeXName(Color_regexpframe));
1063 docstring bgcol = from_ascii("white");
1064 features.addPreambleSnippet(
1065 "\\newcommand{\\regexp}[1]{\\fcolorbox{"
1067 + bgcol + "}{\\ensuremath{\\mathtt{#1}}}}");
1068 features.addPreambleSnippet(
1069 from_ascii("\\newcommand{\\endregexp}{}"));
1070 } else if (outerDisplay() && features.inDeletedInset()) {
1071 features.require("tikz");
1072 features.require("ct-tikz-object-sout");
1075 // Validation is necessary only if not using AMS math.
1076 // To be safe, we will always run mathedvalidate.
1077 //if (features.amsstyle)
1080 //features.binom = true;
1081 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
1082 // it would be better to do this elsewhere, but we can't validate in
1083 // InsetMathMatrix and we have no way, outside MathExtern, to know if
1084 // we even have any matrices.
1085 features.addCSSSnippet(
1086 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
1087 "table.matrix td{padding: 0.25px;}\n"
1088 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
1089 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
1091 InsetMathGrid::validate(features);
1095 CtObject InsetMathHull::getCtObject(OutputParams const & runparams) const
1097 CtObject res = CtObject::Normal;
1113 case hullMultline: {
1114 if (runparams.inulemcmd
1115 && (!runparams.local_font || runparams.local_font->fontInfo().strikeout() != FONT_ON))
1116 res = CtObject::UDisplayObject;
1118 res = CtObject::DisplayObject;
1126 void InsetMathHull::header_write(TeXMathStream & os) const
1128 bool n = numberedType();
1139 if (cell(0).empty())
1144 writeMathdisplayPreamble(os);
1148 os << "\\begin{equation" << star(n) << "}\n";
1158 writeMathdisplayPreamble(os);
1161 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1168 os << "\\begin{" << hullName(type_) << star(n) << '}'
1169 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1175 os << "\\begin{" << hullName(type_) << '}'
1176 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1186 os << "\\begin{unknown" << star(n) << "}\n";
1192 void InsetMathHull::footer_write(TeXMathStream & os) const
1194 bool n = numberedType();
1211 os << "\\end{equation" << star(n) << "}\n";
1214 writeMathdisplayPostamble(os);
1224 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1225 writeMathdisplayPostamble(os);
1232 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1238 os << "\\end{" << hullName(type_) << "}\n";
1242 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1243 os << "\\endregexp{}}";
1249 os << "\\end{unknown" << star(n) << "}\n";
1255 bool InsetMathHull::allowsTabularFeatures() const
1278 bool InsetMathHull::rowChangeOK() const
1281 type_ == hullEqnArray || type_ == hullAlign ||
1282 type_ == hullFlAlign || type_ == hullAlignAt ||
1283 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1284 type_ == hullGather || type_ == hullMultline;
1288 bool InsetMathHull::colChangeOK() const
1291 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1292 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1296 void InsetMathHull::addRow(row_type row)
1301 bool numbered = numberedType();
1302 // Move the number and raw pointer, do not call label() (bug 7511)
1303 InsetLabel * label = dummy_pointer;
1304 docstring number = empty_docstring();
1305 if (type_ == hullMultline) {
1306 if (row + 1 == nrows()) {
1307 numbered_[row] = NONUMBER;
1308 swap(label, label_[row]);
1309 swap(number, numbers_[row]);
1314 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1315 numbers_.insert(numbers_.begin() + row + 1, number);
1316 label_.insert(label_.begin() + row + 1, label);
1317 InsetMathGrid::addRow(row);
1321 void InsetMathHull::swapRow(row_type row)
1325 if (row + 1 == nrows())
1327 swap(numbered_[row], numbered_[row + 1]);
1328 swap(numbers_[row], numbers_[row + 1]);
1329 swap(label_[row], label_[row + 1]);
1330 InsetMathGrid::swapRow(row);
1334 void InsetMathHull::delRow(row_type row)
1336 if (nrows() <= 1 || !rowChangeOK())
1338 if (row + 1 == nrows() && type_ == hullMultline) {
1339 swap(numbered_[row - 1], numbered_[row]);
1340 swap(numbers_[row - 1], numbers_[row]);
1341 swap(label_[row - 1], label_[row]);
1342 InsetMathGrid::delRow(row);
1345 InsetMathGrid::delRow(row);
1346 // The last dummy row has no number info nor a label.
1347 // Test nrows() + 1 because we have already erased the row.
1348 if (row == nrows() + 1)
1350 numbered_.erase(numbered_.begin() + row);
1351 numbers_.erase(numbers_.begin() + row);
1353 label_.erase(label_.begin() + row);
1357 void InsetMathHull::addCol(col_type col)
1361 InsetMathGrid::addCol(col);
1365 void InsetMathHull::delCol(col_type col)
1367 if (ncols() <= 1 || !colChangeOK())
1369 InsetMathGrid::delCol(col);
1373 docstring InsetMathHull::nicelabel(row_type row) const
1377 docstring const & val = numbers_[row];
1379 return '(' + val + ')';
1380 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1384 void InsetMathHull::glueall(HullType type)
1387 for (idx_type i = 0; i < nargs(); ++i)
1389 InsetLabel * label = 0;
1390 if (type == hullEquation) {
1391 // preserve first non-empty label
1392 for (row_type row = 0; row < nrows(); ++row) {
1394 label = label_[row];
1400 *this = InsetMathHull(buffer_, hullSimple);
1407 void InsetMathHull::splitTo2Cols()
1409 LASSERT(ncols() == 1, return);
1410 InsetMathGrid::addCol(1);
1411 for (row_type row = 0; row < nrows(); ++row) {
1412 idx_type const i = 2 * row;
1413 pos_type pos = firstRelOp(cell(i));
1414 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1415 cell(i).erase(pos, cell(i).size());
1420 void InsetMathHull::splitTo3Cols()
1422 LASSERT(ncols() < 3, return);
1425 InsetMathGrid::addCol(2);
1426 for (row_type row = 0; row < nrows(); ++row) {
1427 idx_type const i = 3 * row + 1;
1428 if (!cell(i).empty()) {
1429 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1430 cell(i).erase(1, cell(i).size());
1436 void InsetMathHull::changeCols(col_type cols)
1438 if (ncols() == cols)
1440 else if (ncols() < cols) {
1446 while (ncols() < cols)
1447 InsetMathGrid::addCol(ncols());
1453 for (row_type row = 0; row < nrows(); ++row) {
1454 idx_type const i = row * ncols();
1455 for (col_type col = cols; col < ncols(); ++col) {
1456 cell(i + cols - 1).append(cell(i + col));
1460 while (ncols() > cols) {
1461 InsetMathGrid::delCol(ncols() - 1);
1466 HullType InsetMathHull::getType() const
1472 void InsetMathHull::setType(HullType type)
1479 bool InsetMathHull::isMutable(HullType type)
1503 void InsetMathHull::mutate(HullType newtype)
1505 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1507 if (newtype == type_)
1510 // This guards the algorithm below it, which is designed with certain types
1512 if (!isMutable(newtype) || !isMutable(type_)) {
1513 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1514 << "' to '" << to_utf8(hullName(newtype))
1515 << "' not implemented" << endl;
1519 // we try to move along the chain
1520 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1522 // +-------------------------------------+
1523 // we use eqnarray as intermediate type for mutations that are not
1524 // directly supported because it handles labels and numbering for
1529 setType(hullSimple);
1535 if (newtype == hullNone) {
1539 setType(hullEquation);
1540 numbered(0, label_[0] != nullptr);
1549 setType(hullSimple);
1554 // split it "nicely" on the first relop
1556 setType(hullEqnArray);
1564 // split it "nicely"
1599 setType(hullEqnArray);
1608 for (row_type row = 0; row < nrows(); ++row)
1609 numbered(row, false);
1619 for (row_type row = 0; row < nrows(); ++row)
1620 numbered(row, false);
1627 setType(hullEqnArray);
1657 for (row_type row = 0; row < nrows(); ++row)
1658 numbered(row, false);
1662 // first we mutate to EqnArray
1664 setType(hullEqnArray);
1671 // we passed the guard so we should not be here
1672 LYXERR0("Mutation not implemented, but should have been.");
1673 LASSERT(false, return);
1679 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1680 bool last_eoln) const
1683 if (numberedType()) {
1684 if (label_[row] && numbered(row)) {
1685 docstring const name =
1686 latex ? escape(label_[row]->getParam("name"))
1687 : label_[row]->getParam("name");
1688 res += "\\label{" + name + '}';
1690 if (type_ != hullMultline) {
1691 if (numbered_[row] == NONUMBER)
1692 res += "\\nonumber ";
1693 else if (numbered_[row] == NOTAG)
1697 // Never add \\ on the last empty line of eqnarray and friends
1699 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1702 void InsetMathHull::write(TeXMathStream & os) const
1704 ModeSpecifier specifier(os, MATH_MODE);
1706 InsetMathGrid::write(os);
1711 void InsetMathHull::normalize(NormalStream & os) const
1713 os << "[formula " << hullName(type_) << ' ';
1714 InsetMathGrid::normalize(os);
1719 void InsetMathHull::infoize(odocstream & os) const
1721 os << bformat(_("Type: %1$s"), hullName(type_));
1725 void InsetMathHull::check() const
1727 LATTEST(numbered_.size() == nrows());
1728 LATTEST(numbers_.size() == nrows());
1729 LATTEST(label_.size() == nrows());
1733 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1735 //FIXME: sort out whether we want std::string or docstring for those
1736 string const lang = func.getArg(0);
1737 docstring extra = from_utf8(func.getArg(1));
1739 extra = from_ascii("noextra");
1741 // replace selection with result of computation
1742 if (reduceSelectionToOneCell(cur)) {
1744 asArray(grabAndEraseSelection(cur), ar);
1745 lyxerr << "use selection: " << ar << endl;
1746 cur.insert(pipeThroughExtern(lang, extra, ar));
1750 // only inline, display or eqnarray math is allowed
1751 switch (getType()) {
1757 frontend::Alert::warning(_("Bad math environment"),
1758 _("Computation cannot be performed for AMS "
1759 "math environments.\nChange the math "
1760 "formula type and try again."));
1765 eq.push_back(MathAtom(new InsetMathChar('=')));
1767 // go to first item in line
1768 cur.idx() -= cur.idx() % ncols();
1771 if (getType() == hullSimple) {
1772 size_type pos = cur.cell().find_last(eq);
1774 if (pos == cur.cell().size()) {
1776 lyxerr << "use whole cell: " << ar << endl;
1778 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1779 lyxerr << "use partial cell form pos: " << pos << endl;
1781 cur.cell().append(eq);
1782 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1783 cur.pos() = cur.lastpos();
1787 if (getType() == hullEquation) {
1788 lyxerr << "use equation inset" << endl;
1789 mutate(hullEqnArray);
1790 MathData & ar = cur.cell();
1791 lyxerr << "use cell: " << ar << endl;
1795 cur.cell() = pipeThroughExtern(lang, extra, ar);
1796 // move to end of line
1797 cur.pos() = cur.lastpos();
1802 lyxerr << "use eqnarray" << endl;
1803 cur.idx() += 2 - cur.idx() % ncols();
1805 MathData ar = cur.cell();
1806 lyxerr << "use cell: " << ar << endl;
1807 // FIXME: temporarily disabled
1813 cur.cell() = pipeThroughExtern(lang, extra, ar);
1814 cur.pos() = cur.lastpos();
1819 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1821 //lyxerr << "action: " << cmd.action() << endl;
1822 switch (cmd.action()) {
1824 case LFUN_FINISHED_BACKWARD:
1825 case LFUN_FINISHED_FORWARD:
1826 case LFUN_FINISHED_RIGHT:
1827 case LFUN_FINISHED_LEFT:
1828 //lyxerr << "action: " << cmd.action() << endl;
1829 InsetMathGrid::doDispatch(cur, cmd);
1832 case LFUN_PARAGRAPH_BREAK:
1833 // just swallow this
1836 case LFUN_NEWLINE_INSERT:
1837 // some magic for the common case
1838 if (type_ == hullSimple || type_ == hullEquation) {
1839 cur.recordUndoInset();
1841 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1842 mutate(align ? hullAlign : hullEqnArray);
1843 // mutate() may change labels and such.
1844 cur.forceBufferUpdate();
1845 cur.idx() = nrows() * ncols() - 1;
1846 cur.pos() = cur.lastpos();
1848 InsetMathGrid::doDispatch(cur, cmd);
1851 case LFUN_MATH_NUMBER_TOGGLE: {
1852 //lyxerr << "toggling all numbers" << endl;
1853 cur.recordUndoInset();
1854 bool old = numberedType();
1855 if (type_ == hullMultline)
1856 numbered(nrows() - 1, !old);
1858 for (row_type row = 0; row < nrows(); ++row)
1859 numbered(row, !old);
1861 cur.message(old ? _("No number") : _("Number"));
1862 cur.forceBufferUpdate();
1866 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1867 cur.recordUndoInset();
1868 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1869 bool old = numbered(r);
1870 cur.message(old ? _("No number") : _("Number"));
1872 cur.forceBufferUpdate();
1876 case LFUN_LABEL_INSERT: {
1877 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1878 docstring old_label = label(r);
1879 docstring const default_label = from_ascii("eq:");
1880 if (old_label.empty())
1881 old_label = default_label;
1883 InsetCommandParams p(LABEL_CODE);
1884 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1885 string const data = InsetCommand::params2string(p);
1887 if (cmd.argument().empty())
1888 cur.bv().showDialog("label", data);
1890 FuncRequest fr(LFUN_INSET_INSERT, data);
1896 case LFUN_LABEL_COPY_AS_REFERENCE: {
1898 if (cmd.argument().empty() && &cur.inset() == this)
1899 // if there is no argument and we're inside math, we retrieve
1900 // the row number from the cursor position.
1901 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1903 // if there is an argument, find the corresponding label, else
1904 // check whether there is at least one label.
1905 for (row = 0; row != nrows(); ++row)
1906 if (numbered(row) && label_[row]
1907 && (cmd.argument().empty() || label(row) == cmd.argument()))
1914 InsetCommandParams p(REF_CODE, "ref");
1915 p["reference"] = label(row);
1916 cap::clearSelection();
1917 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1921 case LFUN_WORD_DELETE_FORWARD:
1922 case LFUN_CHAR_DELETE_FORWARD:
1923 if (col(cur.idx()) + 1 == ncols()
1924 && cur.pos() == cur.lastpos()
1925 && !cur.selection()) {
1926 if (!label(row(cur.idx())).empty()) {
1927 cur.recordUndoInset();
1928 label(row(cur.idx()), docstring());
1929 } else if (numbered(row(cur.idx()))) {
1930 cur.recordUndoInset();
1931 numbered(row(cur.idx()), false);
1932 cur.forceBufferUpdate();
1934 InsetMathGrid::doDispatch(cur, cmd);
1938 InsetMathGrid::doDispatch(cur, cmd);
1943 case LFUN_INSET_INSERT: {
1944 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1945 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1946 string const name = cmd.getArg(0);
1947 if (name == "label") {
1948 InsetCommandParams p(LABEL_CODE);
1949 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1950 docstring str = p["name"];
1951 cur.recordUndoInset();
1952 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1956 docstring old = label(r);
1959 // The label will take care of the reference update.
1963 // Newly created inset so initialize it.
1964 label_[r]->initView();
1967 cur.forceBufferUpdate();
1970 InsetMathGrid::doDispatch(cur, cmd);
1974 case LFUN_MATH_EXTERN:
1975 cur.recordUndoInset();
1979 case LFUN_MATH_MUTATE: {
1980 cur.recordUndoInset();
1981 row_type row = cur.row();
1982 col_type col = cur.col();
1983 mutate(hullType(cmd.argument()));
1984 cur.idx() = row * ncols() + col;
1985 if (cur.idx() > cur.lastidx()) {
1986 cur.idx() = cur.lastidx();
1987 cur.pos() = cur.lastpos();
1989 if (cur.pos() > cur.lastpos())
1990 cur.pos() = cur.lastpos();
1992 cur.forceBufferUpdate();
1993 // FIXME: find some more clever handling of the selection,
1994 // i.e. preserve it.
1995 cur.clearSelection();
1996 //cur.dispatched(FINISHED);
2000 case LFUN_MATH_DISPLAY: {
2001 cur.recordUndoInset();
2002 mutate(type_ == hullSimple ? hullEquation : hullSimple);
2003 // if the cursor is in a cell that got merged, move it to
2004 // start of the hull inset.
2005 if (cur.idx() > 0) {
2009 if (cur.pos() > cur.lastpos())
2010 cur.pos() = cur.lastpos();
2015 case LFUN_TABULAR_FEATURE:
2016 if (!allowsTabularFeatures())
2019 InsetMathGrid::doDispatch(cur, cmd);
2023 InsetMathGrid::doDispatch(cur, cmd);
2031 bool allowDisplayMath(Cursor const & cur)
2033 LATTEST(cur.depth() > 1);
2034 Cursor tmpcur = cur;
2037 FuncRequest cmd(LFUN_MATH_DISPLAY);
2038 return tmpcur.getStatus(cmd, status) && status.enabled();
2044 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
2045 FuncStatus & status) const
2047 switch (cmd.action()) {
2048 case LFUN_FINISHED_BACKWARD:
2049 case LFUN_FINISHED_FORWARD:
2050 case LFUN_FINISHED_RIGHT:
2051 case LFUN_FINISHED_LEFT:
2054 case LFUN_NEWLINE_INSERT:
2055 case LFUN_MATH_EXTERN:
2057 status.setEnabled(true);
2060 // we never allow this in math, and we want to bind enter
2061 // to another actions in command-alternatives
2062 case LFUN_PARAGRAPH_BREAK:
2063 status.setEnabled(false);
2065 case LFUN_MATH_MUTATE: {
2066 HullType const ht = hullType(cmd.argument());
2067 status.setOnOff(type_ == ht);
2068 status.setEnabled(isMutable(ht) && isMutable(type_));
2070 if (ht != hullSimple && status.enabled())
2071 status.setEnabled(allowDisplayMath(cur));
2074 case LFUN_MATH_DISPLAY: {
2075 status.setEnabled(display() || allowDisplayMath(cur));
2076 status.setOnOff(display());
2080 case LFUN_MATH_NUMBER_TOGGLE:
2081 // FIXME: what is the right test, this or the one of
2083 status.setEnabled(display());
2084 status.setOnOff(numberedType());
2087 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
2088 // FIXME: what is the right test, this or the one of
2090 bool const enable = (type_ == hullMultline)
2091 ? (nrows() - 1 == cur.row())
2093 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2094 status.setEnabled(enable);
2095 status.setOnOff(enable && numbered(r));
2099 case LFUN_LABEL_INSERT:
2100 status.setEnabled(type_ != hullSimple);
2103 case LFUN_LABEL_COPY_AS_REFERENCE: {
2104 bool enabled = false;
2105 if (cmd.argument().empty() && &cur.inset() == this) {
2106 // if there is no argument and we're inside math, we retrieve
2107 // the row number from the cursor position.
2108 row_type row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2109 enabled = numberedType() && label_[row] && numbered(row);
2111 // if there is an argument, find the corresponding label, else
2112 // check whether there is at least one label.
2113 for (row_type row = 0; row != nrows(); ++row) {
2114 if (numbered(row) && label_[row] &&
2115 (cmd.argument().empty() || label(row) == cmd.argument())) {
2121 status.setEnabled(enabled);
2125 case LFUN_INSET_INSERT:
2126 if (cmd.getArg(0) == "label") {
2127 status.setEnabled(type_ != hullSimple);
2130 return InsetMathGrid::getStatus(cur, cmd, status);
2132 case LFUN_TABULAR_FEATURE: {
2133 if (!allowsTabularFeatures())
2135 string s = cmd.getArg(0);
2137 && (s == "append-row"
2138 || s == "delete-row"
2139 || s == "copy-row")) {
2140 status.message(bformat(
2141 from_utf8(N_("Can't change number of rows in '%1$s'")),
2143 status.setEnabled(false);
2147 && (s == "append-column"
2148 || s == "delete-column"
2149 || s == "copy-column")) {
2150 status.message(bformat(
2151 from_utf8(N_("Can't change number of columns in '%1$s'")),
2153 status.setEnabled(false);
2156 if (s == "add-vline-left" || s == "add-vline-right") {
2157 status.message(bformat(
2158 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2160 status.setEnabled(false);
2163 if (s == "valign-top" || s == "valign-middle"
2164 || s == "valign-bottom" || s == "align-left"
2165 || s == "align-center" || s == "align-right") {
2166 status.setEnabled(false);
2169 return InsetMathGrid::getStatus(cur, cmd, status);
2173 return InsetMathGrid::getStatus(cur, cmd, status);
2178 int InsetMathHull::leftMargin() const
2180 return (getType() == hullSimple) ? 0 : InsetMathGrid::leftMargin();
2184 int InsetMathHull::rightMargin() const
2186 return (getType() == hullSimple) ? 0 : InsetMathGrid::rightMargin();
2190 int InsetMathHull::border() const
2192 return (getType() == hullSimple) ? 0 : InsetMathGrid::border();
2196 /////////////////////////////////////////////////////////////////////
2200 // simply scrap this function if you want
2201 void InsetMathHull::mutateToText()
2204 // translate to latex
2206 latex(os, false, false);
2207 string str = os.str();
2210 Text * lt = view_->cursor().innerText();
2211 string::const_iterator cit = str.begin();
2212 string::const_iterator end = str.end();
2213 for (; cit != end; ++cit)
2214 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2217 //dispatch(LFUN_ESCAPE);
2222 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2223 docstring const & font)
2225 // this whole function is a hack and won't work for incremental font
2228 if (cur.inset().asInsetMath()->name() == font)
2229 cur.handleFont(to_utf8(font));
2231 cur.handleNest(createInsetMath(font, cur.buffer()));
2237 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2242 font.fromString(to_utf8(arg), b);
2243 if (font.fontInfo().color() != Color_inherit) {
2244 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2250 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2252 InsetMathNest::edit(cur, front, entry_from);
2253 // The inset formula dimension is not necessarily the same as the
2254 // one of the instant preview image, so we have to indicate to the
2255 // BufferView that a metrics update is needed.
2256 cur.screenUpdateFlags(Update::Force);
2260 /////////////////////////////////////////////////////////////////////
2264 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2267 // FIXME: completely broken
2268 static InsetMathHull * lastformula = 0;
2269 static CursorBase current = DocIterator(ibegin(nucleus()));
2271 static string laststr;
2273 if (lastformula != this || laststr != str) {
2274 //lyxerr << "reset lastformula to " << this << endl;
2277 current = ibegin(nucleus());
2279 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2283 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2285 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2286 CursorSlice & top = it.back();
2287 MathData const & a = top.asInsetMath()->cell(top.idx_);
2288 if (a.matchpart(ar, top.pos_)) {
2289 bv->cursor().setSelection(it, ar.size());
2291 top.pos_ += ar.size();
2297 //lyxerr << "not found!" << endl;
2304 void InsetMathHull::write(ostream & os) const
2306 odocstringstream oss;
2307 otexrowstream ots(oss);
2308 TeXMathStream wi(ots, false, false, TeXMathStream::wsDefault);
2311 os << to_utf8(oss.str());
2315 void InsetMathHull::read(Lexer & lex)
2318 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2319 operator=(*at->asHullInset());
2323 bool InsetMathHull::readQuiet(Lexer & lex)
2326 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2328 operator=(*at->asHullInset());
2333 int InsetMathHull::plaintext(odocstringstream & os,
2334 OutputParams const & op, size_t max_length) const
2336 // Try enabling this now that there is a flag as requested at #2275.
2337 if (buffer().isExporting() && display()) {
2341 TextPainter tpain(dim.width(), dim.height());
2342 drawT(tpain, 0, dim.ascent());
2344 // reset metrics cache to "real" values
2346 return tpain.textheight();
2349 odocstringstream oss;
2350 otexrowstream ots(oss);
2351 Encoding const * const enc = encodings.fromLyXName("utf8");
2352 TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault, enc);
2355 if (type_ == hullRegexp)
2358 for (row_type r = 0; r < nrows(); ++r) {
2359 for (col_type c = 0; c < ncols(); ++c)
2360 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2361 // if it's for the TOC, we write just the first line
2362 // and do not include the newline.
2363 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2365 if (r < nrows() - 1)
2369 docstring const str = oss.str();
2375 void InsetMathHull::docbook(XMLStream & xs, OutputParams const & runparams) const
2377 // Choose the tag around the MathML equation.
2380 if (getType() == hullSimple)
2381 name = from_ascii("inlineequation");
2383 doCR = true; // This is a block equation, always have <informalequation> on its own line.
2384 name = from_ascii("informalequation");
2387 // DocBook also has <equation>, but it comes with a title.
2388 // TODO: recognise \tag from amsmath? This would allow having <equation> with a proper title.
2391 for (row_type i = 0; i < nrows(); ++i) {
2392 if (!label(i).empty()) {
2393 attr = "xml:id=\"" + xml::cleanID(label(i)) + "\"";
2399 if (!xs.isLastTagCR())
2402 xs << xml::StartTag(name, attr);
2405 // With DocBook 5, MathML must be within its own namespace; defined in Buffer.cpp::writeDocBookSource as "m".
2406 // Output everything in a separate stream so that this does not interfere with the standard flow of DocBook tags.
2407 odocstringstream osmath;
2408 MathMLStream ms(osmath, "m", true);
2410 // Output the MathML subtree.
2411 odocstringstream ls;
2414 // TeX transcription. Avoid MTag/ETag so that there are no extraneous spaces.
2415 ms << "<" << from_ascii("alt") << " role='tex'" << ">";
2416 // Workaround for db2latex: db2latex always includes equations with
2417 // \ensuremath{} or \begin{display}\end{display}
2418 // so we strip LyX' math environment
2419 TeXMathStream wi(ols, false, false, TeXMathStream::wsDefault, runparams.encoding);
2420 InsetMathGrid::write(wi);
2421 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2422 ms << "</" << from_ascii("alt") << ">";
2424 // Actual transformation of the formula into MathML. This translation may fail (for example, due to custom macros).
2425 // The new output stream is required to deal with the errors: first write completely the formula into this
2426 // temporary stream; then, if it is possible without error, then copy it back to the "real" stream. Otherwise,
2427 // some incomplete tags might be put into the real stream.
2429 // First, generate the MathML expression.
2430 odocstringstream ostmp;
2431 MathMLStream mstmp(ostmp, ms.xmlns(), ms.xmlMode());
2432 InsetMathGrid::mathmlize(mstmp);
2434 // Then, output it (but only if the generation can be done without errors!).
2437 osmath << ostmp.str(); // osmath is not a XMLStream, so no need for XMLStream::ESCAPE_NONE.
2439 } catch (MathExportException const &) {
2441 osmath << "<mathphrase>MathML export failed. Please report this as a bug.</mathphrase>";
2444 // Output the complete formula to the DocBook stream.
2445 xs << XMLStream::ESCAPE_NONE << osmath.str();
2447 xs << xml::EndTag(name);
2453 bool InsetMathHull::haveNumbers() const
2455 bool havenumbers = false;
2456 // inline formulas are never numbered (bug 7351 part 3)
2457 if (getType() == hullSimple)
2459 for (size_t i = 0; i != numbered_.size(); ++i) {
2470 // We need to do something about alignment here.
2472 // This duplicates code from InsetMathGrid, but
2473 // we need access here to number information,
2474 // and we simply do not have that in InsetMathGrid.
2475 void InsetMathHull::htmlize(HtmlStream & os) const
2477 bool const havenumbers = haveNumbers();
2478 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2481 os << cell(index(0, 0));
2485 os << MTag("table", "class='mathtable'");
2486 for (row_type row = 0; row < nrows(); ++row) {
2488 for (col_type col = 0; col < ncols(); ++col) {
2490 os << cell(index(row, col));
2495 docstring const & num = numbers_[row];
2497 os << '(' << num << ')';
2502 os << ETag("table");
2506 // this duplicates code from InsetMathGrid, but
2507 // we need access here to number information,
2508 // and we simply do not have that in InsetMathGrid.
2509 void InsetMathHull::mathmlize(MathMLStream & ms) const
2511 bool const havenumbers = haveNumbers();
2512 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2515 ms << MTag("mtable");
2516 char const * const celltag = havetable ? "mtd" : "mrow";
2517 // FIXME There does not seem to be wide support at the moment
2518 // for mlabeledtr, so we have to use just mtr for now.
2519 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2520 char const * const rowtag = "mtr";
2521 for (row_type row = 0; row < nrows(); ++row) {
2524 for (col_type col = 0; col < ncols(); ++col) {
2526 << cell(index(row, col))
2532 docstring const & num = numbers_[row];
2534 ms << '(' << num << ')';
2541 ms << ETag("mtable");
2545 void InsetMathHull::mathAsLatex(TeXMathStream & os) const
2547 MathEnsurer ensurer(os, false);
2548 bool havenumbers = haveNumbers();
2549 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2552 os << cell(index(0, 0));
2556 os << "<table class='mathtable'>";
2557 for (row_type row = 0; row < nrows(); ++row) {
2559 for (col_type col = 0; col < ncols(); ++col) {
2560 os << "<td class='math'>";
2561 os << cell(index(row, col));
2566 docstring const & num = numbers_[row];
2568 os << '(' << num << ')';
2577 docstring InsetMathHull::xhtml(XMLStream & xs, OutputParams const & op) const
2579 BufferParams::MathOutput const mathtype =
2580 buffer().masterBuffer()->params().html_math_output;
2582 bool success = false;
2584 // we output all the labels just at the beginning of the equation.
2585 // this should be fine.
2586 for (size_t i = 0; i != label_.size(); ++i) {
2587 InsetLabel const * const il = label_[i];
2593 // FIXME Eventually we would like to do this inset by inset.
2594 if (mathtype == BufferParams::MathML) {
2595 odocstringstream os;
2596 MathMLStream ms(os);
2600 } catch (MathExportException const &) {}
2602 if (getType() == hullSimple)
2603 xs << xml::StartTag("math",
2604 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2606 xs << xml::StartTag("math",
2607 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2608 xs << XMLStream::ESCAPE_NONE
2610 << xml::EndTag("math");
2612 } else if (mathtype == BufferParams::HTML) {
2613 odocstringstream os;
2618 } catch (MathExportException const &) {}
2620 string const tag = (getType() == hullSimple) ? "span" : "div";
2621 xs << xml::StartTag(tag, "class='formula'", true)
2622 << XMLStream::ESCAPE_NONE
2624 << xml::EndTag(tag);
2628 // what we actually want is this:
2630 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2632 // || mathtype == BufferParams::Images
2634 // but what follows is equivalent, since we'll enter only if either (a) we
2635 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2636 // aren't doing LaTeX.
2638 // so this is for Images.
2639 if (!success && mathtype != BufferParams::LaTeX) {
2640 graphics::PreviewImage const * pimage = 0;
2642 loadPreview(docit_);
2643 pimage = preview_->getPreviewImage(buffer());
2644 // FIXME Do we always have png?
2647 if (pimage || op.dryrun) {
2648 string const filename = pimage ? pimage->filename().onlyFileName()
2649 : "previewimage.png";
2651 // if we are not in the master buffer, then we need to see that the
2652 // generated image is copied there; otherwise, preview fails.
2653 Buffer const * mbuf = buffer().masterBuffer();
2654 if (mbuf != &buffer()) {
2655 string mbtmp = mbuf->temppath();
2656 FileName const mbufimg(support::addName(mbtmp, filename));
2657 pimage->filename().copyTo(mbufimg);
2659 // add the file to the list of files to be exported
2660 op.exportdata->addExternalFile("xhtml", pimage->filename());
2663 string const tag = (getType() == hullSimple) ? "span" : "div";
2665 << xml::StartTag(tag, "style = \"text-align: center;\"")
2666 << xml::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2673 // so we'll pass this test if we've failed everything else, or
2674 // if mathtype was LaTeX, since we won't have entered any of the
2676 if (!success /* || mathtype != BufferParams::LaTeX */) {
2677 // Unfortunately, we cannot use latexString() because we do not want
2678 // $...$ or whatever.
2679 odocstringstream ls;
2680 otexrowstream ots(ls);
2681 TeXMathStream wi(ots, false, true, TeXMathStream::wsPreview);
2682 ModeSpecifier specifier(wi, MATH_MODE);
2684 docstring const latex = ls.str();
2686 // class='math' allows for use of jsMath
2687 // http://www.math.union.edu/~dpvc/jsMath/
2689 // probably should allow for some kind of customization here
2690 string const tag = (getType() == hullSimple) ? "span" : "div";
2691 xs << xml::StartTag(tag, "class='math'")
2700 void InsetMathHull::toString(odocstream & os) const
2702 odocstringstream ods;
2703 plaintext(ods, OutputParams(0));
2708 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2710 odocstringstream ods;
2713 // FIXME: this results in spilling TeX into the LyXHTML output since the
2714 // outliner is used to generate the LyXHTML list of figures/etc.
2720 string InsetMathHull::contextMenuName() const
2722 return "context-math";
2726 void InsetMathHull::recordLocation(DocIterator const & di)
2732 bool InsetMathHull::canPaintChange(BufferView const &) const
2734 // We let RowPainter do it seamlessly for inline insets