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 cnts.step(eqstr, utype);
320 numbers_[i] = cnts.theCounter(eqstr, lang);
322 numbers_[i] = empty_docstring();
328 for (size_t i = 0; i != label_.size(); ++i) {
330 label_[i]->updateBuffer(it, utype);
333 InsetMathGrid::updateBuffer(it, utype);
337 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active,
338 UpdateType utype, TocBackend & backend) const
341 //FIXME: buffer_ should be set at creation for this inset! Problem is
342 // This inset is created at too many places (see Parser::parse1() in
347 TocBuilder & b = backend.builder("equation");
348 // compute first and last item
349 row_type first = nrows();
350 for (row_type row = 0; row != nrows(); ++row)
355 if (first == nrows())
358 row_type last = nrows() - 1;
359 for (; last != 0; --last)
362 // add equation numbers
363 b.pushItem(pit, docstring(), output_active);
365 b.argumentItem(bformat(from_ascii("(%1$s-%2$s)"),
366 numbers_[first], numbers_[last]));
367 for (row_type row = 0; row != nrows(); ++row) {
371 label_[row]->addToToc(pit, output_active, utype, backend);
372 docstring label = nicelabel(row);
374 // this is the only equation
375 b.argumentItem(label);
377 // insert as sub-items
378 b.pushItem(pit, label, output_active);
386 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
388 if (previewState(&cur.bv())) {
392 return InsetMathNest::editXY(cur, x, y);
396 InsetMath::mode_type InsetMathHull::currentMode() const
400 return UNDECIDED_MODE;
402 // definitely math mode ...
422 // FIXME: InsetMathGrid should be changed to let the real column alignment be
423 // given by a virtual method like displayColAlign, because the values produced
424 // by defaultColAlign can be invalidated by lfuns such as add-column. For the
425 // moment the values produced by defaultColAlign are not used, notably because
426 // alignment is not implemented in the LyXHTML output.
427 char InsetMathHull::defaultColAlign(col_type col)
429 return colAlign(type_, col);
433 char InsetMathHull::displayColAlign(idx_type idx) const
437 row_type const r = row(idx);
440 if (r == nrows() - 1)
451 return colAlign(type_, col(idx));
455 return InsetMathGrid::displayColAlign(idx);
459 int InsetMathHull::displayColSpace(col_type col) const
461 return colSpace(type_, col);
465 // FIXME: same comment as for defaultColAlign applies.
466 int InsetMathHull::defaultColSpace(col_type col)
468 return colSpace(type_, col);
472 string InsetMathHull::standardFont() const
478 return "lyxnochange";
485 ColorCode InsetMathHull::standardColor() const
490 return Color_foreground;
498 bool InsetMathHull::previewState(const BufferView *const bv) const
500 if (!editing(bv) && RenderPreview::previewMath()
501 && type_ != hullRegexp)
503 graphics::PreviewImage const * pimage =
504 preview_->getPreviewImage(bv->buffer());
505 return pimage && pimage->image();
512 const int ERROR_FRAME_WIDTH = 2;
514 bool previewTooSmall(MetricsBase const & mb, Dimension const & dim)
516 // Value was hardcoded to 10 pixels
517 int const minval = mb.bv->zoomedPixels(10);
518 return dim.width() <= minval && dim.height() <= minval;
523 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
525 // true value in LaTeX is 12pt plus 3pt minus 9pt
526 // FIXME: even better would be to handle the short skip case.
527 int const display_margin = display() ? mi.base.inPixels(Length(12, Length::PT)) : 0;
529 if (previewState(mi.base.bv)) {
530 preview_->metrics(mi, dim);
531 if (previewTooSmall(mi.base, dim)) {
532 // preview image is too small
533 dim.wid += 2 * ERROR_FRAME_WIDTH;
534 dim.asc += 2 * ERROR_FRAME_WIDTH;
536 // insert a gap in front of the formula
537 // value was hardcoded to 1 pixel
538 dim.wid += mi.base.bv->zoomedPixels(1) ;
540 dim.asc += display_margin;
541 dim.des += display_margin;
547 Changer dummy1 = mi.base.changeFontSet(standardFont());
548 Changer dummy2 = mi.base.font.changeStyle(display() ? LM_ST_DISPLAY
551 // let the cells adjust themselves
552 InsetMathGrid::metrics(mi, dim);
555 dim.asc += display_margin;
556 dim.des += display_margin;
559 if (numberedType()) {
560 Changer dummy = mi.base.changeFontSet("mathrm");
562 for (row_type row = 0; row < nrows(); ++row)
563 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
566 // Value was hardcoded to 30 pixels
567 dim.wid += mi.base.bv->zoomedPixels(30) + l;
570 // reserve some space for marker.
575 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
577 BufferView const * const bv = pi.base.bv;
578 if (previewState(bv)) {
579 Dimension const dim = dimension(*pi.base.bv);
580 if (previewTooSmall(pi.base, dim))
582 return graphics::PreviewLoader::backgroundColor();
588 void InsetMathHull::drawMarkers(PainterInfo & pi, int x, int y) const
590 ColorCode pen_color = mouseHovered(pi.base.bv) || editing(pi.base.bv)?
591 Color_mathframe : Color_mathcorners;
592 // If the corners have the same color as the background, do not paint them.
593 if (lcolor.getX11Name(Color_mathbg) == lcolor.getX11Name(pen_color))
596 Inset::drawMarkers(pi, x, y);
597 Dimension const dim = dimension(*pi.base.bv);
598 int const t = x + dim.width() - 1;
599 int const a = y - dim.ascent();
600 pi.pain.line(x, a + 3, x, a, pen_color);
601 pi.pain.line(t, a + 3, t, a, pen_color);
602 pi.pain.line(x, a, x + 3, a, pen_color);
603 pi.pain.line(t - 3, a, t, a, pen_color);
607 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
609 Dimension const dim = dimension(*pi.base.bv);
610 if (previewTooSmall(pi.base, dim)) {
611 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
612 dim.wid, dim.asc + dim.des, backgroundColor(pi));
615 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
616 dim.asc + dim.des - 1, pi.backgroundColor(this));
620 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
622 BufferView const * const bv = pi.base.bv;
623 Dimension const dim = dimension(*bv);
625 if (type_ == hullRegexp)
626 pi.pain.rectangle(x + 2, y - dim.ascent() + 1,
627 dim.width() - 3, dim.height() - 2, Color_regexpframe);
629 if (previewState(bv)) {
630 // Do not draw change tracking cue if taken care of by RowPainter
632 Changer dummy = !canPaintChange(*bv) ? make_change(pi.change_, Change())
634 if (previewTooSmall(pi.base, dim)) {
635 // we have an extra frame
636 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
638 // one pixel gap in front
639 // value was hardcoded to 1 pixel
640 int const gap = pi.base.bv->zoomedPixels(1) ;
641 preview_->draw(pi, x + gap, y);
646 ColorCode color = pi.selected && lyxrc.use_system_colors
647 ? Color_selectiontext : standardColor();
648 bool const really_change_color = pi.base.font.color() == Color_none;
649 Changer dummy0 = really_change_color ? pi.base.font.changeColor(color)
651 Changer dummy1 = pi.base.changeFontSet(standardFont());
652 Changer dummy2 = pi.base.font.changeStyle(display() ? LM_ST_DISPLAY
656 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
657 if (numberedType() && math_number == BufferParams::LEFT) {
658 Changer dummy = pi.base.changeFontSet("mathrm");
660 for (row_type row = 0; row < nrows(); ++row)
661 l = max(l, mathed_string_width(pi.base.font, nicelabel(row)));
664 // Value was hardcoded to 30 pixels
665 xmath += pi.base.bv->zoomedPixels(30) + l;
668 InsetMathGrid::draw(pi, xmath + 1, y);
669 drawMarkers(pi, x, y);
671 if (numberedType()) {
672 Changer dummy = pi.base.changeFontSet("mathrm");
673 for (row_type row = 0; row < nrows(); ++row) {
674 int const yy = y + rowinfo_[row].offset_;
675 docstring const nl = nicelabel(row);
676 if (math_number == BufferParams::LEFT)
679 int l = mathed_string_width(pi.base.font, nl);
680 pi.draw(x + dim.wid - l, yy, nl);
685 // drawing change line
686 if (canPaintChange(*bv))
687 pi.change_.paintCue(pi, x + 1, y + 1 - dim.asc,
688 x + dim.wid, y + dim.des);
692 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
695 InsetMathGrid::metricsT(mi, dim);
698 otexrowstream ots(os);
699 WriteStream wi(ots, false, true, WriteStream::wsDefault);
701 dim.wid = os.str().size();
708 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
711 InsetMathGrid::drawT(pain, x, y);
714 otexrowstream ots(os);
715 WriteStream wi(ots, false, true, WriteStream::wsDefault);
717 pain.draw(x, y, os.str().c_str());
722 static docstring latexString(InsetMathHull const & inset)
725 // This has to be static, because a preview snippet or a math
726 // macro containing math in text mode (such as $\text{$\phi$}$ or
727 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
728 // first time as a whole, and the second time only the inner math.
729 // In this last case inset.buffer() would be invalid.
730 static Encoding const * encoding = 0;
731 if (inset.isBufferValid())
732 encoding = &(inset.buffer().params().encoding());
733 otexrowstream ots(ls);
734 WriteStream wi(ots, false, true, WriteStream::wsPreview, encoding);
740 void InsetMathHull::initUnicodeMath() const
742 // Trigger classification of the unicode symbols in this inset
743 docstring const dummy = latexString(*this);
747 void InsetMathHull::addPreview(DocIterator const & inset_pos,
748 graphics::PreviewLoader & /*ploader*/) const
750 if (RenderPreview::previewMath()) {
751 preparePreview(inset_pos);
756 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
757 MacroNameSet & macros, MacroNameSet & defs) const
759 MacroNameSet::iterator const end = macros.end();
761 for (size_t i = 0; i < md.size(); ++i) {
762 InsetMathMacro const * mi = md[i].nucleus()->asMacro();
763 InsetMathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
764 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
765 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
766 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
767 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
769 // Look for macros in the arguments of this macro.
770 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
771 usedMacros(mi->cell(idx), pos, macros, defs);
772 // Make sure this is a macro defined in the document
773 // (as we also spot the macros in the symbols file)
774 // or that we have not already accounted for it.
775 docstring const name = mi->name();
776 if (macros.find(name) == end)
779 // Look for macros in the definition of this macro.
780 MathData ar(pos.buffer());
781 MacroData const * data =
782 pos.buffer()->getMacro(name, pos, true);
784 odocstringstream macro_def;
785 data->write(macro_def, true);
787 defs.insert(macro_def.str());
788 asArray(data->definition(), ar);
790 usedMacros(ar, pos, macros, defs);
792 MathData ar(pos.buffer());
793 asArray(mt->definition(), ar);
794 usedMacros(ar, pos, macros, defs);
796 if (!si->nuc().empty())
797 usedMacros(si->nuc(), pos, macros, defs);
799 usedMacros(si->down(), pos, macros, defs);
801 usedMacros(si->up(), pos, macros, defs);
802 } else if (fi || gi) {
803 idx_type nidx = fi ? fi->nargs() : gi->nargs();
804 for (idx_type idx = 0; idx < nidx; ++idx)
805 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
808 usedMacros(ni->cell(0), pos, macros, defs);
814 void InsetMathHull::preparePreview(DocIterator const & pos,
815 bool forexport) const
817 // there is no need to do all the macro stuff if we're not
818 // actually going to generate the preview.
819 if (!RenderPreview::previewMath() && !forexport)
822 Buffer const * buffer = pos.buffer();
824 // collect macros at this position
826 buffer->listMacroNames(macros);
828 // collect definitions only for the macros used in this inset
830 for (idx_type idx = 0; idx < nargs(); ++idx)
831 usedMacros(cell(idx), pos, macros, defs);
833 docstring macro_preamble;
834 for (auto const & defvar : defs)
835 macro_preamble.append(defvar);
837 // set the font series and size for this snippet
838 DocIterator dit = pos.getInnerText();
839 Paragraph const & par = dit.paragraph();
840 Font font = par.getFontSettings(buffer->params(), dit.pos());
841 font.fontInfo().realize(par.layout().font);
842 string const lsize = font.latexSize();
845 if (font.fontInfo().series() == BOLD_SERIES) {
846 setfont += from_ascii("\\textbf{");
849 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
850 setfont += from_ascii("\\" + lsize + '\n');
853 if (forexport && haveNumbers()) {
854 docstring eqstr = from_ascii("equation");
855 CounterMap::const_iterator it = counter_map.find(eqstr);
856 if (it != counter_map.end()) {
857 int num = it->second;
859 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
860 '{' + convert<docstring>(num) + '}' + '\n';
862 for (size_t i = 0; i != numcnts; ++i) {
863 docstring cnt = from_ascii(counters_to_save[i]);
864 it = counter_map.find(cnt);
865 if (it == counter_map.end())
867 int num = it->second;
869 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
870 '{' + convert<docstring>(num) + '}';
873 docstring const snippet = macro_preamble + setfont + setcnt
874 + latexString(*this) + endfont;
875 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
876 preview_->addPreview(snippet, *buffer, forexport);
880 void InsetMathHull::reloadPreview(DocIterator const & pos) const
883 preview_->startLoading(*pos.buffer());
887 void InsetMathHull::loadPreview(DocIterator const & pos) const
889 bool const forexport = true;
890 preparePreview(pos, forexport);
891 preview_->startLoading(*pos.buffer(), forexport);
895 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
897 if (RenderPreview::previewMath()) {
899 cur.screenUpdateFlags(Update::Force);
905 docstring InsetMathHull::label(row_type row) const
907 LASSERT(row < nrows(), return docstring());
908 if (InsetLabel * il = label_[row])
909 return il->screenLabel();
914 void InsetMathHull::label(row_type row, docstring const & label)
916 //lyxerr << "setting label '" << label << "' for row " << row << endl;
920 label_[row] = dummy_pointer;
923 label_[row]->updateLabelAndRefs(label);
925 label_[row]->setParam("name", label);
929 InsetCommandParams p(LABEL_CODE);
931 label_[row] = new InsetLabel(buffer_, p);
933 label_[row]->setBuffer(buffer());
937 void InsetMathHull::numbered(row_type row, Numbered num)
939 numbered_[row] = num;
940 if (!numbered(row) && label_[row]) {
947 bool InsetMathHull::numbered(row_type row) const
949 return numbered_[row] == NUMBER;
953 bool InsetMathHull::ams() const
973 for (size_t row = 0; row < numbered_.size(); ++row)
974 if (numbered_[row] == NOTAG)
980 bool InsetMathHull::outerDisplay() const
1003 Inset::DisplayType InsetMathHull::display() const
1020 if (buffer().params().is_math_indent)
1030 int InsetMathHull::indent(BufferView const & bv) const
1032 // FIXME: set this in the textclass. This value is what the article class uses.
1033 static Length default_indent(2.5, Length::EM);
1034 if (display() != Inline && buffer().params().is_math_indent) {
1035 Length const & len = buffer().params().getMathIndent();
1037 return bv.inPixels(default_indent);
1039 return bv.inPixels(len);
1041 return Inset::indent(bv);
1045 bool InsetMathHull::numberedType() const
1064 for (row_type row = 0; row < nrows(); ++row)
1071 void InsetMathHull::validate(LaTeXFeatures & features) const
1073 if (features.runparams().isLaTeX()) {
1075 features.require("amsmath");
1077 if (type_ == hullRegexp) {
1078 features.require("color");
1079 docstring frcol = from_utf8(lcolor.getLaTeXName(Color_regexpframe));
1080 docstring bgcol = from_ascii("white");
1081 features.addPreambleSnippet(
1082 "\\newcommand{\\regexp}[1]{\\fcolorbox{"
1084 + bgcol + "}{\\ensuremath{\\mathtt{#1}}}}");
1085 features.addPreambleSnippet(
1086 from_ascii("\\newcommand{\\endregexp}{}"));
1087 } else if (outerDisplay() && features.inDeletedInset()
1088 && !features.mustProvide("ct-dvipost")) {
1089 features.require("ct-tikz-math-sout");
1092 // Validation is necessary only if not using AMS math.
1093 // To be safe, we will always run mathedvalidate.
1094 //if (features.amsstyle)
1097 //features.binom = true;
1098 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
1099 // it would be better to do this elsewhere, but we can't validate in
1100 // InsetMathMatrix and we have no way, outside MathExtern, to know if
1101 // we even have any matrices.
1102 features.addCSSSnippet(
1103 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
1104 "table.matrix td{padding: 0.25px;}\n"
1105 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
1106 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
1108 InsetMathGrid::validate(features);
1112 void InsetMathHull::header_write(WriteStream & os) const
1114 bool n = numberedType();
1125 if (cell(0).empty())
1130 writeMathdisplayPreamble(os);
1134 os << "\\begin{equation" << star(n) << "}\n";
1144 writeMathdisplayPreamble(os);
1147 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1154 os << "\\begin{" << hullName(type_) << star(n) << '}'
1155 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1161 os << "\\begin{" << hullName(type_) << '}'
1162 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1172 os << "\\begin{unknown" << star(n) << "}\n";
1178 void InsetMathHull::footer_write(WriteStream & os) const
1180 bool n = numberedType();
1197 os << "\\end{equation" << star(n) << "}\n";
1200 writeMathdisplayPostamble(os);
1210 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1211 writeMathdisplayPostamble(os);
1218 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1224 os << "\\end{" << hullName(type_) << "}\n";
1228 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1229 os << "\\endregexp{}}";
1235 os << "\\end{unknown" << star(n) << "}\n";
1241 bool InsetMathHull::allowsTabularFeatures() const
1264 bool InsetMathHull::rowChangeOK() const
1267 type_ == hullEqnArray || type_ == hullAlign ||
1268 type_ == hullFlAlign || type_ == hullAlignAt ||
1269 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1270 type_ == hullGather || type_ == hullMultline;
1274 bool InsetMathHull::colChangeOK() const
1277 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1278 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1282 void InsetMathHull::addRow(row_type row)
1287 bool numbered = numberedType();
1288 // Move the number and raw pointer, do not call label() (bug 7511)
1289 InsetLabel * label = dummy_pointer;
1290 docstring number = empty_docstring();
1291 if (type_ == hullMultline) {
1292 if (row + 1 == nrows()) {
1293 numbered_[row] = NONUMBER;
1294 swap(label, label_[row]);
1295 swap(number, numbers_[row]);
1300 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1301 numbers_.insert(numbers_.begin() + row + 1, number);
1302 label_.insert(label_.begin() + row + 1, label);
1303 InsetMathGrid::addRow(row);
1307 void InsetMathHull::swapRow(row_type row)
1311 if (row + 1 == nrows())
1313 swap(numbered_[row], numbered_[row + 1]);
1314 swap(numbers_[row], numbers_[row + 1]);
1315 swap(label_[row], label_[row + 1]);
1316 InsetMathGrid::swapRow(row);
1320 void InsetMathHull::delRow(row_type row)
1322 if (nrows() <= 1 || !rowChangeOK())
1324 if (row + 1 == nrows() && type_ == hullMultline) {
1325 swap(numbered_[row - 1], numbered_[row]);
1326 swap(numbers_[row - 1], numbers_[row]);
1327 swap(label_[row - 1], label_[row]);
1328 InsetMathGrid::delRow(row);
1331 InsetMathGrid::delRow(row);
1332 // The last dummy row has no number info nor a label.
1333 // Test nrows() + 1 because we have already erased the row.
1334 if (row == nrows() + 1)
1336 numbered_.erase(numbered_.begin() + row);
1337 numbers_.erase(numbers_.begin() + row);
1339 label_.erase(label_.begin() + row);
1343 void InsetMathHull::addCol(col_type col)
1347 InsetMathGrid::addCol(col);
1351 void InsetMathHull::delCol(col_type col)
1353 if (ncols() <= 1 || !colChangeOK())
1355 InsetMathGrid::delCol(col);
1359 docstring InsetMathHull::nicelabel(row_type row) const
1363 docstring const & val = numbers_[row];
1365 return '(' + val + ')';
1366 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1370 void InsetMathHull::glueall(HullType type)
1373 for (idx_type i = 0; i < nargs(); ++i)
1375 InsetLabel * label = 0;
1376 if (type == hullEquation) {
1377 // preserve first non-empty label
1378 for (row_type row = 0; row < nrows(); ++row) {
1380 label = label_[row];
1386 *this = InsetMathHull(buffer_, hullSimple);
1393 void InsetMathHull::splitTo2Cols()
1395 LASSERT(ncols() == 1, return);
1396 InsetMathGrid::addCol(1);
1397 for (row_type row = 0; row < nrows(); ++row) {
1398 idx_type const i = 2 * row;
1399 pos_type pos = firstRelOp(cell(i));
1400 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1401 cell(i).erase(pos, cell(i).size());
1406 void InsetMathHull::splitTo3Cols()
1408 LASSERT(ncols() < 3, return);
1411 InsetMathGrid::addCol(2);
1412 for (row_type row = 0; row < nrows(); ++row) {
1413 idx_type const i = 3 * row + 1;
1414 if (!cell(i).empty()) {
1415 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1416 cell(i).erase(1, cell(i).size());
1422 void InsetMathHull::changeCols(col_type cols)
1424 if (ncols() == cols)
1426 else if (ncols() < cols) {
1432 while (ncols() < cols)
1433 InsetMathGrid::addCol(ncols());
1439 for (row_type row = 0; row < nrows(); ++row) {
1440 idx_type const i = row * ncols();
1441 for (col_type col = cols; col < ncols(); ++col) {
1442 cell(i + cols - 1).append(cell(i + col));
1446 while (ncols() > cols) {
1447 InsetMathGrid::delCol(ncols() - 1);
1452 HullType InsetMathHull::getType() const
1458 void InsetMathHull::setType(HullType type)
1465 bool InsetMathHull::isMutable(HullType type)
1489 void InsetMathHull::mutate(HullType newtype)
1491 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1493 if (newtype == type_)
1496 // This guards the algorithm below it, which is designed with certain types
1498 if (!isMutable(newtype) || !isMutable(type_)) {
1499 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1500 << "' to '" << to_utf8(hullName(newtype))
1501 << "' not implemented" << endl;
1505 // we try to move along the chain
1506 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1508 // +-------------------------------------+
1509 // we use eqnarray as intermediate type for mutations that are not
1510 // directly supported because it handles labels and numbering for
1515 setType(hullSimple);
1521 if (newtype == hullNone) {
1525 setType(hullEquation);
1526 numbered(0, label_[0] ? true : false);
1535 setType(hullSimple);
1540 // split it "nicely" on the first relop
1542 setType(hullEqnArray);
1550 // split it "nicely"
1585 setType(hullEqnArray);
1594 for (row_type row = 0; row < nrows(); ++row)
1595 numbered(row, false);
1605 for (row_type row = 0; row < nrows(); ++row)
1606 numbered(row, false);
1613 setType(hullEqnArray);
1643 for (row_type row = 0; row < nrows(); ++row)
1644 numbered(row, false);
1648 // first we mutate to EqnArray
1650 setType(hullEqnArray);
1657 // we passed the guard so we should not be here
1658 LYXERR0("Mutation not implemented, but should have been.");
1659 LASSERT(false, return);
1665 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1666 bool last_eoln) const
1669 if (numberedType()) {
1670 if (label_[row] && numbered(row)) {
1671 docstring const name =
1672 latex ? escape(label_[row]->getParam("name"))
1673 : label_[row]->getParam("name");
1674 res += "\\label{" + name + '}';
1676 if (type_ != hullMultline) {
1677 if (numbered_[row] == NONUMBER)
1678 res += "\\nonumber ";
1679 else if (numbered_[row] == NOTAG)
1683 // Never add \\ on the last empty line of eqnarray and friends
1685 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1688 void InsetMathHull::write(WriteStream & os) const
1690 ModeSpecifier specifier(os, MATH_MODE);
1692 InsetMathGrid::write(os);
1697 void InsetMathHull::normalize(NormalStream & os) const
1699 os << "[formula " << hullName(type_) << ' ';
1700 InsetMathGrid::normalize(os);
1705 void InsetMathHull::infoize(odocstream & os) const
1707 os << bformat(_("Type: %1$s"), hullName(type_));
1711 void InsetMathHull::check() const
1713 LATTEST(numbered_.size() == nrows());
1714 LATTEST(numbers_.size() == nrows());
1715 LATTEST(label_.size() == nrows());
1719 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1723 idocstringstream iss(func.argument());
1724 iss >> dlang >> extra;
1726 extra = from_ascii("noextra");
1727 string const lang = to_ascii(dlang);
1729 // replace selection with result of computation
1730 if (reduceSelectionToOneCell(cur)) {
1732 asArray(grabAndEraseSelection(cur), ar);
1733 lyxerr << "use selection: " << ar << endl;
1734 cur.insert(pipeThroughExtern(lang, extra, ar));
1738 // only inline, display or eqnarray math is allowed
1739 switch (getType()) {
1745 frontend::Alert::warning(_("Bad math environment"),
1746 _("Computation cannot be performed for AMS "
1747 "math environments.\nChange the math "
1748 "formula type and try again."));
1753 eq.push_back(MathAtom(new InsetMathChar('=')));
1755 // go to first item in line
1756 cur.idx() -= cur.idx() % ncols();
1759 if (getType() == hullSimple) {
1760 size_type pos = cur.cell().find_last(eq);
1762 if (pos == cur.cell().size()) {
1764 lyxerr << "use whole cell: " << ar << endl;
1766 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1767 lyxerr << "use partial cell form pos: " << pos << endl;
1769 cur.cell().append(eq);
1770 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1771 cur.pos() = cur.lastpos();
1775 if (getType() == hullEquation) {
1776 lyxerr << "use equation inset" << endl;
1777 mutate(hullEqnArray);
1778 MathData & ar = cur.cell();
1779 lyxerr << "use cell: " << ar << endl;
1783 cur.cell() = pipeThroughExtern(lang, extra, ar);
1784 // move to end of line
1785 cur.pos() = cur.lastpos();
1790 lyxerr << "use eqnarray" << endl;
1791 cur.idx() += 2 - cur.idx() % ncols();
1793 MathData ar = cur.cell();
1794 lyxerr << "use cell: " << ar << endl;
1795 // FIXME: temporarily disabled
1801 cur.cell() = pipeThroughExtern(lang, extra, ar);
1802 cur.pos() = cur.lastpos();
1807 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1809 //lyxerr << "action: " << cmd.action() << endl;
1810 switch (cmd.action()) {
1812 case LFUN_FINISHED_BACKWARD:
1813 case LFUN_FINISHED_FORWARD:
1814 case LFUN_FINISHED_RIGHT:
1815 case LFUN_FINISHED_LEFT:
1816 //lyxerr << "action: " << cmd.action() << endl;
1817 InsetMathGrid::doDispatch(cur, cmd);
1820 case LFUN_PARAGRAPH_BREAK:
1821 // just swallow this
1824 case LFUN_NEWLINE_INSERT:
1825 // some magic for the common case
1826 if (type_ == hullSimple || type_ == hullEquation) {
1827 cur.recordUndoInset();
1829 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1830 mutate(align ? hullAlign : hullEqnArray);
1831 // mutate() may change labels and such.
1832 cur.forceBufferUpdate();
1833 cur.idx() = nrows() * ncols() - 1;
1834 cur.pos() = cur.lastpos();
1836 InsetMathGrid::doDispatch(cur, cmd);
1839 case LFUN_MATH_NUMBER_TOGGLE: {
1840 //lyxerr << "toggling all numbers" << endl;
1841 cur.recordUndoInset();
1842 bool old = numberedType();
1843 if (type_ == hullMultline)
1844 numbered(nrows() - 1, !old);
1846 for (row_type row = 0; row < nrows(); ++row)
1847 numbered(row, !old);
1849 cur.message(old ? _("No number") : _("Number"));
1850 cur.forceBufferUpdate();
1854 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1855 cur.recordUndoInset();
1856 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1857 bool old = numbered(r);
1858 cur.message(old ? _("No number") : _("Number"));
1860 cur.forceBufferUpdate();
1864 case LFUN_LABEL_INSERT: {
1865 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1866 docstring old_label = label(r);
1867 docstring const default_label = from_ascii("eq:");
1868 if (old_label.empty())
1869 old_label = default_label;
1871 InsetCommandParams p(LABEL_CODE);
1872 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1873 string const data = InsetCommand::params2string(p);
1875 if (cmd.argument().empty())
1876 cur.bv().showDialog("label", data);
1878 FuncRequest fr(LFUN_INSET_INSERT, data);
1884 case LFUN_LABEL_COPY_AS_REFERENCE: {
1886 if (cmd.argument().empty() && &cur.inset() == this)
1887 // if there is no argument and we're inside math, we retrieve
1888 // the row number from the cursor position.
1889 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1891 // if there is an argument, find the corresponding label, else
1892 // check whether there is at least one label.
1893 for (row = 0; row != nrows(); ++row)
1894 if (numbered(row) && label_[row]
1895 && (cmd.argument().empty() || label(row) == cmd.argument()))
1902 InsetCommandParams p(REF_CODE, "ref");
1903 p["reference"] = label(row);
1904 cap::clearSelection();
1905 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1909 case LFUN_WORD_DELETE_FORWARD:
1910 case LFUN_CHAR_DELETE_FORWARD:
1911 if (col(cur.idx()) + 1 == ncols()
1912 && cur.pos() == cur.lastpos()
1913 && !cur.selection()) {
1914 if (!label(row(cur.idx())).empty()) {
1915 cur.recordUndoInset();
1916 label(row(cur.idx()), docstring());
1917 } else if (numbered(row(cur.idx()))) {
1918 cur.recordUndoInset();
1919 numbered(row(cur.idx()), false);
1920 cur.forceBufferUpdate();
1922 InsetMathGrid::doDispatch(cur, cmd);
1926 InsetMathGrid::doDispatch(cur, cmd);
1931 case LFUN_INSET_INSERT: {
1932 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1933 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1934 string const name = cmd.getArg(0);
1935 if (name == "label") {
1936 InsetCommandParams p(LABEL_CODE);
1937 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1938 docstring str = p["name"];
1939 cur.recordUndoInset();
1940 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1944 docstring old = label(r);
1947 // The label will take care of the reference update.
1951 // Newly created inset so initialize it.
1952 label_[r]->initView();
1955 cur.forceBufferUpdate();
1958 InsetMathGrid::doDispatch(cur, cmd);
1962 case LFUN_MATH_EXTERN:
1963 cur.recordUndoInset();
1967 case LFUN_MATH_MUTATE: {
1968 cur.recordUndoInset();
1969 row_type row = cur.row();
1970 col_type col = cur.col();
1971 mutate(hullType(cmd.argument()));
1972 cur.idx() = row * ncols() + col;
1973 if (cur.idx() > cur.lastidx()) {
1974 cur.idx() = cur.lastidx();
1975 cur.pos() = cur.lastpos();
1977 if (cur.pos() > cur.lastpos())
1978 cur.pos() = cur.lastpos();
1980 cur.forceBufferUpdate();
1981 // FIXME: find some more clever handling of the selection,
1982 // i.e. preserve it.
1983 cur.clearSelection();
1984 //cur.dispatched(FINISHED);
1988 case LFUN_MATH_DISPLAY: {
1989 cur.recordUndoInset();
1990 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1991 // if the cursor is in a cell that got merged, move it to
1992 // start of the hull inset.
1993 if (cur.idx() > 0) {
1997 if (cur.pos() > cur.lastpos())
1998 cur.pos() = cur.lastpos();
2003 case LFUN_TABULAR_FEATURE:
2004 if (!allowsTabularFeatures())
2007 InsetMathGrid::doDispatch(cur, cmd);
2011 InsetMathGrid::doDispatch(cur, cmd);
2019 bool allowDisplayMath(Cursor const & cur)
2021 LATTEST(cur.depth() > 1);
2022 Cursor tmpcur = cur;
2025 FuncRequest cmd(LFUN_MATH_DISPLAY);
2026 return tmpcur.getStatus(cmd, status) && status.enabled();
2032 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
2033 FuncStatus & status) const
2035 switch (cmd.action()) {
2036 case LFUN_FINISHED_BACKWARD:
2037 case LFUN_FINISHED_FORWARD:
2038 case LFUN_FINISHED_RIGHT:
2039 case LFUN_FINISHED_LEFT:
2042 case LFUN_NEWLINE_INSERT:
2043 case LFUN_MATH_EXTERN:
2045 status.setEnabled(true);
2048 // we never allow this in math, and we want to bind enter
2049 // to another actions in command-alternatives
2050 case LFUN_PARAGRAPH_BREAK:
2051 status.setEnabled(false);
2053 case LFUN_MATH_MUTATE: {
2054 HullType const ht = hullType(cmd.argument());
2055 status.setOnOff(type_ == ht);
2056 status.setEnabled(isMutable(ht) && isMutable(type_));
2058 if (ht != hullSimple && status.enabled())
2059 status.setEnabled(allowDisplayMath(cur));
2062 case LFUN_MATH_DISPLAY: {
2063 status.setEnabled(display() != Inline || allowDisplayMath(cur));
2064 status.setOnOff(display() != Inline);
2068 case LFUN_MATH_NUMBER_TOGGLE:
2069 // FIXME: what is the right test, this or the one of
2071 status.setEnabled(display() != Inline);
2072 status.setOnOff(numberedType());
2075 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
2076 // FIXME: what is the right test, this or the one of
2078 bool const enable = (type_ == hullMultline)
2079 ? (nrows() - 1 == cur.row())
2080 : display() != Inline;
2081 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2082 status.setEnabled(enable);
2083 status.setOnOff(enable && numbered(r));
2087 case LFUN_LABEL_INSERT:
2088 status.setEnabled(type_ != hullSimple);
2091 case LFUN_LABEL_COPY_AS_REFERENCE: {
2092 bool enabled = false;
2093 if (cmd.argument().empty() && &cur.inset() == this) {
2094 // if there is no argument and we're inside math, we retrieve
2095 // the row number from the cursor position.
2096 row_type row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2097 enabled = numberedType() && label_[row] && numbered(row);
2099 // if there is an argument, find the corresponding label, else
2100 // check whether there is at least one label.
2101 for (row_type row = 0; row != nrows(); ++row) {
2102 if (numbered(row) && label_[row] &&
2103 (cmd.argument().empty() || label(row) == cmd.argument())) {
2109 status.setEnabled(enabled);
2113 case LFUN_INSET_INSERT:
2114 if (cmd.getArg(0) == "label") {
2115 status.setEnabled(type_ != hullSimple);
2118 return InsetMathGrid::getStatus(cur, cmd, status);
2120 case LFUN_TABULAR_FEATURE: {
2121 if (!allowsTabularFeatures())
2123 string s = cmd.getArg(0);
2125 && (s == "append-row"
2126 || s == "delete-row"
2127 || s == "copy-row")) {
2128 status.message(bformat(
2129 from_utf8(N_("Can't change number of rows in '%1$s'")),
2131 status.setEnabled(false);
2135 && (s == "append-column"
2136 || s == "delete-column"
2137 || s == "copy-column")) {
2138 status.message(bformat(
2139 from_utf8(N_("Can't change number of columns in '%1$s'")),
2141 status.setEnabled(false);
2144 if (s == "add-vline-left" || s == "add-vline-right") {
2145 status.message(bformat(
2146 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2148 status.setEnabled(false);
2151 if (s == "valign-top" || s == "valign-middle"
2152 || s == "valign-bottom" || s == "align-left"
2153 || s == "align-center" || s == "align-right") {
2154 status.setEnabled(false);
2157 return InsetMathGrid::getStatus(cur, cmd, status);
2161 return InsetMathGrid::getStatus(cur, cmd, status);
2166 int InsetMathHull::leftMargin() const
2168 return (getType() == hullSimple) ? 0 : InsetMathGrid::leftMargin();
2172 int InsetMathHull::rightMargin() const
2174 return (getType() == hullSimple) ? 0 : InsetMathGrid::rightMargin();
2178 int InsetMathHull::border() const
2180 return (getType() == hullSimple) ? 0 : InsetMathGrid::border();
2184 /////////////////////////////////////////////////////////////////////
2188 // simply scrap this function if you want
2189 void InsetMathHull::mutateToText()
2192 // translate to latex
2194 latex(os, false, false);
2195 string str = os.str();
2198 Text * lt = view_->cursor().innerText();
2199 string::const_iterator cit = str.begin();
2200 string::const_iterator end = str.end();
2201 for (; cit != end; ++cit)
2202 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2205 //dispatch(LFUN_ESCAPE);
2210 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2211 docstring const & font)
2213 // this whole function is a hack and won't work for incremental font
2216 if (cur.inset().asInsetMath()->name() == font)
2217 cur.handleFont(to_utf8(font));
2219 cur.handleNest(createInsetMath(font, cur.buffer()));
2225 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2230 font.fromString(to_utf8(arg), b);
2231 if (font.fontInfo().color() != Color_inherit) {
2232 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2238 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2240 InsetMathNest::edit(cur, front, entry_from);
2241 // The inset formula dimension is not necessarily the same as the
2242 // one of the instant preview image, so we have to indicate to the
2243 // BufferView that a metrics update is needed.
2244 cur.screenUpdateFlags(Update::Force);
2248 /////////////////////////////////////////////////////////////////////
2252 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2255 // FIXME: completely broken
2256 static InsetMathHull * lastformula = 0;
2257 static CursorBase current = DocIterator(ibegin(nucleus()));
2259 static string laststr;
2261 if (lastformula != this || laststr != str) {
2262 //lyxerr << "reset lastformula to " << this << endl;
2265 current = ibegin(nucleus());
2267 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2271 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2273 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2274 CursorSlice & top = it.back();
2275 MathData const & a = top.asInsetMath()->cell(top.idx_);
2276 if (a.matchpart(ar, top.pos_)) {
2277 bv->cursor().setSelection(it, ar.size());
2279 top.pos_ += ar.size();
2285 //lyxerr << "not found!" << endl;
2292 void InsetMathHull::write(ostream & os) const
2294 odocstringstream oss;
2295 otexrowstream ots(oss);
2296 WriteStream wi(ots, false, false, WriteStream::wsDefault);
2299 os << to_utf8(oss.str());
2303 void InsetMathHull::read(Lexer & lex)
2306 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2307 operator=(*at->asHullInset());
2311 bool InsetMathHull::readQuiet(Lexer & lex)
2314 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2316 operator=(*at->asHullInset());
2321 int InsetMathHull::plaintext(odocstringstream & os,
2322 OutputParams const & op, size_t max_length) const
2324 // Try enabling this now that there is a flag as requested at #2275.
2325 if (buffer().isExporting() && display()) {
2329 TextPainter tpain(dim.width(), dim.height());
2330 drawT(tpain, 0, dim.ascent());
2332 // reset metrics cache to "real" values
2334 return tpain.textheight();
2337 odocstringstream oss;
2338 otexrowstream ots(oss);
2339 Encoding const * const enc = encodings.fromLyXName("utf8");
2340 WriteStream wi(ots, false, true, WriteStream::wsDefault, enc);
2343 if (type_ == hullRegexp)
2346 for (row_type r = 0; r < nrows(); ++r) {
2347 for (col_type c = 0; c < ncols(); ++c)
2348 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2349 // if it's for the TOC, we write just the first line
2350 // and do not include the newline.
2351 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2353 if (r < nrows() - 1)
2357 docstring const str = oss.str();
2363 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
2368 if (getType() == hullSimple)
2369 name = from_ascii("inlineequation");
2371 name = from_ascii("informalequation");
2373 docstring bname = name;
2374 if (!label(0).empty())
2375 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
2377 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
2379 odocstringstream ls;
2381 if (runparams.flavor == OutputParams::XML) {
2382 ms << MTag("alt role='tex' ");
2383 // Workaround for db2latex: db2latex always includes equations with
2384 // \ensuremath{} or \begin{display}\end{display}
2385 // so we strip LyX' math environment
2386 WriteStream wi(ols, false, false, WriteStream::wsDefault, runparams.encoding);
2387 InsetMathGrid::write(wi);
2388 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2393 InsetMathGrid::mathmlize(ms);
2396 ms << MTag("alt role='tex'");
2397 latex(ols, runparams);
2398 res = ols.texrow().rows();
2399 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2403 ms << from_ascii("<graphic fileref=\"eqn/");
2404 if (!label(0).empty())
2405 ms << sgml::cleanID(buffer(), runparams, label(0));
2407 ms << sgml::uniqueID(from_ascii("anon"));
2409 if (runparams.flavor == OutputParams::XML)
2410 ms << from_ascii("\"/>");
2412 ms << from_ascii("\">");
2414 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2416 return ms.line() + res;
2420 bool InsetMathHull::haveNumbers() const
2422 bool havenumbers = false;
2423 // inline formulas are never numbered (bug 7351 part 3)
2424 if (getType() == hullSimple)
2426 for (size_t i = 0; i != numbered_.size(); ++i) {
2437 // We need to do something about alignment here.
2439 // This duplicates code from InsetMathGrid, but
2440 // we need access here to number information,
2441 // and we simply do not have that in InsetMathGrid.
2442 void InsetMathHull::htmlize(HtmlStream & os) const
2444 bool const havenumbers = haveNumbers();
2445 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2448 os << cell(index(0, 0));
2452 os << MTag("table", "class='mathtable'");
2453 for (row_type row = 0; row < nrows(); ++row) {
2455 for (col_type col = 0; col < ncols(); ++col) {
2457 os << cell(index(row, col));
2462 docstring const & num = numbers_[row];
2464 os << '(' << num << ')';
2469 os << ETag("table");
2473 // this duplicates code from InsetMathGrid, but
2474 // we need access here to number information,
2475 // and we simply do not have that in InsetMathGrid.
2476 void InsetMathHull::mathmlize(MathStream & os) const
2478 bool const havenumbers = haveNumbers();
2479 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2482 os << MTag("mtable");
2483 char const * const celltag = havetable ? "mtd" : "mrow";
2484 // FIXME There does not seem to be wide support at the moment
2485 // for mlabeledtr, so we have to use just mtr for now.
2486 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2487 char const * const rowtag = "mtr";
2488 for (row_type row = 0; row < nrows(); ++row) {
2491 for (col_type col = 0; col < ncols(); ++col) {
2493 << cell(index(row, col))
2499 docstring const & num = numbers_[row];
2501 os << '(' << num << ')';
2508 os << ETag("mtable");
2512 void InsetMathHull::mathAsLatex(WriteStream & os) const
2514 MathEnsurer ensurer(os, false);
2515 bool havenumbers = haveNumbers();
2516 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2519 os << cell(index(0, 0));
2523 os << "<table class='mathtable'>";
2524 for (row_type row = 0; row < nrows(); ++row) {
2526 for (col_type col = 0; col < ncols(); ++col) {
2527 os << "<td class='math'>";
2528 os << cell(index(row, col));
2533 docstring const & num = numbers_[row];
2535 os << '(' << num << ')';
2544 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2546 BufferParams::MathOutput const mathtype =
2547 buffer().masterBuffer()->params().html_math_output;
2549 bool success = false;
2551 // we output all the labels just at the beginning of the equation.
2552 // this should be fine.
2553 for (size_t i = 0; i != label_.size(); ++i) {
2554 InsetLabel const * const il = label_[i];
2560 // FIXME Eventually we would like to do this inset by inset.
2561 if (mathtype == BufferParams::MathML) {
2562 odocstringstream os;
2567 } catch (MathExportException const &) {}
2569 if (getType() == hullSimple)
2570 xs << html::StartTag("math",
2571 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2573 xs << html::StartTag("math",
2574 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2575 xs << XHTMLStream::ESCAPE_NONE
2577 << html::EndTag("math");
2579 } else if (mathtype == BufferParams::HTML) {
2580 odocstringstream os;
2585 } catch (MathExportException const &) {}
2587 string const tag = (getType() == hullSimple) ? "span" : "div";
2588 xs << html::StartTag(tag, "class='formula'", true)
2589 << XHTMLStream::ESCAPE_NONE
2591 << html::EndTag(tag);
2595 // what we actually want is this:
2597 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2599 // || mathtype == BufferParams::Images
2601 // but what follows is equivalent, since we'll enter only if either (a) we
2602 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2603 // aren't doing LaTeX.
2605 // so this is for Images.
2606 if (!success && mathtype != BufferParams::LaTeX) {
2607 graphics::PreviewImage const * pimage = 0;
2609 loadPreview(docit_);
2610 pimage = preview_->getPreviewImage(buffer());
2611 // FIXME Do we always have png?
2614 if (pimage || op.dryrun) {
2615 string const filename = pimage ? pimage->filename().onlyFileName()
2616 : "previewimage.png";
2618 // if we are not in the master buffer, then we need to see that the
2619 // generated image is copied there; otherwise, preview fails.
2620 Buffer const * mbuf = buffer().masterBuffer();
2621 if (mbuf != &buffer()) {
2622 string mbtmp = mbuf->temppath();
2623 FileName const mbufimg(support::addName(mbtmp, filename));
2624 pimage->filename().copyTo(mbufimg);
2626 // add the file to the list of files to be exported
2627 op.exportdata->addExternalFile("xhtml", pimage->filename());
2630 string const tag = (getType() == hullSimple) ? "span" : "div";
2632 << html::StartTag(tag, "style = \"text-align: center;\"")
2633 << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2634 << html::EndTag(tag)
2640 // so we'll pass this test if we've failed everything else, or
2641 // if mathtype was LaTeX, since we won't have entered any of the
2643 if (!success /* || mathtype != BufferParams::LaTeX */) {
2644 // Unfortunately, we cannot use latexString() because we do not want
2645 // $...$ or whatever.
2646 odocstringstream ls;
2647 otexrowstream ots(ls);
2648 WriteStream wi(ots, false, true, WriteStream::wsPreview);
2649 ModeSpecifier specifier(wi, MATH_MODE);
2651 docstring const latex = ls.str();
2653 // class='math' allows for use of jsMath
2654 // http://www.math.union.edu/~dpvc/jsMath/
2656 // probably should allow for some kind of customization here
2657 string const tag = (getType() == hullSimple) ? "span" : "div";
2658 xs << html::StartTag(tag, "class='math'")
2660 << html::EndTag(tag)
2667 void InsetMathHull::toString(odocstream & os) const
2669 odocstringstream ods;
2670 plaintext(ods, OutputParams(0));
2675 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2677 odocstringstream ods;
2680 // FIXME: this results in spilling TeX into the LyXHTML output since the
2681 // outliner is used to generate the LyXHTML list of figures/etc.
2687 string InsetMathHull::contextMenuName() const
2689 return "context-math";
2693 void InsetMathHull::recordLocation(DocIterator const & di)
2699 bool InsetMathHull::canPaintChange(BufferView const &) const
2701 // We let RowPainter do it seamlessly for inline insets
2702 return display() != Inline;