2 * \file InsetMathHull.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 #include "InsetMathHull.h"
15 #include "InsetMathChar.h"
16 #include "InsetMathColor.h"
17 #include "InsetMathFrac.h"
18 #include "InsetMathNest.h"
19 #include "InsetMathScript.h"
20 #include "MathExtern.h"
21 #include "MathFactory.h"
22 #include "MathStream.h"
23 #include "MathSupport.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
29 #include "CutAndPaste.h"
32 #include "FuncRequest.h"
33 #include "FuncStatus.h"
35 #include "LaTeXFeatures.h"
37 #include "MacroTable.h"
38 #include "InsetMathMacro.h"
39 #include "InsetMathMacroTemplate.h"
40 #include "MetricsInfo.h"
41 #include "output_xhtml.h"
42 #include "Paragraph.h"
43 #include "ParIterator.h"
46 #include "TextClass.h"
47 #include "TextPainter.h"
48 #include "TocBackend.h"
50 #include "insets/InsetLabel.h"
51 #include "insets/InsetRef.h"
52 #include "insets/RenderPreview.h"
54 #include "graphics/GraphicsImage.h"
55 #include "graphics/PreviewImage.h"
56 #include "graphics/PreviewLoader.h"
58 #include "frontends/alert.h"
59 #include "frontends/Painter.h"
61 #include "support/convert.h"
62 #include "support/debug.h"
63 #include "support/gettext.h"
64 #include "support/filetools.h"
65 #include "support/lassert.h"
66 #include "support/lstrings.h"
67 #include "support/RefChanger.h"
72 using namespace lyx::support;
76 using cap::grabAndEraseSelection;
77 using cap::reduceSelectionToOneCell;
81 int getCols(HullType type)
106 // returns position of first relation operator in the array
107 // used for "intelligent splitting"
108 size_t firstRelOp(MathData const & ar)
110 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
111 if ((*it)->mathClass() == MC_REL)
112 return it - ar.begin();
117 char const * star(bool numbered)
119 return numbered ? "" : "*";
123 // writes a preamble for underlined or struck out math display
124 void writeMathdisplayPreamble(WriteStream & os)
126 if (os.strikeoutMath()) {
127 if (os.ulemCmd() == WriteStream::UNDERLINE)
128 os << "\\raisebox{-\\belowdisplayshortskip}{"
129 "\\lyxmathsout{\\parbox[b]{\\linewidth}{";
131 os << "\\lyxmathsout{\\parbox{\\linewidth}{";
132 } else if (os.ulemCmd() == WriteStream::UNDERLINE)
133 os << "\\raisebox{-\\belowdisplayshortskip}{"
134 "\\parbox[b]{\\linewidth}{";
135 else if (os.ulemCmd() == WriteStream::STRIKEOUT)
136 os << "\\parbox{\\linewidth}{";
140 // writes a postamble for underlined or struck out math display
141 void writeMathdisplayPostamble(WriteStream & os)
143 if (os.strikeoutMath()) {
144 if (os.ulemCmd() == WriteStream::UNDERLINE)
147 } else if (os.ulemCmd() == WriteStream::UNDERLINE)
149 else if (os.ulemCmd() == WriteStream::STRIKEOUT)
157 HullType hullType(docstring const & s)
159 if (s == "none") return hullNone;
160 if (s == "simple") return hullSimple;
161 if (s == "equation") return hullEquation;
162 if (s == "eqnarray") return hullEqnArray;
163 if (s == "align") return hullAlign;
164 if (s == "alignat") return hullAlignAt;
165 if (s == "xalignat") return hullXAlignAt;
166 if (s == "xxalignat") return hullXXAlignAt;
167 if (s == "multline") return hullMultline;
168 if (s == "gather") return hullGather;
169 if (s == "flalign") return hullFlAlign;
170 if (s == "regexp") return hullRegexp;
171 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
176 docstring hullName(HullType type)
179 case hullNone: return from_ascii("none");
180 case hullSimple: return from_ascii("simple");
181 case hullEquation: return from_ascii("equation");
182 case hullEqnArray: return from_ascii("eqnarray");
183 case hullAlign: return from_ascii("align");
184 case hullAlignAt: return from_ascii("alignat");
185 case hullXAlignAt: return from_ascii("xalignat");
186 case hullXXAlignAt: return from_ascii("xxalignat");
187 case hullMultline: return from_ascii("multline");
188 case hullGather: return from_ascii("gather");
189 case hullFlAlign: return from_ascii("flalign");
190 case hullRegexp: return from_ascii("regexp");
192 lyxerr << "unknown hull type" << endl;
195 return from_ascii("none");
198 static InsetLabel * dummy_pointer = 0;
200 InsetMathHull::InsetMathHull(Buffer * buf)
201 : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, NUMBER),
202 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
203 preview_(new RenderPreview(this))
205 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
206 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
207 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
208 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
215 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
216 : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, NUMBER),
217 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
218 preview_(new RenderPreview(this))
226 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
232 InsetMathHull::~InsetMathHull()
234 for (size_t i = 0; i < label_.size(); ++i)
239 Inset * InsetMathHull::clone() const
241 return new InsetMathHull(*this);
245 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
249 InsetMathGrid::operator=(other);
251 numbered_ = other.numbered_;
252 numbers_ = other.numbers_;
253 buffer_ = other.buffer_;
254 for (size_t i = 0; i < label_.size(); ++i)
256 label_ = other.label_;
257 for (size_t i = 0; i != label_.size(); ++i) {
259 label_[i] = new InsetLabel(*label_[i]);
261 preview_.reset(new RenderPreview(*other.preview_, this));
267 void InsetMathHull::setBuffer(Buffer & buffer)
269 InsetMathGrid::setBuffer(buffer);
271 for (size_t i = 0; i != label_.size(); ++i) {
273 label_[i]->setBuffer(buffer);
278 // FIXME This should really be controlled by the TOC level, or
279 // something of the sort.
281 const char * counters_to_save[] = {"section", "chapter"};
282 unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
286 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
289 //FIXME: buffer_ should be set at creation for this inset! Problem is
290 // This inset is created at too many places (see Parser::parse1() in
295 // if any of the equations are numbered, then we want to save the values
296 // of some of the counters.
298 BufferParams const & bp = buffer_->params();
299 string const & lang = it->getParLanguage(bp)->code();
301 buffer_->masterBuffer()->params().documentClass().counters();
303 // right now, we only need to do this at export time
304 if (utype == OutputUpdate) {
305 for (size_t i = 0; i < numcnts; ++i) {
306 docstring const cnt = from_ascii(counters_to_save[i]);
307 if (cnts.hasCounter(cnt))
308 counter_map[cnt] = cnts.value(cnt);
312 // this has to be done separately
313 docstring const eqstr = from_ascii("equation");
314 if (cnts.hasCounter(eqstr)) {
315 if (utype == OutputUpdate)
316 counter_map[eqstr] = cnts.value(eqstr);
317 for (size_t i = 0; i != label_.size(); ++i) {
319 Paragraph const & par = it.paragraph();
320 if (!par.isDeleted(it.pos())) {
321 cnts.step(eqstr, utype);
322 numbers_[i] = cnts.theCounter(eqstr, lang);
324 numbers_[i] = from_ascii("#");
326 numbers_[i] = empty_docstring();
332 for (size_t i = 0; i != label_.size(); ++i) {
334 label_[i]->updateBuffer(it, utype);
337 InsetMathGrid::updateBuffer(it, utype);
341 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active,
342 UpdateType utype, TocBackend & backend) const
345 //FIXME: buffer_ should be set at creation for this inset! Problem is
346 // This inset is created at too many places (see Parser::parse1() in
351 TocBuilder & b = backend.builder("equation");
352 // compute first and last item
353 row_type first = nrows();
354 for (row_type row = 0; row != nrows(); ++row)
359 if (first == nrows())
362 row_type last = nrows() - 1;
363 for (; last != 0; --last)
366 // add equation numbers
367 b.pushItem(pit, docstring(), output_active);
369 b.argumentItem(bformat(from_ascii("(%1$s-%2$s)"),
370 numbers_[first], numbers_[last]));
371 for (row_type row = 0; row != nrows(); ++row) {
375 label_[row]->addToToc(pit, output_active, utype, backend);
376 docstring label = nicelabel(row);
378 // this is the only equation
379 b.argumentItem(label);
381 // insert as sub-items
382 b.pushItem(pit, label, output_active);
390 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
392 if (previewState(&cur.bv())) {
396 return InsetMathNest::editXY(cur, x, y);
400 InsetMath::mode_type InsetMathHull::currentMode() const
404 return UNDECIDED_MODE;
406 // definitely math mode ...
426 // FIXME: InsetMathGrid should be changed to let the real column alignment be
427 // given by a virtual method like displayColAlign, because the values produced
428 // by defaultColAlign can be invalidated by lfuns such as add-column. For the
429 // moment the values produced by defaultColAlign are not used, notably because
430 // alignment is not implemented in the LyXHTML output.
431 char InsetMathHull::defaultColAlign(col_type col)
433 return colAlign(type_, col, buffer().params());
437 char InsetMathHull::displayColAlign(idx_type idx) const
441 row_type const r = row(idx);
444 if (r == nrows() - 1)
455 return colAlign(type_, col(idx), buffer().params());
459 return InsetMathGrid::displayColAlign(idx);
463 int InsetMathHull::displayColSpace(col_type col) const
465 return colSpace(type_, col);
469 // FIXME: same comment as for defaultColAlign applies.
470 int InsetMathHull::defaultColSpace(col_type col)
472 return colSpace(type_, col);
476 string InsetMathHull::standardFont() const
482 return "lyxnochange";
489 ColorCode InsetMathHull::standardColor() const
494 return Color_foreground;
502 bool InsetMathHull::previewState(const BufferView *const bv) const
504 if (!editing(bv) && RenderPreview::previewMath()
505 && type_ != hullRegexp)
507 graphics::PreviewImage const * pimage =
508 preview_->getPreviewImage(bv->buffer());
509 return pimage && pimage->image();
516 const int ERROR_FRAME_WIDTH = 2;
518 bool previewTooSmall(MetricsBase const & mb, Dimension const & dim)
520 // Value was hardcoded to 10 pixels
521 int const minval = mb.bv->zoomedPixels(10);
522 return dim.width() <= minval && dim.height() <= minval;
527 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
529 // true value in LaTeX is 12pt plus 3pt minus 9pt
530 // FIXME: even better would be to handle the short skip case.
531 int const display_margin = display() ? mi.base.inPixels(Length(12, Length::PT)) : 0;
533 if (previewState(mi.base.bv)) {
534 preview_->metrics(mi, dim);
535 if (previewTooSmall(mi.base, dim)) {
536 // preview image is too small
537 dim.wid += 2 * ERROR_FRAME_WIDTH;
538 dim.asc += 2 * ERROR_FRAME_WIDTH;
540 // insert a gap in front of the formula
541 // value was hardcoded to 1 pixel
542 dim.wid += mi.base.bv->zoomedPixels(1) ;
544 dim.asc += display_margin;
545 dim.des += display_margin;
551 Changer dummy1 = mi.base.changeFontSet(standardFont());
552 Changer dummy2 = mi.base.font.changeStyle(display() ? LM_ST_DISPLAY
555 // let the cells adjust themselves
556 InsetMathGrid::metrics(mi, dim);
559 dim.asc += display_margin;
560 dim.des += display_margin;
563 if (numberedType()) {
564 Changer dummy = mi.base.changeFontSet("mathrm");
566 for (row_type row = 0; row < nrows(); ++row)
567 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
570 // Value was hardcoded to 30 pixels
571 dim.wid += mi.base.bv->zoomedPixels(30) + l;
574 // reserve some space for marker.
579 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
581 BufferView const * const bv = pi.base.bv;
582 if (previewState(bv)) {
583 Dimension const dim = dimension(*pi.base.bv);
584 if (previewTooSmall(pi.base, dim))
586 return graphics::PreviewLoader::backgroundColor();
592 void InsetMathHull::drawMarkers(PainterInfo & pi, int x, int y) const
594 ColorCode pen_color = mouseHovered(pi.base.bv) || editing(pi.base.bv)?
595 Color_mathframe : Color_mathcorners;
596 // If the corners have the same color as the background, do not paint them.
597 if (lcolor.getX11Name(Color_mathbg) == lcolor.getX11Name(pen_color))
600 Inset::drawMarkers(pi, x, y);
601 Dimension const dim = dimension(*pi.base.bv);
602 int const t = x + dim.width() - 1;
603 int const a = y - dim.ascent();
604 pi.pain.line(x, a + 3, x, a, pen_color);
605 pi.pain.line(t, a + 3, t, a, pen_color);
606 pi.pain.line(x, a, x + 3, a, pen_color);
607 pi.pain.line(t - 3, a, t, a, pen_color);
611 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
613 Dimension const dim = dimension(*pi.base.bv);
614 if (previewTooSmall(pi.base, dim)) {
615 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
616 dim.wid, dim.asc + dim.des, backgroundColor(pi));
619 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
620 dim.asc + dim.des - 1, pi.backgroundColor(this));
624 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
626 BufferView const * const bv = pi.base.bv;
627 Dimension const dim = dimension(*bv);
629 if (type_ == hullRegexp)
630 pi.pain.rectangle(x + 2, y - dim.ascent() + 1,
631 dim.width() - 3, dim.height() - 2, Color_regexpframe);
633 if (previewState(bv)) {
634 // Do not draw change tracking cue if taken care of by RowPainter
636 Changer dummy = !canPaintChange(*bv) ? make_change(pi.change_, Change())
638 if (previewTooSmall(pi.base, dim)) {
639 // we have an extra frame
640 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
642 // one pixel gap in front
643 // value was hardcoded to 1 pixel
644 int const gap = pi.base.bv->zoomedPixels(1) ;
645 preview_->draw(pi, x + gap, y);
650 ColorCode color = pi.selected && lyxrc.use_system_colors
651 ? Color_selectiontext : standardColor();
652 bool const really_change_color = pi.base.font.color() == Color_none;
653 Changer dummy0 = really_change_color ? pi.base.font.changeColor(color)
655 Changer dummy1 = pi.base.changeFontSet(standardFont());
656 Changer dummy2 = pi.base.font.changeStyle(display() ? LM_ST_DISPLAY
660 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
661 if (numberedType() && math_number == BufferParams::LEFT) {
662 Changer dummy = pi.base.changeFontSet("mathrm");
664 for (row_type row = 0; row < nrows(); ++row)
665 l = max(l, mathed_string_width(pi.base.font, nicelabel(row)));
668 // Value was hardcoded to 30 pixels
669 xmath += pi.base.bv->zoomedPixels(30) + l;
672 InsetMathGrid::draw(pi, xmath + 1, y);
673 drawMarkers(pi, x, y);
675 if (numberedType()) {
676 Changer dummy = pi.base.changeFontSet("mathrm");
677 for (row_type row = 0; row < nrows(); ++row) {
678 int const yy = y + rowinfo_[row].offset_;
679 docstring const nl = nicelabel(row);
680 if (math_number == BufferParams::LEFT)
683 int l = mathed_string_width(pi.base.font, nl);
684 pi.draw(x + dim.wid - l, yy, nl);
689 // drawing change line
690 if (canPaintChange(*bv))
691 pi.change_.paintCue(pi, x + 1, y + 1 - dim.asc,
692 x + dim.wid, y + dim.des);
696 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
699 InsetMathGrid::metricsT(mi, dim);
702 otexrowstream ots(os);
703 WriteStream wi(ots, false, true, WriteStream::wsDefault);
705 dim.wid = os.str().size();
712 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
715 InsetMathGrid::drawT(pain, x, y);
718 otexrowstream ots(os);
719 WriteStream wi(ots, false, true, WriteStream::wsDefault);
721 pain.draw(x, y, os.str().c_str());
726 static docstring latexString(InsetMathHull const & inset)
729 // This has to be static, because a preview snippet or a math
730 // macro containing math in text mode (such as $\text{$\phi$}$ or
731 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
732 // first time as a whole, and the second time only the inner math.
733 // In this last case inset.buffer() would be invalid.
734 static Encoding const * encoding = 0;
735 if (inset.isBufferValid())
736 encoding = &(inset.buffer().params().encoding());
737 otexrowstream ots(ls);
738 WriteStream wi(ots, false, true, WriteStream::wsPreview, encoding);
744 void InsetMathHull::initUnicodeMath() const
746 // Trigger classification of the unicode symbols in this inset
747 docstring const dummy = latexString(*this);
751 void InsetMathHull::addPreview(DocIterator const & inset_pos,
752 graphics::PreviewLoader & /*ploader*/) const
754 if (RenderPreview::previewMath()) {
755 preparePreview(inset_pos);
760 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
761 MacroNameSet & macros, MacroNameSet & defs) const
763 MacroNameSet::iterator const end = macros.end();
765 for (size_t i = 0; i < md.size(); ++i) {
766 InsetMathMacro const * mi = md[i].nucleus()->asMacro();
767 InsetMathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
768 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
769 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
770 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
771 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
773 // Look for macros in the arguments of this macro.
774 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
775 usedMacros(mi->cell(idx), pos, macros, defs);
776 // Make sure this is a macro defined in the document
777 // (as we also spot the macros in the symbols file)
778 // or that we have not already accounted for it.
779 docstring const name = mi->name();
780 if (macros.find(name) == end)
783 // Look for macros in the definition of this macro.
784 MathData ar(pos.buffer());
785 MacroData const * data =
786 pos.buffer()->getMacro(name, pos, true);
788 odocstringstream macro_def;
789 data->write(macro_def, true);
791 defs.insert(macro_def.str());
792 asArray(data->definition(), ar);
794 usedMacros(ar, pos, macros, defs);
796 MathData ar(pos.buffer());
797 asArray(mt->definition(), ar);
798 usedMacros(ar, pos, macros, defs);
800 if (!si->nuc().empty())
801 usedMacros(si->nuc(), pos, macros, defs);
803 usedMacros(si->down(), pos, macros, defs);
805 usedMacros(si->up(), pos, macros, defs);
806 } else if (fi || gi) {
807 idx_type nidx = fi ? fi->nargs() : gi->nargs();
808 for (idx_type idx = 0; idx < nidx; ++idx)
809 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
812 usedMacros(ni->cell(0), pos, macros, defs);
818 void InsetMathHull::preparePreview(DocIterator const & pos,
819 bool forexport) const
821 // there is no need to do all the macro stuff if we're not
822 // actually going to generate the preview.
823 if (!RenderPreview::previewMath() && !forexport)
826 Buffer const * buffer = pos.buffer();
828 // collect macros at this position
830 buffer->listMacroNames(macros);
832 // collect definitions only for the macros used in this inset
834 for (idx_type idx = 0; idx < nargs(); ++idx)
835 usedMacros(cell(idx), pos, macros, defs);
837 docstring macro_preamble;
838 for (auto const & defvar : defs)
839 macro_preamble.append(defvar);
841 // set the font series and size for this snippet
842 DocIterator dit = pos.getInnerText();
843 Paragraph const & par = dit.paragraph();
844 Font font = par.getFontSettings(buffer->params(), dit.pos());
845 font.fontInfo().realize(par.layout().font);
846 string const lsize = font.latexSize();
849 if (font.fontInfo().series() == BOLD_SERIES) {
850 setfont += from_ascii("\\textbf{");
853 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
854 setfont += from_ascii("\\" + lsize + '\n');
857 if (forexport && haveNumbers()) {
858 docstring eqstr = from_ascii("equation");
859 CounterMap::const_iterator it = counter_map.find(eqstr);
860 if (it != counter_map.end()) {
861 int num = it->second;
863 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
864 '{' + convert<docstring>(num) + '}' + '\n';
866 for (size_t i = 0; i != numcnts; ++i) {
867 docstring cnt = from_ascii(counters_to_save[i]);
868 it = counter_map.find(cnt);
869 if (it == counter_map.end())
871 int num = it->second;
873 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
874 '{' + convert<docstring>(num) + '}';
877 docstring const snippet = macro_preamble + setfont + setcnt
878 + latexString(*this) + endfont;
879 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
880 preview_->addPreview(snippet, *buffer, forexport);
884 void InsetMathHull::reloadPreview(DocIterator const & pos) const
887 preview_->startLoading(*pos.buffer());
891 void InsetMathHull::loadPreview(DocIterator const & pos) const
893 bool const forexport = true;
894 preparePreview(pos, forexport);
895 preview_->startLoading(*pos.buffer(), forexport);
899 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
901 if (RenderPreview::previewMath()) {
903 cur.screenUpdateFlags(Update::Force);
909 docstring InsetMathHull::label(row_type row) const
911 LASSERT(row < nrows(), return docstring());
912 if (InsetLabel * il = label_[row])
913 return il->screenLabel();
918 void InsetMathHull::label(row_type row, docstring const & label)
920 //lyxerr << "setting label '" << label << "' for row " << row << endl;
924 label_[row] = dummy_pointer;
927 label_[row]->updateLabelAndRefs(label);
929 label_[row]->setParam("name", label);
933 InsetCommandParams p(LABEL_CODE);
935 label_[row] = new InsetLabel(buffer_, p);
937 label_[row]->setBuffer(buffer());
941 void InsetMathHull::numbered(row_type row, Numbered num)
943 numbered_[row] = num;
944 if (!numbered(row) && label_[row]) {
951 bool InsetMathHull::numbered(row_type row) const
953 return numbered_[row] == NUMBER;
957 bool InsetMathHull::ams() const
977 for (size_t row = 0; row < numbered_.size(); ++row)
978 if (numbered_[row] == NOTAG)
984 bool InsetMathHull::outerDisplay() const
1007 Inset::DisplayType InsetMathHull::display() const
1024 if (buffer().params().is_math_indent)
1034 int InsetMathHull::indent(BufferView const & bv) const
1036 // FIXME: set this in the textclass. This value is what the article class uses.
1037 static Length default_indent(2.5, Length::EM);
1038 if (display() != Inline && buffer().params().is_math_indent) {
1039 Length const & len = buffer().params().getMathIndent();
1041 return bv.inPixels(default_indent);
1043 return bv.inPixels(len);
1045 return Inset::indent(bv);
1049 bool InsetMathHull::numberedType() const
1068 for (row_type row = 0; row < nrows(); ++row)
1075 void InsetMathHull::validate(LaTeXFeatures & features) const
1077 if (features.runparams().isLaTeX()) {
1079 features.require("amsmath");
1081 if (type_ == hullRegexp) {
1082 features.require("color");
1083 docstring frcol = from_utf8(lcolor.getLaTeXName(Color_regexpframe));
1084 docstring bgcol = from_ascii("white");
1085 features.addPreambleSnippet(
1086 "\\newcommand{\\regexp}[1]{\\fcolorbox{"
1088 + bgcol + "}{\\ensuremath{\\mathtt{#1}}}}");
1089 features.addPreambleSnippet(
1090 from_ascii("\\newcommand{\\endregexp}{}"));
1091 } else if (outerDisplay() && features.inDeletedInset()
1092 && !features.mustProvide("ct-dvipost")) {
1093 features.require("ct-tikz-math-sout");
1096 // Validation is necessary only if not using AMS math.
1097 // To be safe, we will always run mathedvalidate.
1098 //if (features.amsstyle)
1101 //features.binom = true;
1102 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
1103 // it would be better to do this elsewhere, but we can't validate in
1104 // InsetMathMatrix and we have no way, outside MathExtern, to know if
1105 // we even have any matrices.
1106 features.addCSSSnippet(
1107 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
1108 "table.matrix td{padding: 0.25px;}\n"
1109 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
1110 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
1112 InsetMathGrid::validate(features);
1116 void InsetMathHull::header_write(WriteStream & os) const
1118 bool n = numberedType();
1129 if (cell(0).empty())
1134 writeMathdisplayPreamble(os);
1138 os << "\\begin{equation" << star(n) << "}\n";
1148 writeMathdisplayPreamble(os);
1151 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1158 os << "\\begin{" << hullName(type_) << star(n) << '}'
1159 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1165 os << "\\begin{" << hullName(type_) << '}'
1166 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1176 os << "\\begin{unknown" << star(n) << "}\n";
1182 void InsetMathHull::footer_write(WriteStream & os) const
1184 bool n = numberedType();
1201 os << "\\end{equation" << star(n) << "}\n";
1204 writeMathdisplayPostamble(os);
1214 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1215 writeMathdisplayPostamble(os);
1222 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1228 os << "\\end{" << hullName(type_) << "}\n";
1232 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1233 os << "\\endregexp{}}";
1239 os << "\\end{unknown" << star(n) << "}\n";
1245 bool InsetMathHull::allowsTabularFeatures() const
1268 bool InsetMathHull::rowChangeOK() const
1271 type_ == hullEqnArray || type_ == hullAlign ||
1272 type_ == hullFlAlign || type_ == hullAlignAt ||
1273 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1274 type_ == hullGather || type_ == hullMultline;
1278 bool InsetMathHull::colChangeOK() const
1281 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1282 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1286 void InsetMathHull::addRow(row_type row)
1291 bool numbered = numberedType();
1292 // Move the number and raw pointer, do not call label() (bug 7511)
1293 InsetLabel * label = dummy_pointer;
1294 docstring number = empty_docstring();
1295 if (type_ == hullMultline) {
1296 if (row + 1 == nrows()) {
1297 numbered_[row] = NONUMBER;
1298 swap(label, label_[row]);
1299 swap(number, numbers_[row]);
1304 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1305 numbers_.insert(numbers_.begin() + row + 1, number);
1306 label_.insert(label_.begin() + row + 1, label);
1307 InsetMathGrid::addRow(row);
1311 void InsetMathHull::swapRow(row_type row)
1315 if (row + 1 == nrows())
1317 swap(numbered_[row], numbered_[row + 1]);
1318 swap(numbers_[row], numbers_[row + 1]);
1319 swap(label_[row], label_[row + 1]);
1320 InsetMathGrid::swapRow(row);
1324 void InsetMathHull::delRow(row_type row)
1326 if (nrows() <= 1 || !rowChangeOK())
1328 if (row + 1 == nrows() && type_ == hullMultline) {
1329 swap(numbered_[row - 1], numbered_[row]);
1330 swap(numbers_[row - 1], numbers_[row]);
1331 swap(label_[row - 1], label_[row]);
1332 InsetMathGrid::delRow(row);
1335 InsetMathGrid::delRow(row);
1336 // The last dummy row has no number info nor a label.
1337 // Test nrows() + 1 because we have already erased the row.
1338 if (row == nrows() + 1)
1340 numbered_.erase(numbered_.begin() + row);
1341 numbers_.erase(numbers_.begin() + row);
1343 label_.erase(label_.begin() + row);
1347 void InsetMathHull::addCol(col_type col)
1351 InsetMathGrid::addCol(col);
1355 void InsetMathHull::delCol(col_type col)
1357 if (ncols() <= 1 || !colChangeOK())
1359 InsetMathGrid::delCol(col);
1363 docstring InsetMathHull::nicelabel(row_type row) const
1367 docstring const & val = numbers_[row];
1369 return '(' + val + ')';
1370 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1374 void InsetMathHull::glueall(HullType type)
1377 for (idx_type i = 0; i < nargs(); ++i)
1379 InsetLabel * label = 0;
1380 if (type == hullEquation) {
1381 // preserve first non-empty label
1382 for (row_type row = 0; row < nrows(); ++row) {
1384 label = label_[row];
1390 *this = InsetMathHull(buffer_, hullSimple);
1397 void InsetMathHull::splitTo2Cols()
1399 LASSERT(ncols() == 1, return);
1400 InsetMathGrid::addCol(1);
1401 for (row_type row = 0; row < nrows(); ++row) {
1402 idx_type const i = 2 * row;
1403 pos_type pos = firstRelOp(cell(i));
1404 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1405 cell(i).erase(pos, cell(i).size());
1410 void InsetMathHull::splitTo3Cols()
1412 LASSERT(ncols() < 3, return);
1415 InsetMathGrid::addCol(2);
1416 for (row_type row = 0; row < nrows(); ++row) {
1417 idx_type const i = 3 * row + 1;
1418 if (!cell(i).empty()) {
1419 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1420 cell(i).erase(1, cell(i).size());
1426 void InsetMathHull::changeCols(col_type cols)
1428 if (ncols() == cols)
1430 else if (ncols() < cols) {
1436 while (ncols() < cols)
1437 InsetMathGrid::addCol(ncols());
1443 for (row_type row = 0; row < nrows(); ++row) {
1444 idx_type const i = row * ncols();
1445 for (col_type col = cols; col < ncols(); ++col) {
1446 cell(i + cols - 1).append(cell(i + col));
1450 while (ncols() > cols) {
1451 InsetMathGrid::delCol(ncols() - 1);
1456 HullType InsetMathHull::getType() const
1462 void InsetMathHull::setType(HullType type)
1469 bool InsetMathHull::isMutable(HullType type)
1493 void InsetMathHull::mutate(HullType newtype)
1495 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1497 if (newtype == type_)
1500 // This guards the algorithm below it, which is designed with certain types
1502 if (!isMutable(newtype) || !isMutable(type_)) {
1503 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1504 << "' to '" << to_utf8(hullName(newtype))
1505 << "' not implemented" << endl;
1509 // we try to move along the chain
1510 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1512 // +-------------------------------------+
1513 // we use eqnarray as intermediate type for mutations that are not
1514 // directly supported because it handles labels and numbering for
1519 setType(hullSimple);
1525 if (newtype == hullNone) {
1529 setType(hullEquation);
1530 numbered(0, label_[0] ? true : false);
1539 setType(hullSimple);
1544 // split it "nicely" on the first relop
1546 setType(hullEqnArray);
1554 // split it "nicely"
1589 setType(hullEqnArray);
1598 for (row_type row = 0; row < nrows(); ++row)
1599 numbered(row, false);
1609 for (row_type row = 0; row < nrows(); ++row)
1610 numbered(row, false);
1617 setType(hullEqnArray);
1647 for (row_type row = 0; row < nrows(); ++row)
1648 numbered(row, false);
1652 // first we mutate to EqnArray
1654 setType(hullEqnArray);
1661 // we passed the guard so we should not be here
1662 LYXERR0("Mutation not implemented, but should have been.");
1663 LASSERT(false, return);
1669 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1670 bool last_eoln) const
1673 if (numberedType()) {
1674 if (label_[row] && numbered(row)) {
1675 docstring const name =
1676 latex ? escape(label_[row]->getParam("name"))
1677 : label_[row]->getParam("name");
1678 res += "\\label{" + name + '}';
1680 if (type_ != hullMultline) {
1681 if (numbered_[row] == NONUMBER)
1682 res += "\\nonumber ";
1683 else if (numbered_[row] == NOTAG)
1687 // Never add \\ on the last empty line of eqnarray and friends
1689 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1692 void InsetMathHull::write(WriteStream & os) const
1694 ModeSpecifier specifier(os, MATH_MODE);
1696 InsetMathGrid::write(os);
1701 void InsetMathHull::normalize(NormalStream & os) const
1703 os << "[formula " << hullName(type_) << ' ';
1704 InsetMathGrid::normalize(os);
1709 void InsetMathHull::infoize(odocstream & os) const
1711 os << bformat(_("Type: %1$s"), hullName(type_));
1715 void InsetMathHull::check() const
1717 LATTEST(numbered_.size() == nrows());
1718 LATTEST(numbers_.size() == nrows());
1719 LATTEST(label_.size() == nrows());
1723 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1725 //FIXME: sort out whether we want std::string or docstring for those
1726 string const lang = func.getArg(0);
1727 docstring extra = from_utf8(func.getArg(1));
1729 extra = from_ascii("noextra");
1731 // replace selection with result of computation
1732 if (reduceSelectionToOneCell(cur)) {
1734 asArray(grabAndEraseSelection(cur), ar);
1735 lyxerr << "use selection: " << ar << endl;
1736 cur.insert(pipeThroughExtern(lang, extra, ar));
1740 // only inline, display or eqnarray math is allowed
1741 switch (getType()) {
1747 frontend::Alert::warning(_("Bad math environment"),
1748 _("Computation cannot be performed for AMS "
1749 "math environments.\nChange the math "
1750 "formula type and try again."));
1755 eq.push_back(MathAtom(new InsetMathChar('=')));
1757 // go to first item in line
1758 cur.idx() -= cur.idx() % ncols();
1761 if (getType() == hullSimple) {
1762 size_type pos = cur.cell().find_last(eq);
1764 if (pos == cur.cell().size()) {
1766 lyxerr << "use whole cell: " << ar << endl;
1768 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1769 lyxerr << "use partial cell form pos: " << pos << endl;
1771 cur.cell().append(eq);
1772 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1773 cur.pos() = cur.lastpos();
1777 if (getType() == hullEquation) {
1778 lyxerr << "use equation inset" << endl;
1779 mutate(hullEqnArray);
1780 MathData & ar = cur.cell();
1781 lyxerr << "use cell: " << ar << endl;
1785 cur.cell() = pipeThroughExtern(lang, extra, ar);
1786 // move to end of line
1787 cur.pos() = cur.lastpos();
1792 lyxerr << "use eqnarray" << endl;
1793 cur.idx() += 2 - cur.idx() % ncols();
1795 MathData ar = cur.cell();
1796 lyxerr << "use cell: " << ar << endl;
1797 // FIXME: temporarily disabled
1803 cur.cell() = pipeThroughExtern(lang, extra, ar);
1804 cur.pos() = cur.lastpos();
1809 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1811 //lyxerr << "action: " << cmd.action() << endl;
1812 switch (cmd.action()) {
1814 case LFUN_FINISHED_BACKWARD:
1815 case LFUN_FINISHED_FORWARD:
1816 case LFUN_FINISHED_RIGHT:
1817 case LFUN_FINISHED_LEFT:
1818 //lyxerr << "action: " << cmd.action() << endl;
1819 InsetMathGrid::doDispatch(cur, cmd);
1822 case LFUN_PARAGRAPH_BREAK:
1823 // just swallow this
1826 case LFUN_NEWLINE_INSERT:
1827 // some magic for the common case
1828 if (type_ == hullSimple || type_ == hullEquation) {
1829 cur.recordUndoInset();
1831 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1832 mutate(align ? hullAlign : hullEqnArray);
1833 // mutate() may change labels and such.
1834 cur.forceBufferUpdate();
1835 cur.idx() = nrows() * ncols() - 1;
1836 cur.pos() = cur.lastpos();
1838 InsetMathGrid::doDispatch(cur, cmd);
1841 case LFUN_MATH_NUMBER_TOGGLE: {
1842 //lyxerr << "toggling all numbers" << endl;
1843 cur.recordUndoInset();
1844 bool old = numberedType();
1845 if (type_ == hullMultline)
1846 numbered(nrows() - 1, !old);
1848 for (row_type row = 0; row < nrows(); ++row)
1849 numbered(row, !old);
1851 cur.message(old ? _("No number") : _("Number"));
1852 cur.forceBufferUpdate();
1856 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1857 cur.recordUndoInset();
1858 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1859 bool old = numbered(r);
1860 cur.message(old ? _("No number") : _("Number"));
1862 cur.forceBufferUpdate();
1866 case LFUN_LABEL_INSERT: {
1867 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1868 docstring old_label = label(r);
1869 docstring const default_label = from_ascii("eq:");
1870 if (old_label.empty())
1871 old_label = default_label;
1873 InsetCommandParams p(LABEL_CODE);
1874 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1875 string const data = InsetCommand::params2string(p);
1877 if (cmd.argument().empty())
1878 cur.bv().showDialog("label", data);
1880 FuncRequest fr(LFUN_INSET_INSERT, data);
1886 case LFUN_LABEL_COPY_AS_REFERENCE: {
1888 if (cmd.argument().empty() && &cur.inset() == this)
1889 // if there is no argument and we're inside math, we retrieve
1890 // the row number from the cursor position.
1891 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1893 // if there is an argument, find the corresponding label, else
1894 // check whether there is at least one label.
1895 for (row = 0; row != nrows(); ++row)
1896 if (numbered(row) && label_[row]
1897 && (cmd.argument().empty() || label(row) == cmd.argument()))
1904 InsetCommandParams p(REF_CODE, "ref");
1905 p["reference"] = label(row);
1906 cap::clearSelection();
1907 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1911 case LFUN_WORD_DELETE_FORWARD:
1912 case LFUN_CHAR_DELETE_FORWARD:
1913 if (col(cur.idx()) + 1 == ncols()
1914 && cur.pos() == cur.lastpos()
1915 && !cur.selection()) {
1916 if (!label(row(cur.idx())).empty()) {
1917 cur.recordUndoInset();
1918 label(row(cur.idx()), docstring());
1919 } else if (numbered(row(cur.idx()))) {
1920 cur.recordUndoInset();
1921 numbered(row(cur.idx()), false);
1922 cur.forceBufferUpdate();
1924 InsetMathGrid::doDispatch(cur, cmd);
1928 InsetMathGrid::doDispatch(cur, cmd);
1933 case LFUN_INSET_INSERT: {
1934 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1935 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1936 string const name = cmd.getArg(0);
1937 if (name == "label") {
1938 InsetCommandParams p(LABEL_CODE);
1939 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1940 docstring str = p["name"];
1941 cur.recordUndoInset();
1942 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1946 docstring old = label(r);
1949 // The label will take care of the reference update.
1953 // Newly created inset so initialize it.
1954 label_[r]->initView();
1957 cur.forceBufferUpdate();
1960 InsetMathGrid::doDispatch(cur, cmd);
1964 case LFUN_MATH_EXTERN:
1965 cur.recordUndoInset();
1969 case LFUN_MATH_MUTATE: {
1970 cur.recordUndoInset();
1971 row_type row = cur.row();
1972 col_type col = cur.col();
1973 mutate(hullType(cmd.argument()));
1974 cur.idx() = row * ncols() + col;
1975 if (cur.idx() > cur.lastidx()) {
1976 cur.idx() = cur.lastidx();
1977 cur.pos() = cur.lastpos();
1979 if (cur.pos() > cur.lastpos())
1980 cur.pos() = cur.lastpos();
1982 cur.forceBufferUpdate();
1983 // FIXME: find some more clever handling of the selection,
1984 // i.e. preserve it.
1985 cur.clearSelection();
1986 //cur.dispatched(FINISHED);
1990 case LFUN_MATH_DISPLAY: {
1991 cur.recordUndoInset();
1992 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1993 // if the cursor is in a cell that got merged, move it to
1994 // start of the hull inset.
1995 if (cur.idx() > 0) {
1999 if (cur.pos() > cur.lastpos())
2000 cur.pos() = cur.lastpos();
2005 case LFUN_TABULAR_FEATURE:
2006 if (!allowsTabularFeatures())
2009 InsetMathGrid::doDispatch(cur, cmd);
2013 InsetMathGrid::doDispatch(cur, cmd);
2021 bool allowDisplayMath(Cursor const & cur)
2023 LATTEST(cur.depth() > 1);
2024 Cursor tmpcur = cur;
2027 FuncRequest cmd(LFUN_MATH_DISPLAY);
2028 return tmpcur.getStatus(cmd, status) && status.enabled();
2034 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
2035 FuncStatus & status) const
2037 switch (cmd.action()) {
2038 case LFUN_FINISHED_BACKWARD:
2039 case LFUN_FINISHED_FORWARD:
2040 case LFUN_FINISHED_RIGHT:
2041 case LFUN_FINISHED_LEFT:
2044 case LFUN_NEWLINE_INSERT:
2045 case LFUN_MATH_EXTERN:
2047 status.setEnabled(true);
2050 // we never allow this in math, and we want to bind enter
2051 // to another actions in command-alternatives
2052 case LFUN_PARAGRAPH_BREAK:
2053 status.setEnabled(false);
2055 case LFUN_MATH_MUTATE: {
2056 HullType const ht = hullType(cmd.argument());
2057 status.setOnOff(type_ == ht);
2058 status.setEnabled(isMutable(ht) && isMutable(type_));
2060 if (ht != hullSimple && status.enabled())
2061 status.setEnabled(allowDisplayMath(cur));
2064 case LFUN_MATH_DISPLAY: {
2065 status.setEnabled(display() != Inline || allowDisplayMath(cur));
2066 status.setOnOff(display() != Inline);
2070 case LFUN_MATH_NUMBER_TOGGLE:
2071 // FIXME: what is the right test, this or the one of
2073 status.setEnabled(display() != Inline);
2074 status.setOnOff(numberedType());
2077 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
2078 // FIXME: what is the right test, this or the one of
2080 bool const enable = (type_ == hullMultline)
2081 ? (nrows() - 1 == cur.row())
2082 : display() != Inline;
2083 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2084 status.setEnabled(enable);
2085 status.setOnOff(enable && numbered(r));
2089 case LFUN_LABEL_INSERT:
2090 status.setEnabled(type_ != hullSimple);
2093 case LFUN_LABEL_COPY_AS_REFERENCE: {
2094 bool enabled = false;
2095 if (cmd.argument().empty() && &cur.inset() == this) {
2096 // if there is no argument and we're inside math, we retrieve
2097 // the row number from the cursor position.
2098 row_type row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2099 enabled = numberedType() && label_[row] && numbered(row);
2101 // if there is an argument, find the corresponding label, else
2102 // check whether there is at least one label.
2103 for (row_type row = 0; row != nrows(); ++row) {
2104 if (numbered(row) && label_[row] &&
2105 (cmd.argument().empty() || label(row) == cmd.argument())) {
2111 status.setEnabled(enabled);
2115 case LFUN_INSET_INSERT:
2116 if (cmd.getArg(0) == "label") {
2117 status.setEnabled(type_ != hullSimple);
2120 return InsetMathGrid::getStatus(cur, cmd, status);
2122 case LFUN_TABULAR_FEATURE: {
2123 if (!allowsTabularFeatures())
2125 string s = cmd.getArg(0);
2127 && (s == "append-row"
2128 || s == "delete-row"
2129 || s == "copy-row")) {
2130 status.message(bformat(
2131 from_utf8(N_("Can't change number of rows in '%1$s'")),
2133 status.setEnabled(false);
2137 && (s == "append-column"
2138 || s == "delete-column"
2139 || s == "copy-column")) {
2140 status.message(bformat(
2141 from_utf8(N_("Can't change number of columns in '%1$s'")),
2143 status.setEnabled(false);
2146 if (s == "add-vline-left" || s == "add-vline-right") {
2147 status.message(bformat(
2148 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2150 status.setEnabled(false);
2153 if (s == "valign-top" || s == "valign-middle"
2154 || s == "valign-bottom" || s == "align-left"
2155 || s == "align-center" || s == "align-right") {
2156 status.setEnabled(false);
2159 return InsetMathGrid::getStatus(cur, cmd, status);
2163 return InsetMathGrid::getStatus(cur, cmd, status);
2168 int InsetMathHull::leftMargin() const
2170 return (getType() == hullSimple) ? 0 : InsetMathGrid::leftMargin();
2174 int InsetMathHull::rightMargin() const
2176 return (getType() == hullSimple) ? 0 : InsetMathGrid::rightMargin();
2180 int InsetMathHull::border() const
2182 return (getType() == hullSimple) ? 0 : InsetMathGrid::border();
2186 /////////////////////////////////////////////////////////////////////
2190 // simply scrap this function if you want
2191 void InsetMathHull::mutateToText()
2194 // translate to latex
2196 latex(os, false, false);
2197 string str = os.str();
2200 Text * lt = view_->cursor().innerText();
2201 string::const_iterator cit = str.begin();
2202 string::const_iterator end = str.end();
2203 for (; cit != end; ++cit)
2204 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2207 //dispatch(LFUN_ESCAPE);
2212 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2213 docstring const & font)
2215 // this whole function is a hack and won't work for incremental font
2218 if (cur.inset().asInsetMath()->name() == font)
2219 cur.handleFont(to_utf8(font));
2221 cur.handleNest(createInsetMath(font, cur.buffer()));
2227 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2232 font.fromString(to_utf8(arg), b);
2233 if (font.fontInfo().color() != Color_inherit) {
2234 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2240 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2242 InsetMathNest::edit(cur, front, entry_from);
2243 // The inset formula dimension is not necessarily the same as the
2244 // one of the instant preview image, so we have to indicate to the
2245 // BufferView that a metrics update is needed.
2246 cur.screenUpdateFlags(Update::Force);
2250 /////////////////////////////////////////////////////////////////////
2254 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2257 // FIXME: completely broken
2258 static InsetMathHull * lastformula = 0;
2259 static CursorBase current = DocIterator(ibegin(nucleus()));
2261 static string laststr;
2263 if (lastformula != this || laststr != str) {
2264 //lyxerr << "reset lastformula to " << this << endl;
2267 current = ibegin(nucleus());
2269 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2273 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2275 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2276 CursorSlice & top = it.back();
2277 MathData const & a = top.asInsetMath()->cell(top.idx_);
2278 if (a.matchpart(ar, top.pos_)) {
2279 bv->cursor().setSelection(it, ar.size());
2281 top.pos_ += ar.size();
2287 //lyxerr << "not found!" << endl;
2294 void InsetMathHull::write(ostream & os) const
2296 odocstringstream oss;
2297 otexrowstream ots(oss);
2298 WriteStream wi(ots, false, false, WriteStream::wsDefault);
2301 os << to_utf8(oss.str());
2305 void InsetMathHull::read(Lexer & lex)
2308 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2309 operator=(*at->asHullInset());
2313 bool InsetMathHull::readQuiet(Lexer & lex)
2316 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2318 operator=(*at->asHullInset());
2323 int InsetMathHull::plaintext(odocstringstream & os,
2324 OutputParams const & op, size_t max_length) const
2326 // Try enabling this now that there is a flag as requested at #2275.
2327 if (buffer().isExporting() && display()) {
2331 TextPainter tpain(dim.width(), dim.height());
2332 drawT(tpain, 0, dim.ascent());
2334 // reset metrics cache to "real" values
2336 return tpain.textheight();
2339 odocstringstream oss;
2340 otexrowstream ots(oss);
2341 Encoding const * const enc = encodings.fromLyXName("utf8");
2342 WriteStream wi(ots, false, true, WriteStream::wsDefault, enc);
2345 if (type_ == hullRegexp)
2348 for (row_type r = 0; r < nrows(); ++r) {
2349 for (col_type c = 0; c < ncols(); ++c)
2350 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2351 // if it's for the TOC, we write just the first line
2352 // and do not include the newline.
2353 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2355 if (r < nrows() - 1)
2359 docstring const str = oss.str();
2365 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
2370 if (getType() == hullSimple)
2371 name = from_ascii("inlineequation");
2373 name = from_ascii("informalequation");
2375 docstring bname = name;
2376 if (!label(0).empty())
2377 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
2379 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
2381 odocstringstream ls;
2383 if (runparams.flavor == OutputParams::XML) {
2384 ms << MTag("alt role='tex' ");
2385 // Workaround for db2latex: db2latex always includes equations with
2386 // \ensuremath{} or \begin{display}\end{display}
2387 // so we strip LyX' math environment
2388 WriteStream wi(ols, false, false, WriteStream::wsDefault, runparams.encoding);
2389 InsetMathGrid::write(wi);
2390 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2395 InsetMathGrid::mathmlize(ms);
2398 ms << MTag("alt role='tex'");
2399 latex(ols, runparams);
2400 res = ols.texrow().rows();
2401 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2405 ms << from_ascii("<graphic fileref=\"eqn/");
2406 if (!label(0).empty())
2407 ms << sgml::cleanID(buffer(), runparams, label(0));
2409 ms << sgml::uniqueID(from_ascii("anon"));
2411 if (runparams.flavor == OutputParams::XML)
2412 ms << from_ascii("\"/>");
2414 ms << from_ascii("\">");
2416 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2418 return ms.line() + res;
2422 bool InsetMathHull::haveNumbers() const
2424 bool havenumbers = false;
2425 // inline formulas are never numbered (bug 7351 part 3)
2426 if (getType() == hullSimple)
2428 for (size_t i = 0; i != numbered_.size(); ++i) {
2439 // We need to do something about alignment here.
2441 // This duplicates code from InsetMathGrid, but
2442 // we need access here to number information,
2443 // and we simply do not have that in InsetMathGrid.
2444 void InsetMathHull::htmlize(HtmlStream & os) const
2446 bool const havenumbers = haveNumbers();
2447 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2450 os << cell(index(0, 0));
2454 os << MTag("table", "class='mathtable'");
2455 for (row_type row = 0; row < nrows(); ++row) {
2457 for (col_type col = 0; col < ncols(); ++col) {
2459 os << cell(index(row, col));
2464 docstring const & num = numbers_[row];
2466 os << '(' << num << ')';
2471 os << ETag("table");
2475 // this duplicates code from InsetMathGrid, but
2476 // we need access here to number information,
2477 // and we simply do not have that in InsetMathGrid.
2478 void InsetMathHull::mathmlize(MathStream & os) const
2480 bool const havenumbers = haveNumbers();
2481 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2484 os << MTag("mtable");
2485 char const * const celltag = havetable ? "mtd" : "mrow";
2486 // FIXME There does not seem to be wide support at the moment
2487 // for mlabeledtr, so we have to use just mtr for now.
2488 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2489 char const * const rowtag = "mtr";
2490 for (row_type row = 0; row < nrows(); ++row) {
2493 for (col_type col = 0; col < ncols(); ++col) {
2495 << cell(index(row, col))
2501 docstring const & num = numbers_[row];
2503 os << '(' << num << ')';
2510 os << ETag("mtable");
2514 void InsetMathHull::mathAsLatex(WriteStream & os) const
2516 MathEnsurer ensurer(os, false);
2517 bool havenumbers = haveNumbers();
2518 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2521 os << cell(index(0, 0));
2525 os << "<table class='mathtable'>";
2526 for (row_type row = 0; row < nrows(); ++row) {
2528 for (col_type col = 0; col < ncols(); ++col) {
2529 os << "<td class='math'>";
2530 os << cell(index(row, col));
2535 docstring const & num = numbers_[row];
2537 os << '(' << num << ')';
2546 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2548 BufferParams::MathOutput const mathtype =
2549 buffer().masterBuffer()->params().html_math_output;
2551 bool success = false;
2553 // we output all the labels just at the beginning of the equation.
2554 // this should be fine.
2555 for (size_t i = 0; i != label_.size(); ++i) {
2556 InsetLabel const * const il = label_[i];
2562 // FIXME Eventually we would like to do this inset by inset.
2563 if (mathtype == BufferParams::MathML) {
2564 odocstringstream os;
2569 } catch (MathExportException const &) {}
2571 if (getType() == hullSimple)
2572 xs << html::StartTag("math",
2573 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2575 xs << html::StartTag("math",
2576 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2577 xs << XHTMLStream::ESCAPE_NONE
2579 << html::EndTag("math");
2581 } else if (mathtype == BufferParams::HTML) {
2582 odocstringstream os;
2587 } catch (MathExportException const &) {}
2589 string const tag = (getType() == hullSimple) ? "span" : "div";
2590 xs << html::StartTag(tag, "class='formula'", true)
2591 << XHTMLStream::ESCAPE_NONE
2593 << html::EndTag(tag);
2597 // what we actually want is this:
2599 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2601 // || mathtype == BufferParams::Images
2603 // but what follows is equivalent, since we'll enter only if either (a) we
2604 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2605 // aren't doing LaTeX.
2607 // so this is for Images.
2608 if (!success && mathtype != BufferParams::LaTeX) {
2609 graphics::PreviewImage const * pimage = 0;
2611 loadPreview(docit_);
2612 pimage = preview_->getPreviewImage(buffer());
2613 // FIXME Do we always have png?
2616 if (pimage || op.dryrun) {
2617 string const filename = pimage ? pimage->filename().onlyFileName()
2618 : "previewimage.png";
2620 // if we are not in the master buffer, then we need to see that the
2621 // generated image is copied there; otherwise, preview fails.
2622 Buffer const * mbuf = buffer().masterBuffer();
2623 if (mbuf != &buffer()) {
2624 string mbtmp = mbuf->temppath();
2625 FileName const mbufimg(support::addName(mbtmp, filename));
2626 pimage->filename().copyTo(mbufimg);
2628 // add the file to the list of files to be exported
2629 op.exportdata->addExternalFile("xhtml", pimage->filename());
2632 string const tag = (getType() == hullSimple) ? "span" : "div";
2634 << html::StartTag(tag, "style = \"text-align: center;\"")
2635 << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2636 << html::EndTag(tag)
2642 // so we'll pass this test if we've failed everything else, or
2643 // if mathtype was LaTeX, since we won't have entered any of the
2645 if (!success /* || mathtype != BufferParams::LaTeX */) {
2646 // Unfortunately, we cannot use latexString() because we do not want
2647 // $...$ or whatever.
2648 odocstringstream ls;
2649 otexrowstream ots(ls);
2650 WriteStream wi(ots, false, true, WriteStream::wsPreview);
2651 ModeSpecifier specifier(wi, MATH_MODE);
2653 docstring const latex = ls.str();
2655 // class='math' allows for use of jsMath
2656 // http://www.math.union.edu/~dpvc/jsMath/
2658 // probably should allow for some kind of customization here
2659 string const tag = (getType() == hullSimple) ? "span" : "div";
2660 xs << html::StartTag(tag, "class='math'")
2662 << html::EndTag(tag)
2669 void InsetMathHull::toString(odocstream & os) const
2671 odocstringstream ods;
2672 plaintext(ods, OutputParams(0));
2677 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2679 odocstringstream ods;
2682 // FIXME: this results in spilling TeX into the LyXHTML output since the
2683 // outliner is used to generate the LyXHTML list of figures/etc.
2689 string InsetMathHull::contextMenuName() const
2691 return "context-math";
2695 void InsetMathHull::recordLocation(DocIterator const & di)
2701 bool InsetMathHull::canPaintChange(BufferView const &) const
2703 // We let RowPainter do it seamlessly for inline insets
2704 return display() != Inline;