2 * \file InsetMathHull.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 #include "InsetMathHull.h"
15 #include "InsetMathChar.h"
16 #include "InsetMathColor.h"
17 #include "InsetMathFrac.h"
18 #include "InsetMathNest.h"
19 #include "InsetMathScript.h"
20 #include "MathExtern.h"
21 #include "MathFactory.h"
22 #include "MathStream.h"
23 #include "MathSupport.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
29 #include "CutAndPaste.h"
32 #include "FuncRequest.h"
33 #include "FuncStatus.h"
35 #include "LaTeXFeatures.h"
37 #include "MacroTable.h"
38 #include "InsetMathMacro.h"
39 #include "InsetMathMacroTemplate.h"
40 #include "MetricsInfo.h"
41 #include "output_xhtml.h"
42 #include "Paragraph.h"
43 #include "ParIterator.h"
46 #include "TextClass.h"
47 #include "TextPainter.h"
48 #include "TocBackend.h"
50 #include "insets/InsetLabel.h"
51 #include "insets/InsetRef.h"
52 #include "insets/RenderPreview.h"
54 #include "graphics/GraphicsImage.h"
55 #include "graphics/PreviewImage.h"
56 #include "graphics/PreviewLoader.h"
58 #include "frontends/alert.h"
59 #include "frontends/Painter.h"
61 #include "support/convert.h"
62 #include "support/debug.h"
63 #include "support/gettext.h"
64 #include "support/filetools.h"
65 #include "support/lassert.h"
66 #include "support/lstrings.h"
67 #include "support/RefChanger.h"
72 using namespace lyx::support;
76 using cap::grabAndEraseSelection;
77 using cap::reduceSelectionToOneCell;
81 int getCols(HullType type)
106 // returns position of first relation operator in the array
107 // used for "intelligent splitting"
108 size_t firstRelOp(MathData const & ar)
110 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
111 if ((*it)->mathClass() == MC_REL)
112 return it - ar.begin();
117 char const * star(bool numbered)
119 return numbered ? "" : "*";
123 // writes a preamble for underlined or struck out math display
124 void writeMathdisplayPreamble(WriteStream & os)
126 if (os.strikeoutMath()) {
127 if (os.ulemCmd() == WriteStream::UNDERLINE)
128 os << "\\raisebox{-\\belowdisplayshortskip}{"
129 "\\lyxmathsout{\\parbox[b]{\\linewidth}{";
131 os << "\\lyxmathsout{\\parbox{\\linewidth}{";
132 } else if (os.ulemCmd() == WriteStream::UNDERLINE)
133 os << "\\raisebox{-\\belowdisplayshortskip}{"
134 "\\parbox[b]{\\linewidth}{";
135 else if (os.ulemCmd() == WriteStream::STRIKEOUT)
136 os << "\\parbox{\\linewidth}{";
140 // writes a postamble for underlined or struck out math display
141 void writeMathdisplayPostamble(WriteStream & os)
143 if (os.strikeoutMath()) {
144 if (os.ulemCmd() == WriteStream::UNDERLINE)
147 } else if (os.ulemCmd() == WriteStream::UNDERLINE)
149 else if (os.ulemCmd() == WriteStream::STRIKEOUT)
157 HullType hullType(docstring const & s)
159 if (s == "none") return hullNone;
160 if (s == "simple") return hullSimple;
161 if (s == "equation") return hullEquation;
162 if (s == "eqnarray") return hullEqnArray;
163 if (s == "align") return hullAlign;
164 if (s == "alignat") return hullAlignAt;
165 if (s == "xalignat") return hullXAlignAt;
166 if (s == "xxalignat") return hullXXAlignAt;
167 if (s == "multline") return hullMultline;
168 if (s == "gather") return hullGather;
169 if (s == "flalign") return hullFlAlign;
170 if (s == "regexp") return hullRegexp;
171 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
176 docstring hullName(HullType type)
179 case hullNone: return from_ascii("none");
180 case hullSimple: return from_ascii("simple");
181 case hullEquation: return from_ascii("equation");
182 case hullEqnArray: return from_ascii("eqnarray");
183 case hullAlign: return from_ascii("align");
184 case hullAlignAt: return from_ascii("alignat");
185 case hullXAlignAt: return from_ascii("xalignat");
186 case hullXXAlignAt: return from_ascii("xxalignat");
187 case hullMultline: return from_ascii("multline");
188 case hullGather: return from_ascii("gather");
189 case hullFlAlign: return from_ascii("flalign");
190 case hullRegexp: return from_ascii("regexp");
192 lyxerr << "unknown hull type" << endl;
195 return from_ascii("none");
198 static InsetLabel * dummy_pointer = 0;
200 InsetMathHull::InsetMathHull(Buffer * buf)
201 : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, NONUMBER),
202 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
203 preview_(new RenderPreview(this))
205 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
206 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
207 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
208 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
215 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
216 : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, NONUMBER),
217 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
218 preview_(new RenderPreview(this))
226 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
232 InsetMathHull::~InsetMathHull()
234 for (size_t i = 0; i < label_.size(); ++i)
239 Inset * InsetMathHull::clone() const
241 return new InsetMathHull(*this);
245 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
249 InsetMathGrid::operator=(other);
251 numbered_ = other.numbered_;
252 numbers_ = other.numbers_;
253 buffer_ = other.buffer_;
254 for (size_t i = 0; i < label_.size(); ++i)
256 label_ = other.label_;
257 for (size_t i = 0; i != label_.size(); ++i) {
259 label_[i] = new InsetLabel(*label_[i]);
261 preview_.reset(new RenderPreview(*other.preview_, this));
267 void InsetMathHull::setBuffer(Buffer & buffer)
269 InsetMathGrid::setBuffer(buffer);
271 for (size_t i = 0; i != label_.size(); ++i) {
273 label_[i]->setBuffer(buffer);
278 // FIXME This should really be controlled by the TOC level, or
279 // something of the sort.
281 const char * counters_to_save[] = {"section", "chapter"};
282 unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
286 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
289 //FIXME: buffer_ should be set at creation for this inset! Problem is
290 // This inset is created at too many places (see Parser::parse1() in
295 // if any of the equations are numbered, then we want to save the values
296 // of some of the counters.
298 BufferParams const & bp = buffer_->params();
299 string const & lang = it->getParLanguage(bp)->code();
301 buffer_->masterBuffer()->params().documentClass().counters();
303 // right now, we only need to do this at export time
304 if (utype == OutputUpdate) {
305 for (size_t i = 0; i < numcnts; ++i) {
306 docstring const cnt = from_ascii(counters_to_save[i]);
307 if (cnts.hasCounter(cnt))
308 counter_map[cnt] = cnts.value(cnt);
312 // this has to be done separately
313 docstring const eqstr = from_ascii("equation");
314 if (cnts.hasCounter(eqstr)) {
315 if (utype == OutputUpdate)
316 counter_map[eqstr] = cnts.value(eqstr);
317 for (size_t i = 0; i != label_.size(); ++i) {
319 Paragraph const & par = it.paragraph();
320 if (!par.isDeleted(it.pos())) {
321 cnts.step(eqstr, utype);
322 numbers_[i] = cnts.theCounter(eqstr, lang);
324 numbers_[i] = from_ascii("#");
326 numbers_[i] = empty_docstring();
332 for (size_t i = 0; i != label_.size(); ++i) {
334 label_[i]->updateBuffer(it, utype);
337 InsetMathGrid::updateBuffer(it, utype);
341 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active,
342 UpdateType utype, TocBackend & backend) const
345 //FIXME: buffer_ should be set at creation for this inset! Problem is
346 // This inset is created at too many places (see Parser::parse1() in
351 TocBuilder & b = backend.builder("equation");
352 // compute first and last item
353 row_type first = nrows();
354 for (row_type row = 0; row != nrows(); ++row)
359 if (first == nrows())
362 row_type last = nrows() - 1;
363 for (; last != 0; --last)
366 // add equation numbers
367 b.pushItem(pit, docstring(), output_active);
369 b.argumentItem(bformat(from_ascii("(%1$s-%2$s)"),
370 numbers_[first], numbers_[last]));
371 for (row_type row = 0; row != nrows(); ++row) {
375 label_[row]->addToToc(pit, output_active, utype, backend);
376 docstring label = nicelabel(row);
378 // this is the only equation
379 b.argumentItem(label);
381 // insert as sub-items
382 b.pushItem(pit, label, output_active);
390 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
392 if (previewState(&cur.bv())) {
396 return InsetMathNest::editXY(cur, x, y);
400 InsetMath::mode_type InsetMathHull::currentMode() const
404 return UNDECIDED_MODE;
406 // definitely math mode ...
426 bool InsetMathHull::idxFirst(Cursor & cur) const
434 bool InsetMathHull::idxLast(Cursor & cur) const
436 cur.idx() = nargs() - 1;
437 cur.pos() = cur.lastpos();
442 // FIXME: InsetMathGrid should be changed to let the real column alignment be
443 // given by a virtual method like displayColAlign, because the values produced
444 // by defaultColAlign can be invalidated by lfuns such as add-column. For the
445 // moment the values produced by defaultColAlign are not used, notably because
446 // alignment is not implemented in the LyXHTML output.
447 char InsetMathHull::defaultColAlign(col_type col)
449 return colAlign(type_, col);
453 char InsetMathHull::displayColAlign(idx_type idx) const
457 row_type const r = row(idx);
460 if (r == nrows() - 1)
471 return colAlign(type_, col(idx));
475 return InsetMathGrid::displayColAlign(idx);
479 int InsetMathHull::displayColSpace(col_type col) const
481 return colSpace(type_, col);
485 // FIXME: same comment as for defaultColAlign applies.
486 int InsetMathHull::defaultColSpace(col_type col)
488 return colSpace(type_, col);
492 string InsetMathHull::standardFont() const
498 return "lyxnochange";
505 ColorCode InsetMathHull::standardColor() const
510 return Color_foreground;
518 bool InsetMathHull::previewState(const BufferView *const bv) const
520 if (!editing(bv) && RenderPreview::previewMath()
521 && type_ != hullRegexp)
523 graphics::PreviewImage const * pimage =
524 preview_->getPreviewImage(bv->buffer());
525 return pimage && pimage->image();
532 static const int ERROR_FRAME_WIDTH = 2;
535 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
537 if (previewState(mi.base.bv)) {
538 preview_->metrics(mi, dim);
539 if (previewTooSmall(dim)) {
540 // preview image is too small
541 dim.wid += 2 * ERROR_FRAME_WIDTH;
542 dim.asc += 2 * ERROR_FRAME_WIDTH;
544 // insert a one pixel gap in front of the formula
547 dim.des += displayMargin();
552 Changer dummy1 = mi.base.changeFontSet(standardFont());
553 Changer dummy2 = mi.base.font.changeStyle(display() ? LM_ST_DISPLAY
556 // let the cells adjust themselves
557 InsetMathGrid::metrics(mi, dim);
560 dim.asc += displayMargin();
561 dim.des += displayMargin();
564 if (numberedType()) {
565 Changer dummy = mi.base.changeFontSet("mathrm");
567 for (row_type row = 0; row < nrows(); ++row)
568 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
571 // Value was hardcoded to 30 pixels
572 dim.wid += Length(0.3, Length::IN).inPixels(mi.base) + l;
575 // reserve some space for marker.
580 bool InsetMathHull::previewTooSmall(Dimension const & dim) const
582 return dim.width() <= 10 && dim.height() <= 10;
586 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
588 BufferView const * const bv = pi.base.bv;
589 if (previewState(bv)) {
590 Dimension const dim = dimension(*pi.base.bv);
591 if (previewTooSmall(dim))
593 return graphics::PreviewLoader::backgroundColor();
599 void InsetMathHull::drawMarkers(PainterInfo & pi, int x, int y) const
601 ColorCode pen_color = mouseHovered(pi.base.bv) || editing(pi.base.bv)?
602 Color_mathframe : Color_mathcorners;
603 // If the corners have the same color as the background, do not paint them.
604 if (lcolor.getX11Name(Color_mathbg) == lcolor.getX11Name(pen_color))
607 Inset::drawMarkers(pi, x, y);
608 Dimension const dim = dimension(*pi.base.bv);
609 int const t = x + dim.width() - 1;
610 int const a = y - dim.ascent();
611 pi.pain.line(x, a + 3, x, a, pen_color);
612 pi.pain.line(t, a + 3, t, a, pen_color);
613 pi.pain.line(x, a, x + 3, a, pen_color);
614 pi.pain.line(t - 3, a, t, a, pen_color);
618 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
620 Dimension const dim = dimension(*pi.base.bv);
621 if (previewTooSmall(dim)) {
622 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
623 dim.wid, dim.asc + dim.des, backgroundColor(pi));
626 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
627 dim.asc + dim.des - 1, pi.backgroundColor(this));
631 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
633 BufferView const * const bv = pi.base.bv;
634 Dimension const dim = dimension(*bv);
636 if (type_ == hullRegexp)
637 pi.pain.rectangle(x + 2, y - dim.ascent() + 1,
638 dim.width() - 3, dim.height() - 2, Color_regexpframe);
640 if (previewState(bv)) {
641 // Do not draw change tracking cue if taken care of by RowPainter
643 Changer dummy = !canPaintChange(*bv) ? make_change(pi.change_, Change())
645 if (previewTooSmall(dim)) {
646 // we have an extra frame
647 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
649 // one pixel gap in front
650 preview_->draw(pi, x + 1, y);
655 ColorCode color = pi.selected && lyxrc.use_system_colors
656 ? Color_selectiontext : standardColor();
657 bool const really_change_color = pi.base.font.color() == Color_none;
658 Changer dummy0 = really_change_color ? pi.base.font.changeColor(color)
660 Changer dummy1 = pi.base.changeFontSet(standardFont());
661 Changer dummy2 = pi.base.font.changeStyle(display() ? LM_ST_DISPLAY
665 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
666 if (numberedType() && math_number == BufferParams::LEFT) {
667 Changer dummy = pi.base.changeFontSet("mathrm");
669 for (row_type row = 0; row < nrows(); ++row)
670 l = max(l, mathed_string_width(pi.base.font, nicelabel(row)));
673 // Value was hardcoded to 30 pixels
674 xmath += Length(0.3, Length::IN).inPixels(pi.base) + l;
677 InsetMathGrid::draw(pi, xmath + 1, y);
678 drawMarkers(pi, x, y);
680 if (numberedType()) {
681 Changer dummy = pi.base.changeFontSet("mathrm");
682 for (row_type row = 0; row < nrows(); ++row) {
683 int const yy = y + rowinfo_[row].offset_;
684 docstring const nl = nicelabel(row);
685 if (math_number == BufferParams::LEFT)
688 int l = mathed_string_width(pi.base.font, nl);
689 pi.draw(x + dim.wid - l, yy, nl);
694 // drawing change line
695 if (canPaintChange(*bv)) {
697 int const display_margin = display() ? displayMargin() : 0;
698 pi.change_.paintCue(pi, x + 1, y + 1 - dim.asc + display_margin,
699 x + dim.wid, y + dim.des - display_margin);
704 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
707 InsetMathGrid::metricsT(mi, dim);
710 otexrowstream ots(os);
711 WriteStream wi(ots, false, true, WriteStream::wsDefault);
713 dim.wid = os.str().size();
720 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
723 InsetMathGrid::drawT(pain, x, y);
726 otexrowstream ots(os);
727 WriteStream wi(ots, false, true, WriteStream::wsDefault);
729 pain.draw(x, y, os.str().c_str());
734 static docstring latexString(InsetMathHull const & inset)
737 // This has to be static, because a preview snippet or a math
738 // macro containing math in text mode (such as $\text{$\phi$}$ or
739 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
740 // first time as a whole, and the second time only the inner math.
741 // In this last case inset.buffer() would be invalid.
742 static Encoding const * encoding = 0;
743 if (inset.isBufferValid())
744 encoding = &(inset.buffer().params().encoding());
745 otexrowstream ots(ls);
746 WriteStream wi(ots, false, true, WriteStream::wsPreview, encoding);
752 void InsetMathHull::initUnicodeMath() const
754 // Trigger classification of the unicode symbols in this inset
755 docstring const dummy = latexString(*this);
759 void InsetMathHull::addPreview(DocIterator const & inset_pos,
760 graphics::PreviewLoader & /*ploader*/) const
762 if (RenderPreview::previewMath()) {
763 preparePreview(inset_pos);
768 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
769 MacroNameSet & macros, MacroNameSet & defs) const
771 MacroNameSet::iterator const end = macros.end();
773 for (size_t i = 0; i < md.size(); ++i) {
774 InsetMathMacro const * mi = md[i].nucleus()->asMacro();
775 InsetMathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
776 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
777 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
778 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
779 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
781 // Look for macros in the arguments of this macro.
782 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
783 usedMacros(mi->cell(idx), pos, macros, defs);
784 // Make sure this is a macro defined in the document
785 // (as we also spot the macros in the symbols file)
786 // or that we have not already accounted for it.
787 docstring const name = mi->name();
788 if (macros.find(name) == end)
791 // Look for macros in the definition of this macro.
792 MathData ar(pos.buffer());
793 MacroData const * data =
794 pos.buffer()->getMacro(name, pos, true);
796 odocstringstream macro_def;
797 data->write(macro_def, true);
799 defs.insert(macro_def.str());
800 asArray(data->definition(), ar);
802 usedMacros(ar, pos, macros, defs);
804 MathData ar(pos.buffer());
805 asArray(mt->definition(), ar);
806 usedMacros(ar, pos, macros, defs);
808 if (!si->nuc().empty())
809 usedMacros(si->nuc(), pos, macros, defs);
811 usedMacros(si->down(), pos, macros, defs);
813 usedMacros(si->up(), pos, macros, defs);
814 } else if (fi || gi) {
815 idx_type nidx = fi ? fi->nargs() : gi->nargs();
816 for (idx_type idx = 0; idx < nidx; ++idx)
817 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
820 usedMacros(ni->cell(0), pos, macros, defs);
826 void InsetMathHull::preparePreview(DocIterator const & pos,
827 bool forexport) const
829 // there is no need to do all the macro stuff if we're not
830 // actually going to generate the preview.
831 if (!RenderPreview::previewMath() && !forexport)
834 Buffer const * buffer = pos.buffer();
836 // collect macros at this position
838 buffer->listMacroNames(macros);
840 // collect definitions only for the macros used in this inset
842 for (idx_type idx = 0; idx < nargs(); ++idx)
843 usedMacros(cell(idx), pos, macros, defs);
845 MacroNameSet::iterator it = defs.begin();
846 MacroNameSet::iterator end = defs.end();
847 docstring macro_preamble;
848 for (; it != end; ++it)
849 macro_preamble.append(*it);
851 // set the font series and size for this snippet
852 DocIterator dit = pos.getInnerText();
853 Paragraph const & par = dit.paragraph();
854 Font font = par.getFontSettings(buffer->params(), dit.pos());
855 font.fontInfo().realize(par.layout().font);
856 string const lsize = font.latexSize();
859 if (font.fontInfo().series() == BOLD_SERIES) {
860 setfont += from_ascii("\\textbf{");
863 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
864 setfont += from_ascii("\\" + lsize + '\n');
867 if (forexport && haveNumbers()) {
868 docstring eqstr = from_ascii("equation");
869 CounterMap::const_iterator it = counter_map.find(eqstr);
870 if (it != counter_map.end()) {
871 int num = it->second;
873 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
874 '{' + convert<docstring>(num) + '}' + '\n';
876 for (size_t i = 0; i != numcnts; ++i) {
877 docstring cnt = from_ascii(counters_to_save[i]);
878 it = counter_map.find(cnt);
879 if (it == counter_map.end())
881 int num = it->second;
883 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
884 '{' + convert<docstring>(num) + '}';
887 docstring const snippet = macro_preamble + setfont + setcnt
888 + latexString(*this) + endfont;
889 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
890 preview_->addPreview(snippet, *buffer, forexport);
894 void InsetMathHull::reloadPreview(DocIterator const & pos) const
897 preview_->startLoading(*pos.buffer());
901 void InsetMathHull::loadPreview(DocIterator const & pos) const
903 bool const forexport = true;
904 preparePreview(pos, forexport);
905 preview_->startLoading(*pos.buffer(), forexport);
909 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
911 if (RenderPreview::previewMath()) {
913 cur.screenUpdateFlags(Update::Force);
919 docstring InsetMathHull::label(row_type row) const
921 LASSERT(row < nrows(), return docstring());
922 if (InsetLabel * il = label_[row])
923 return il->screenLabel();
928 void InsetMathHull::label(row_type row, docstring const & label)
930 //lyxerr << "setting label '" << label << "' for row " << row << endl;
934 label_[row] = dummy_pointer;
937 label_[row]->updateLabelAndRefs(label);
939 label_[row]->setParam("name", label);
943 InsetCommandParams p(LABEL_CODE);
945 label_[row] = new InsetLabel(buffer_, p);
947 label_[row]->setBuffer(buffer());
951 void InsetMathHull::numbered(row_type row, Numbered num)
953 numbered_[row] = num;
954 if (!numbered(row) && label_[row]) {
961 bool InsetMathHull::numbered(row_type row) const
963 return numbered_[row] == NUMBER;
967 bool InsetMathHull::ams() const
987 for (size_t row = 0; row < numbered_.size(); ++row)
988 if (numbered_[row] == NOTAG)
994 bool InsetMathHull::outerDisplay() const
1017 Inset::DisplayType InsetMathHull::display() const
1034 if (buffer().params().is_math_indent)
1044 int InsetMathHull::indent(BufferView const & bv) const
1046 // FIXME: set this in the textclass. This value is what the article class uses.
1047 static Length default_indent(2.5, Length::EM);
1048 if (display() != Inline && buffer().params().is_math_indent) {
1049 Length const & len = buffer().params().getMathIndent();
1051 return bv.inPixels(default_indent);
1053 return bv.inPixels(len);
1055 return Inset::indent(bv);
1059 bool InsetMathHull::numberedType() const
1078 for (row_type row = 0; row < nrows(); ++row)
1085 void InsetMathHull::validate(LaTeXFeatures & features) const
1087 if (features.runparams().isLaTeX()) {
1089 features.require("amsmath");
1091 if (type_ == hullRegexp) {
1092 features.require("color");
1093 docstring frcol = from_utf8(lcolor.getLaTeXName(Color_regexpframe));
1094 docstring bgcol = from_ascii("white");
1095 features.addPreambleSnippet(
1096 "\\newcommand{\\regexp}[1]{\\fcolorbox{"
1098 + bgcol + "}{\\ensuremath{\\mathtt{#1}}}}");
1099 features.addPreambleSnippet(
1100 from_ascii("\\newcommand{\\endregexp}{}"));
1101 } else if (outerDisplay() && features.inDeletedInset()
1102 && !features.mustProvide("ct-dvipost")) {
1103 features.require("ct-tikz-math-sout");
1106 // Validation is necessary only if not using AMS math.
1107 // To be safe, we will always run mathedvalidate.
1108 //if (features.amsstyle)
1111 //features.binom = true;
1112 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
1113 // it would be better to do this elsewhere, but we can't validate in
1114 // InsetMathMatrix and we have no way, outside MathExtern, to know if
1115 // we even have any matrices.
1116 features.addCSSSnippet(
1117 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
1118 "table.matrix td{padding: 0.25px;}\n"
1119 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
1120 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
1122 InsetMathGrid::validate(features);
1126 void InsetMathHull::header_write(WriteStream & os) const
1128 bool n = numberedType();
1139 if (cell(0).empty())
1144 writeMathdisplayPreamble(os);
1148 os << "\\begin{equation" << star(n) << "}\n";
1158 writeMathdisplayPreamble(os);
1161 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1168 os << "\\begin{" << hullName(type_) << star(n) << '}'
1169 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1175 os << "\\begin{" << hullName(type_) << '}'
1176 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1186 os << "\\begin{unknown" << star(n) << "}\n";
1192 void InsetMathHull::footer_write(WriteStream & os) const
1194 bool n = numberedType();
1211 os << "\\end{equation" << star(n) << "}\n";
1214 writeMathdisplayPostamble(os);
1224 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1225 writeMathdisplayPostamble(os);
1232 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1238 os << "\\end{" << hullName(type_) << "}\n";
1242 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1243 os << "\\endregexp{}}";
1249 os << "\\end{unknown" << star(n) << "}\n";
1255 bool InsetMathHull::allowsTabularFeatures() const
1278 bool InsetMathHull::rowChangeOK() const
1281 type_ == hullEqnArray || type_ == hullAlign ||
1282 type_ == hullFlAlign || type_ == hullAlignAt ||
1283 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1284 type_ == hullGather || type_ == hullMultline;
1288 bool InsetMathHull::colChangeOK() const
1291 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1292 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1296 void InsetMathHull::addRow(row_type row)
1301 bool numbered = numberedType();
1302 // Move the number and raw pointer, do not call label() (bug 7511)
1303 InsetLabel * label = dummy_pointer;
1304 docstring number = empty_docstring();
1305 if (type_ == hullMultline) {
1306 if (row + 1 == nrows()) {
1307 numbered_[row] = NONUMBER;
1308 swap(label, label_[row]);
1309 swap(number, numbers_[row]);
1314 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1315 numbers_.insert(numbers_.begin() + row + 1, number);
1316 label_.insert(label_.begin() + row + 1, label);
1317 InsetMathGrid::addRow(row);
1321 void InsetMathHull::swapRow(row_type row)
1325 if (row + 1 == nrows())
1327 swap(numbered_[row], numbered_[row + 1]);
1328 swap(numbers_[row], numbers_[row + 1]);
1329 swap(label_[row], label_[row + 1]);
1330 InsetMathGrid::swapRow(row);
1334 void InsetMathHull::delRow(row_type row)
1336 if (nrows() <= 1 || !rowChangeOK())
1338 if (row + 1 == nrows() && type_ == hullMultline) {
1339 swap(numbered_[row - 1], numbered_[row]);
1340 swap(numbers_[row - 1], numbers_[row]);
1341 swap(label_[row - 1], label_[row]);
1342 InsetMathGrid::delRow(row);
1345 InsetMathGrid::delRow(row);
1346 // The last dummy row has no number info nor a label.
1347 // Test nrows() + 1 because we have already erased the row.
1348 if (row == nrows() + 1)
1350 numbered_.erase(numbered_.begin() + row);
1351 numbers_.erase(numbers_.begin() + row);
1353 label_.erase(label_.begin() + row);
1357 void InsetMathHull::addCol(col_type col)
1361 InsetMathGrid::addCol(col);
1365 void InsetMathHull::delCol(col_type col)
1367 if (ncols() <= 1 || !colChangeOK())
1369 InsetMathGrid::delCol(col);
1373 docstring InsetMathHull::nicelabel(row_type row) const
1377 docstring const & val = numbers_[row];
1379 return '(' + val + ')';
1380 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1384 void InsetMathHull::glueall(HullType type)
1387 for (idx_type i = 0; i < nargs(); ++i)
1389 InsetLabel * label = 0;
1390 if (type == hullEquation) {
1391 // preserve first non-empty label
1392 for (row_type row = 0; row < nrows(); ++row) {
1394 label = label_[row];
1400 *this = InsetMathHull(buffer_, hullSimple);
1407 void InsetMathHull::splitTo2Cols()
1409 LASSERT(ncols() == 1, return);
1410 InsetMathGrid::addCol(1);
1411 for (row_type row = 0; row < nrows(); ++row) {
1412 idx_type const i = 2 * row;
1413 pos_type pos = firstRelOp(cell(i));
1414 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1415 cell(i).erase(pos, cell(i).size());
1420 void InsetMathHull::splitTo3Cols()
1422 LASSERT(ncols() < 3, return);
1425 InsetMathGrid::addCol(2);
1426 for (row_type row = 0; row < nrows(); ++row) {
1427 idx_type const i = 3 * row + 1;
1428 if (!cell(i).empty()) {
1429 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1430 cell(i).erase(1, cell(i).size());
1436 void InsetMathHull::changeCols(col_type cols)
1438 if (ncols() == cols)
1440 else if (ncols() < cols) {
1446 while (ncols() < cols)
1447 InsetMathGrid::addCol(ncols());
1453 for (row_type row = 0; row < nrows(); ++row) {
1454 idx_type const i = row * ncols();
1455 for (col_type col = cols; col < ncols(); ++col) {
1456 cell(i + cols - 1).append(cell(i + col));
1460 while (ncols() > cols) {
1461 InsetMathGrid::delCol(ncols() - 1);
1466 HullType InsetMathHull::getType() const
1472 void InsetMathHull::setType(HullType type)
1479 bool InsetMathHull::isMutable(HullType type)
1503 void InsetMathHull::mutate(HullType newtype)
1505 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1507 if (newtype == type_)
1510 // This guards the algorithm below it, which is designed with certain types
1512 if (!isMutable(newtype) || !isMutable(type_)) {
1513 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1514 << "' to '" << to_utf8(hullName(newtype))
1515 << "' not implemented" << endl;
1519 // we try to move along the chain
1520 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1522 // +-------------------------------------+
1523 // we use eqnarray as intermediate type for mutations that are not
1524 // directly supported because it handles labels and numbering for
1529 setType(hullSimple);
1535 if (newtype == hullNone) {
1539 setType(hullEquation);
1540 numbered(0, label_[0] ? true : false);
1549 setType(hullSimple);
1554 // split it "nicely" on the first relop
1556 setType(hullEqnArray);
1564 // split it "nicely"
1599 setType(hullEqnArray);
1608 for (row_type row = 0; row < nrows(); ++row)
1609 numbered(row, false);
1619 for (row_type row = 0; row < nrows(); ++row)
1620 numbered(row, false);
1627 setType(hullEqnArray);
1657 for (row_type row = 0; row < nrows(); ++row)
1658 numbered(row, false);
1662 // first we mutate to EqnArray
1664 setType(hullEqnArray);
1671 // we passed the guard so we should not be here
1672 LASSERT("Mutation not implemented, but should have been.", return);
1678 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1679 bool last_eoln) const
1682 if (numberedType()) {
1683 if (label_[row] && numbered(row)) {
1684 docstring const name =
1685 latex ? escape(label_[row]->getParam("name"))
1686 : label_[row]->getParam("name");
1687 res += "\\label{" + name + '}';
1689 if (type_ != hullMultline) {
1690 if (numbered_[row] == NONUMBER)
1691 res += "\\nonumber ";
1692 else if (numbered_[row] == NOTAG)
1696 // Never add \\ on the last empty line of eqnarray and friends
1698 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1701 void InsetMathHull::write(WriteStream & os) const
1703 ModeSpecifier specifier(os, MATH_MODE);
1705 InsetMathGrid::write(os);
1710 void InsetMathHull::normalize(NormalStream & os) const
1712 os << "[formula " << hullName(type_) << ' ';
1713 InsetMathGrid::normalize(os);
1718 void InsetMathHull::infoize(odocstream & os) const
1720 os << bformat(_("Type: %1$s"), hullName(type_));
1724 void InsetMathHull::check() const
1726 LATTEST(numbered_.size() == nrows());
1727 LATTEST(numbers_.size() == nrows());
1728 LATTEST(label_.size() == nrows());
1732 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1736 idocstringstream iss(func.argument());
1737 iss >> dlang >> extra;
1739 extra = from_ascii("noextra");
1740 string const lang = to_ascii(dlang);
1742 // replace selection with result of computation
1743 if (reduceSelectionToOneCell(cur)) {
1745 asArray(grabAndEraseSelection(cur), ar);
1746 lyxerr << "use selection: " << ar << endl;
1747 cur.insert(pipeThroughExtern(lang, extra, ar));
1751 // only inline, display or eqnarray math is allowed
1752 switch (getType()) {
1758 frontend::Alert::warning(_("Bad math environment"),
1759 _("Computation cannot be performed for AMS "
1760 "math environments.\nChange the math "
1761 "formula type and try again."));
1766 eq.push_back(MathAtom(new InsetMathChar('=')));
1768 // go to first item in line
1769 cur.idx() -= cur.idx() % ncols();
1772 if (getType() == hullSimple) {
1773 size_type pos = cur.cell().find_last(eq);
1775 if (pos == cur.cell().size()) {
1777 lyxerr << "use whole cell: " << ar << endl;
1779 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1780 lyxerr << "use partial cell form pos: " << pos << endl;
1782 cur.cell().append(eq);
1783 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1784 cur.pos() = cur.lastpos();
1788 if (getType() == hullEquation) {
1789 lyxerr << "use equation inset" << endl;
1790 mutate(hullEqnArray);
1791 MathData & ar = cur.cell();
1792 lyxerr << "use cell: " << ar << endl;
1796 cur.cell() = pipeThroughExtern(lang, extra, ar);
1797 // move to end of line
1798 cur.pos() = cur.lastpos();
1803 lyxerr << "use eqnarray" << endl;
1804 cur.idx() += 2 - cur.idx() % ncols();
1806 MathData ar = cur.cell();
1807 lyxerr << "use cell: " << ar << endl;
1808 // FIXME: temporarily disabled
1814 cur.cell() = pipeThroughExtern(lang, extra, ar);
1815 cur.pos() = cur.lastpos();
1820 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1822 //lyxerr << "action: " << cmd.action() << endl;
1823 switch (cmd.action()) {
1825 case LFUN_FINISHED_BACKWARD:
1826 case LFUN_FINISHED_FORWARD:
1827 case LFUN_FINISHED_RIGHT:
1828 case LFUN_FINISHED_LEFT:
1829 //lyxerr << "action: " << cmd.action() << endl;
1830 InsetMathGrid::doDispatch(cur, cmd);
1833 case LFUN_PARAGRAPH_BREAK:
1834 // just swallow this
1837 case LFUN_NEWLINE_INSERT:
1838 // some magic for the common case
1839 if (type_ == hullSimple || type_ == hullEquation) {
1840 cur.recordUndoInset();
1842 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1843 mutate(align ? hullAlign : hullEqnArray);
1844 // mutate() may change labels and such.
1845 cur.forceBufferUpdate();
1846 cur.idx() = nrows() * ncols() - 1;
1847 cur.pos() = cur.lastpos();
1849 InsetMathGrid::doDispatch(cur, cmd);
1852 case LFUN_MATH_NUMBER_TOGGLE: {
1853 //lyxerr << "toggling all numbers" << endl;
1854 cur.recordUndoInset();
1855 bool old = numberedType();
1856 if (type_ == hullMultline)
1857 numbered(nrows() - 1, !old);
1859 for (row_type row = 0; row < nrows(); ++row)
1860 numbered(row, !old);
1862 cur.message(old ? _("No number") : _("Number"));
1863 cur.forceBufferUpdate();
1867 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1868 cur.recordUndoInset();
1869 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1870 bool old = numbered(r);
1871 cur.message(old ? _("No number") : _("Number"));
1873 cur.forceBufferUpdate();
1877 case LFUN_LABEL_INSERT: {
1878 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1879 docstring old_label = label(r);
1880 docstring const default_label = from_ascii("eq:");
1881 if (old_label.empty())
1882 old_label = default_label;
1884 InsetCommandParams p(LABEL_CODE);
1885 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1886 string const data = InsetCommand::params2string(p);
1888 if (cmd.argument().empty())
1889 cur.bv().showDialog("label", data);
1891 FuncRequest fr(LFUN_INSET_INSERT, data);
1897 case LFUN_LABEL_COPY_AS_REFERENCE: {
1899 if (cmd.argument().empty() && &cur.inset() == this)
1900 // if there is no argument and we're inside math, we retrieve
1901 // the row number from the cursor position.
1902 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1904 // if there is an argument, find the corresponding label, else
1905 // check whether there is at least one label.
1906 for (row = 0; row != nrows(); ++row)
1907 if (numbered(row) && label_[row]
1908 && (cmd.argument().empty() || label(row) == cmd.argument()))
1915 InsetCommandParams p(REF_CODE, "ref");
1916 p["reference"] = label(row);
1917 cap::clearSelection();
1918 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1922 case LFUN_WORD_DELETE_FORWARD:
1923 case LFUN_CHAR_DELETE_FORWARD:
1924 if (col(cur.idx()) + 1 == ncols()
1925 && cur.pos() == cur.lastpos()
1926 && !cur.selection()) {
1927 if (!label(row(cur.idx())).empty()) {
1928 cur.recordUndoInset();
1929 label(row(cur.idx()), docstring());
1930 } else if (numbered(row(cur.idx()))) {
1931 cur.recordUndoInset();
1932 numbered(row(cur.idx()), false);
1933 cur.forceBufferUpdate();
1935 InsetMathGrid::doDispatch(cur, cmd);
1939 InsetMathGrid::doDispatch(cur, cmd);
1944 case LFUN_INSET_INSERT: {
1945 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1946 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1947 string const name = cmd.getArg(0);
1948 if (name == "label") {
1949 InsetCommandParams p(LABEL_CODE);
1950 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1951 docstring str = p["name"];
1952 cur.recordUndoInset();
1953 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1957 docstring old = label(r);
1960 // The label will take care of the reference update.
1964 // Newly created inset so initialize it.
1965 label_[r]->initView();
1968 cur.forceBufferUpdate();
1971 InsetMathGrid::doDispatch(cur, cmd);
1975 case LFUN_MATH_EXTERN:
1976 cur.recordUndoInset();
1980 case LFUN_MATH_MUTATE: {
1981 cur.recordUndoInset();
1982 row_type row = cur.row();
1983 col_type col = cur.col();
1984 mutate(hullType(cmd.argument()));
1985 cur.idx() = row * ncols() + col;
1986 if (cur.idx() > cur.lastidx()) {
1987 cur.idx() = cur.lastidx();
1988 cur.pos() = cur.lastpos();
1990 if (cur.pos() > cur.lastpos())
1991 cur.pos() = cur.lastpos();
1993 cur.forceBufferUpdate();
1994 // FIXME: find some more clever handling of the selection,
1995 // i.e. preserve it.
1996 cur.clearSelection();
1997 //cur.dispatched(FINISHED);
2001 case LFUN_MATH_DISPLAY: {
2002 cur.recordUndoInset();
2003 mutate(type_ == hullSimple ? hullEquation : hullSimple);
2004 // if the cursor is in a cell that got merged, move it to
2005 // start of the hull inset.
2006 if (cur.idx() > 0) {
2010 if (cur.pos() > cur.lastpos())
2011 cur.pos() = cur.lastpos();
2016 case LFUN_TABULAR_FEATURE:
2017 if (!allowsTabularFeatures())
2020 InsetMathGrid::doDispatch(cur, cmd);
2024 InsetMathGrid::doDispatch(cur, cmd);
2032 bool allowDisplayMath(Cursor const & cur)
2034 LATTEST(cur.depth() > 1);
2035 Cursor tmpcur = cur;
2038 FuncRequest cmd(LFUN_MATH_DISPLAY);
2039 return tmpcur.getStatus(cmd, status) && status.enabled();
2045 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
2046 FuncStatus & status) const
2048 switch (cmd.action()) {
2049 case LFUN_FINISHED_BACKWARD:
2050 case LFUN_FINISHED_FORWARD:
2051 case LFUN_FINISHED_RIGHT:
2052 case LFUN_FINISHED_LEFT:
2055 case LFUN_NEWLINE_INSERT:
2056 case LFUN_MATH_EXTERN:
2058 status.setEnabled(true);
2061 // we never allow this in math, and we want to bind enter
2062 // to another actions in command-alternatives
2063 case LFUN_PARAGRAPH_BREAK:
2064 status.setEnabled(false);
2066 case LFUN_MATH_MUTATE: {
2067 HullType const ht = hullType(cmd.argument());
2068 status.setOnOff(type_ == ht);
2069 status.setEnabled(isMutable(ht) && isMutable(type_));
2071 if (ht != hullSimple && status.enabled())
2072 status.setEnabled(allowDisplayMath(cur));
2075 case LFUN_MATH_DISPLAY: {
2076 status.setEnabled(display() != Inline || allowDisplayMath(cur));
2077 status.setOnOff(display() != Inline);
2081 case LFUN_MATH_NUMBER_TOGGLE:
2082 // FIXME: what is the right test, this or the one of
2084 status.setEnabled(display() != Inline);
2085 status.setOnOff(numberedType());
2088 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
2089 // FIXME: what is the right test, this or the one of
2091 bool const enable = (type_ == hullMultline)
2092 ? (nrows() - 1 == cur.row())
2093 : display() != Inline;
2094 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2095 status.setEnabled(enable);
2096 status.setOnOff(enable && numbered(r));
2100 case LFUN_LABEL_INSERT:
2101 status.setEnabled(type_ != hullSimple);
2104 case LFUN_LABEL_COPY_AS_REFERENCE: {
2105 bool enabled = false;
2107 if (cmd.argument().empty() && &cur.inset() == this) {
2108 // if there is no argument and we're inside math, we retrieve
2109 // the row number from the cursor position.
2110 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2111 enabled = numberedType() && label_[row] && numbered(row);
2113 // if there is an argument, find the corresponding label, else
2114 // check whether there is at least one label.
2115 for (row_type row = 0; row != nrows(); ++row) {
2116 if (numbered(row) && label_[row] &&
2117 (cmd.argument().empty() || label(row) == cmd.argument())) {
2123 status.setEnabled(enabled);
2127 case LFUN_INSET_INSERT:
2128 if (cmd.getArg(0) == "label") {
2129 status.setEnabled(type_ != hullSimple);
2132 return InsetMathGrid::getStatus(cur, cmd, status);
2134 case LFUN_TABULAR_FEATURE: {
2135 if (!allowsTabularFeatures())
2137 string s = cmd.getArg(0);
2139 && (s == "append-row"
2140 || s == "delete-row"
2141 || s == "copy-row")) {
2142 status.message(bformat(
2143 from_utf8(N_("Can't change number of rows in '%1$s'")),
2145 status.setEnabled(false);
2149 && (s == "append-column"
2150 || s == "delete-column"
2151 || s == "copy-column")) {
2152 status.message(bformat(
2153 from_utf8(N_("Can't change number of columns in '%1$s'")),
2155 status.setEnabled(false);
2158 if (s == "add-vline-left" || s == "add-vline-right") {
2159 status.message(bformat(
2160 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2162 status.setEnabled(false);
2165 if (s == "valign-top" || s == "valign-middle"
2166 || s == "valign-bottom" || s == "align-left"
2167 || s == "align-center" || s == "align-right") {
2168 status.setEnabled(false);
2171 return InsetMathGrid::getStatus(cur, cmd, status);
2175 return InsetMathGrid::getStatus(cur, cmd, status);
2180 int InsetMathHull::leftMargin() const
2182 return (getType() == hullSimple) ? 0 : InsetMathGrid::leftMargin();
2186 int InsetMathHull::rightMargin() const
2188 return (getType() == hullSimple) ? 0 : InsetMathGrid::rightMargin();
2192 int InsetMathHull::border() const
2194 return (getType() == hullSimple) ? 0 : InsetMathGrid::border();
2198 /////////////////////////////////////////////////////////////////////
2202 // simply scrap this function if you want
2203 void InsetMathHull::mutateToText()
2206 // translate to latex
2208 latex(os, false, false);
2209 string str = os.str();
2212 Text * lt = view_->cursor().innerText();
2213 string::const_iterator cit = str.begin();
2214 string::const_iterator end = str.end();
2215 for (; cit != end; ++cit)
2216 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2219 //dispatch(LFUN_ESCAPE);
2224 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2225 docstring const & font)
2227 // this whole function is a hack and won't work for incremental font
2230 if (cur.inset().asInsetMath()->name() == font)
2231 cur.handleFont(to_utf8(font));
2233 cur.handleNest(createInsetMath(font, cur.buffer()));
2239 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2244 font.fromString(to_utf8(arg), b);
2245 if (font.fontInfo().color() != Color_inherit) {
2246 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2247 cur.handleNest(at, 0);
2252 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2255 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
2256 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
2257 enter_front ? idxFirst(cur) : idxLast(cur);
2258 // The inset formula dimension is not necessarily the same as the
2259 // one of the instant preview image, so we have to indicate to the
2260 // BufferView that a metrics update is needed.
2261 cur.screenUpdateFlags(Update::Force);
2265 void InsetMathHull::revealCodes(Cursor & cur) const
2267 if (!cur.inMathed())
2269 odocstringstream os;
2270 cur.info(os, false);
2271 cur.message(os.str());
2273 // write something to the minibuffer
2274 // translate to latex
2278 string str = os.str();
2280 string::size_type pos = 0;
2282 for (string::iterator it = str.begin(); it != str.end(); ++it) {
2285 else if (*it == '\0') {
2287 pos = it - str.begin();
2293 res = res.substr(pos - 30);
2294 if (res.size() > 60)
2295 res = res.substr(0, 60);
2301 /////////////////////////////////////////////////////////////////////
2305 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2308 // FIXME: completely broken
2309 static InsetMathHull * lastformula = 0;
2310 static CursorBase current = DocIterator(ibegin(nucleus()));
2312 static string laststr;
2314 if (lastformula != this || laststr != str) {
2315 //lyxerr << "reset lastformula to " << this << endl;
2318 current = ibegin(nucleus());
2320 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2324 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2326 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2327 CursorSlice & top = it.back();
2328 MathData const & a = top.asInsetMath()->cell(top.idx_);
2329 if (a.matchpart(ar, top.pos_)) {
2330 bv->cursor().setSelection(it, ar.size());
2332 top.pos_ += ar.size();
2338 //lyxerr << "not found!" << endl;
2345 void InsetMathHull::write(ostream & os) const
2347 odocstringstream oss;
2348 otexrowstream ots(oss);
2349 WriteStream wi(ots, false, false, WriteStream::wsDefault);
2352 os << to_utf8(oss.str());
2356 void InsetMathHull::read(Lexer & lex)
2359 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2360 operator=(*at->asHullInset());
2364 bool InsetMathHull::readQuiet(Lexer & lex)
2367 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2369 operator=(*at->asHullInset());
2374 int InsetMathHull::plaintext(odocstringstream & os,
2375 OutputParams const & op, size_t max_length) const
2377 // disables ASCII-art for export of equations. See #2275.
2378 if (0 && display()) {
2382 TextPainter tpain(dim.width(), dim.height());
2383 drawT(tpain, 0, dim.ascent());
2385 // reset metrics cache to "real" values
2387 return tpain.textheight();
2390 odocstringstream oss;
2391 otexrowstream ots(oss);
2392 Encoding const * const enc = encodings.fromLyXName("utf8");
2393 WriteStream wi(ots, false, true, WriteStream::wsDefault, enc);
2396 if (type_ == hullRegexp)
2399 for (row_type r = 0; r < nrows(); ++r) {
2400 for (col_type c = 0; c < ncols(); ++c)
2401 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2402 // if it's for the TOC, we write just the first line
2403 // and do not include the newline.
2404 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2406 if (r < nrows() - 1)
2410 docstring const str = oss.str();
2416 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
2421 if (getType() == hullSimple)
2422 name = from_ascii("inlineequation");
2424 name = from_ascii("informalequation");
2426 docstring bname = name;
2427 if (!label(0).empty())
2428 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
2430 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
2432 odocstringstream ls;
2434 if (runparams.flavor == OutputParams::XML) {
2435 ms << MTag("alt role='tex' ");
2436 // Workaround for db2latex: db2latex always includes equations with
2437 // \ensuremath{} or \begin{display}\end{display}
2438 // so we strip LyX' math environment
2439 WriteStream wi(ols, false, false, WriteStream::wsDefault, runparams.encoding);
2440 InsetMathGrid::write(wi);
2441 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2446 InsetMathGrid::mathmlize(ms);
2449 ms << MTag("alt role='tex'");
2450 latex(ols, runparams);
2451 res = ols.texrow().rows();
2452 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2456 ms << from_ascii("<graphic fileref=\"eqn/");
2457 if (!label(0).empty())
2458 ms << sgml::cleanID(buffer(), runparams, label(0));
2460 ms << sgml::uniqueID(from_ascii("anon"));
2462 if (runparams.flavor == OutputParams::XML)
2463 ms << from_ascii("\"/>");
2465 ms << from_ascii("\">");
2467 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2469 return ms.line() + res;
2473 bool InsetMathHull::haveNumbers() const
2475 bool havenumbers = false;
2476 // inline formulas are never numbered (bug 7351 part 3)
2477 if (getType() == hullSimple)
2479 for (size_t i = 0; i != numbered_.size(); ++i) {
2490 // We need to do something about alignment here.
2492 // This duplicates code from InsetMathGrid, but
2493 // we need access here to number information,
2494 // and we simply do not have that in InsetMathGrid.
2495 void InsetMathHull::htmlize(HtmlStream & os) const
2497 bool const havenumbers = haveNumbers();
2498 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2501 os << cell(index(0, 0));
2505 os << MTag("table", "class='mathtable'");
2506 for (row_type row = 0; row < nrows(); ++row) {
2508 for (col_type col = 0; col < ncols(); ++col) {
2510 os << cell(index(row, col));
2515 docstring const & num = numbers_[row];
2517 os << '(' << num << ')';
2522 os << ETag("table");
2526 // this duplicates code from InsetMathGrid, but
2527 // we need access here to number information,
2528 // and we simply do not have that in InsetMathGrid.
2529 void InsetMathHull::mathmlize(MathStream & os) const
2531 bool const havenumbers = haveNumbers();
2532 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2535 os << MTag("mtable");
2536 char const * const celltag = havetable ? "mtd" : "mrow";
2537 // FIXME There does not seem to be wide support at the moment
2538 // for mlabeledtr, so we have to use just mtr for now.
2539 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2540 char const * const rowtag = "mtr";
2541 for (row_type row = 0; row < nrows(); ++row) {
2544 for (col_type col = 0; col < ncols(); ++col) {
2546 << cell(index(row, col))
2552 docstring const & num = numbers_[row];
2554 os << '(' << num << ')';
2561 os << ETag("mtable");
2565 void InsetMathHull::mathAsLatex(WriteStream & os) const
2567 MathEnsurer ensurer(os, false);
2568 bool havenumbers = haveNumbers();
2569 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2572 os << cell(index(0, 0));
2576 os << "<table class='mathtable'>";
2577 for (row_type row = 0; row < nrows(); ++row) {
2579 for (col_type col = 0; col < ncols(); ++col) {
2580 os << "<td class='math'>";
2581 os << cell(index(row, col));
2586 docstring const & num = numbers_[row];
2588 os << '(' << num << ')';
2597 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2599 BufferParams::MathOutput const mathtype =
2600 buffer().masterBuffer()->params().html_math_output;
2602 bool success = false;
2604 // we output all the labels just at the beginning of the equation.
2605 // this should be fine.
2606 for (size_t i = 0; i != label_.size(); ++i) {
2607 InsetLabel const * const il = label_[i];
2613 // FIXME Eventually we would like to do this inset by inset.
2614 if (mathtype == BufferParams::MathML) {
2615 odocstringstream os;
2620 } catch (MathExportException const &) {}
2622 if (getType() == hullSimple)
2623 xs << html::StartTag("math",
2624 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2626 xs << html::StartTag("math",
2627 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2628 xs << XHTMLStream::ESCAPE_NONE
2630 << html::EndTag("math");
2632 } else if (mathtype == BufferParams::HTML) {
2633 odocstringstream os;
2638 } catch (MathExportException const &) {}
2640 string const tag = (getType() == hullSimple) ? "span" : "div";
2641 xs << html::StartTag(tag, "class='formula'", true)
2642 << XHTMLStream::ESCAPE_NONE
2644 << html::EndTag(tag);
2648 // what we actually want is this:
2650 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2652 // || mathtype == BufferParams::Images
2654 // but what follows is equivalent, since we'll enter only if either (a) we
2655 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2656 // aren't doing LaTeX.
2658 // so this is for Images.
2659 if (!success && mathtype != BufferParams::LaTeX) {
2660 graphics::PreviewImage const * pimage = 0;
2662 loadPreview(docit_);
2663 pimage = preview_->getPreviewImage(buffer());
2664 // FIXME Do we always have png?
2667 if (pimage || op.dryrun) {
2668 string const filename = pimage ? pimage->filename().onlyFileName()
2669 : "previewimage.png";
2671 // if we are not in the master buffer, then we need to see that the
2672 // generated image is copied there; otherwise, preview fails.
2673 Buffer const * mbuf = buffer().masterBuffer();
2674 if (mbuf != &buffer()) {
2675 string mbtmp = mbuf->temppath();
2676 FileName const mbufimg(support::addName(mbtmp, filename));
2677 pimage->filename().copyTo(mbufimg);
2679 // add the file to the list of files to be exported
2680 op.exportdata->addExternalFile("xhtml", pimage->filename());
2683 string const tag = (getType() == hullSimple) ? "span" : "div";
2685 << html::StartTag(tag, "style = \"text-align: center;\"")
2686 << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2687 << html::EndTag(tag)
2693 // so we'll pass this test if we've failed everything else, or
2694 // if mathtype was LaTeX, since we won't have entered any of the
2696 if (!success /* || mathtype != BufferParams::LaTeX */) {
2697 // Unfortunately, we cannot use latexString() because we do not want
2698 // $...$ or whatever.
2699 odocstringstream ls;
2700 otexrowstream ots(ls);
2701 WriteStream wi(ots, false, true, WriteStream::wsPreview);
2702 ModeSpecifier specifier(wi, MATH_MODE);
2704 docstring const latex = ls.str();
2706 // class='math' allows for use of jsMath
2707 // http://www.math.union.edu/~dpvc/jsMath/
2709 // probably should allow for some kind of customization here
2710 string const tag = (getType() == hullSimple) ? "span" : "div";
2711 xs << html::StartTag(tag, "class='math'")
2713 << html::EndTag(tag)
2720 void InsetMathHull::toString(odocstream & os) const
2722 odocstringstream ods;
2723 plaintext(ods, OutputParams(0));
2728 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2730 odocstringstream ods;
2733 // FIXME: this results in spilling TeX into the LyXHTML output since the
2734 // outliner is used to generate the LyXHTML list of figures/etc.
2740 string InsetMathHull::contextMenuName() const
2742 return "context-math";
2746 void InsetMathHull::recordLocation(DocIterator const & di)
2752 bool InsetMathHull::canPaintChange(BufferView const &) const
2754 // We let RowPainter do it seamlessly for inline insets
2755 return display() != Inline;