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 "InsetMathGrid.h"
19 #include "InsetMathNest.h"
20 #include "InsetMathScript.h"
21 #include "MathExtern.h"
22 #include "MathFactory.h"
23 #include "MathStream.h"
24 #include "MathSupport.h"
27 #include "BufferParams.h"
28 #include "BufferView.h"
30 #include "CutAndPaste.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
36 #include "LaTeXFeatures.h"
38 #include "MacroTable.h"
39 #include "MathMacro.h"
40 #include "MathMacroTemplate.h"
41 #include "output_xhtml.h"
42 #include "Paragraph.h"
43 #include "ParIterator.h"
45 #include "TextClass.h"
46 #include "TextPainter.h"
47 #include "TocBackend.h"
49 #include "insets/InsetLabel.h"
50 #include "insets/InsetRef.h"
51 #include "insets/RenderPreview.h"
53 #include "graphics/GraphicsImage.h"
54 #include "graphics/PreviewImage.h"
55 #include "graphics/PreviewLoader.h"
57 #include "frontends/alert.h"
58 #include "frontends/Painter.h"
60 #include "support/convert.h"
61 #include "support/lassert.h"
62 #include "support/debug.h"
63 #include "support/filetools.h"
64 #include "support/gettext.h"
65 #include "support/lstrings.h"
70 using namespace lyx::support;
74 using cap::grabAndEraseSelection;
75 using cap::reduceSelectionToOneCell;
79 int getCols(HullType type)
96 // returns position of first relation operator in the array
97 // used for "intelligent splitting"
98 size_t firstRelOp(MathData const & ar)
100 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
101 if ((*it)->isRelOp())
102 return it - ar.begin();
107 char const * star(bool numbered)
109 return numbered ? "" : "*";
113 } // end anon namespace
116 HullType hullType(docstring const & s)
118 if (s == "none") return hullNone;
119 if (s == "simple") return hullSimple;
120 if (s == "equation") return hullEquation;
121 if (s == "eqnarray") return hullEqnArray;
122 if (s == "align") return hullAlign;
123 if (s == "alignat") return hullAlignAt;
124 if (s == "xalignat") return hullXAlignAt;
125 if (s == "xxalignat") return hullXXAlignAt;
126 if (s == "multline") return hullMultline;
127 if (s == "gather") return hullGather;
128 if (s == "flalign") return hullFlAlign;
129 if (s == "regexp") return hullRegexp;
130 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
135 docstring hullName(HullType type)
138 case hullNone: return from_ascii("none");
139 case hullSimple: return from_ascii("simple");
140 case hullEquation: return from_ascii("equation");
141 case hullEqnArray: return from_ascii("eqnarray");
142 case hullAlign: return from_ascii("align");
143 case hullAlignAt: return from_ascii("alignat");
144 case hullXAlignAt: return from_ascii("xalignat");
145 case hullXXAlignAt: return from_ascii("xxalignat");
146 case hullMultline: return from_ascii("multline");
147 case hullGather: return from_ascii("gather");
148 case hullFlAlign: return from_ascii("flalign");
149 case hullRegexp: return from_ascii("regexp");
151 lyxerr << "unknown hull type '" << type << "'" << endl;
152 return from_ascii("none");
156 static InsetLabel * dummy_pointer = 0;
158 InsetMathHull::InsetMathHull(Buffer * buf)
159 : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, NUMBER),
160 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
161 preview_(new RenderPreview(this))
163 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
164 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
165 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
166 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
173 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
174 : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, NUMBER),
175 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
176 preview_(new RenderPreview(this))
184 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
190 InsetMathHull::~InsetMathHull()
192 for (size_t i = 0; i < label_.size(); ++i)
197 Inset * InsetMathHull::clone() const
199 return new InsetMathHull(*this);
203 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
207 InsetMathGrid::operator=(other);
209 numbered_ = other.numbered_;
210 numbers_ = other.numbers_;
211 buffer_ = other.buffer_;
212 for (size_t i = 0; i < label_.size(); ++i)
214 label_ = other.label_;
215 for (size_t i = 0; i != label_.size(); ++i) {
217 label_[i] = new InsetLabel(*label_[i]);
219 preview_.reset(new RenderPreview(*other.preview_, this));
225 void InsetMathHull::setBuffer(Buffer & buffer)
227 InsetMathGrid::setBuffer(buffer);
229 for (size_t i = 0; i != label_.size(); ++i) {
231 label_[i]->setBuffer(buffer);
236 // FIXME This should really be controlled by the TOC level, or
237 // something of the sort.
239 const char * counters_to_save[] = {"section", "chapter"};
240 unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
244 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
247 //FIXME: buffer_ should be set at creation for this inset! Problem is
248 // This inset is created at too many places (see Parser::parse1() in
253 // if any of the equations are numbered, then we want to save the values
254 // of some of the counters.
256 BufferParams const & bp = buffer_->params();
257 string const & lang = it->getParLanguage(bp)->code();
259 buffer_->masterBuffer()->params().documentClass().counters();
261 // right now, we only need to do this at export time
262 if (utype == OutputUpdate) {
263 for (size_t i = 0; i < numcnts; ++i) {
264 docstring const cnt = from_ascii(counters_to_save[i]);
265 if (cnts.hasCounter(cnt))
266 counter_map[cnt] = cnts.value(cnt);
270 // this has to be done separately
271 docstring const eqstr = from_ascii("equation");
272 if (cnts.hasCounter(eqstr)) {
273 if (utype == OutputUpdate)
274 counter_map[eqstr] = cnts.value(eqstr);
275 for (size_t i = 0; i != label_.size(); ++i) {
277 cnts.step(eqstr, utype);
278 numbers_[i] = cnts.theCounter(eqstr, lang);
280 numbers_[i] = empty_docstring();
286 for (size_t i = 0; i != label_.size(); ++i) {
288 label_[i]->updateBuffer(it, utype);
291 InsetMathGrid::updateBuffer(it, utype);
295 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active,
296 UpdateType utype) const
299 //FIXME: buffer_ should be set at creation for this inset! Problem is
300 // This inset is created at too many places (see Parser::parse1() in
305 shared_ptr<Toc> toc = buffer().tocBackend().toc("equation");
307 for (row_type row = 0; row != nrows(); ++row) {
311 label_[row]->addToToc(pit, output_active, utype);
312 toc->push_back(TocItem(pit, 0, nicelabel(row), output_active));
317 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
319 if (previewState(&cur.bv())) {
323 return InsetMathNest::editXY(cur, x, y);
327 InsetMath::mode_type InsetMathHull::currentMode() const
329 if (type_ == hullNone)
330 return UNDECIDED_MODE;
331 // definitely math mode ...
336 bool InsetMathHull::idxFirst(Cursor & cur) const
344 bool InsetMathHull::idxLast(Cursor & cur) const
346 cur.idx() = nargs() - 1;
347 cur.pos() = cur.lastpos();
352 // FIXME: InsetMathGrid should be changed to let the real column alignment be
353 // given by a virtual method like displayColAlign, because the values produced
354 // by defaultColAlign can be invalidated by lfuns such as add-column. For the
355 // moment the values produced by defaultColAlign are not used, notably because
356 // alignment is not implemented in the LyXHTML output.
357 char InsetMathHull::defaultColAlign(col_type col)
359 return colAlign(type_, col);
363 char InsetMathHull::displayColAlign(idx_type idx) const
367 row_type const r = row(idx);
370 if (r == nrows() - 1)
381 return colAlign(type_, col(idx));
385 return InsetMathGrid::displayColAlign(idx);
389 int InsetMathHull::displayColSpace(col_type col) const
391 return colSpace(type_, col);
395 // FIXME: same comment as for defaultColAlign applies.
396 int InsetMathHull::defaultColSpace(col_type col)
398 return colSpace(type_, col);
402 docstring InsetMathHull::standardFont() const
407 font_name = from_ascii("texttt");
410 font_name = from_ascii("lyxnochange");
413 font_name = from_ascii("mathnormal");
419 ColorCode InsetMathHull::standardColor() const
425 color = Color_foreground;
434 bool InsetMathHull::previewState(const BufferView *const bv) const
436 if (!editing(bv) && RenderPreview::previewMath()
437 && type_ != hullRegexp)
439 graphics::PreviewImage const * pimage =
440 preview_->getPreviewImage(bv->buffer());
441 return pimage && pimage->image();
448 static const int ERROR_FRAME_WIDTH = 2;
451 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
453 if (previewState(mi.base.bv)) {
454 preview_->metrics(mi, dim);
455 if (previewTooSmall(dim)) {
456 // preview image is too small
457 dim.wid += 2 * ERROR_FRAME_WIDTH;
458 dim.asc += 2 * ERROR_FRAME_WIDTH;
460 // insert a one pixel gap in front of the formula
463 dim.des += displayMargin();
465 // Cache the inset dimension.
466 setDimCache(mi, dim);
470 FontSetChanger dummy1(mi.base, standardFont());
471 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
473 // let the cells adjust themselves
474 InsetMathGrid::metrics(mi, dim);
477 dim.asc += displayMargin();
478 dim.des += displayMargin();
481 if (numberedType()) {
482 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
484 for (row_type row = 0; row < nrows(); ++row)
485 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
491 if (type_ == hullRegexp)
493 // make it at least as high as the current font
496 math_font_max_dim(mi.base.font, asc, des);
497 dim.asc = max(dim.asc, asc);
498 dim.des = max(dim.des, des);
499 // Cache the inset dimension.
500 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
501 setDimCache(mi, dim);
505 bool InsetMathHull::previewTooSmall(Dimension const & dim) const
507 return dim.width() <= 10 && dim.height() <= 10;
511 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
513 BufferView const * const bv = pi.base.bv;
514 if (previewState(bv)) {
515 Dimension const dim = dimension(*pi.base.bv);
516 if (previewTooSmall(dim))
518 return graphics::PreviewLoader::backgroundColor();
524 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
526 Dimension const dim = dimension(*pi.base.bv);
527 if (previewTooSmall(dim)) {
528 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
529 dim.wid, dim.asc + dim.des, backgroundColor(pi));
532 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
533 dim.asc + dim.des - 1, pi.backgroundColor(this));
537 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
539 BufferView const * const bv = pi.base.bv;
541 if (type_ == hullRegexp) {
542 Dimension const dim = dimension(*bv);
543 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
544 dim.width() - 2, dim.height() - 2, Color_regexpframe);
547 if (previewState(bv)) {
548 Dimension const dim = dimension(*bv);
549 if (previewTooSmall(dim)) {
550 // we have an extra frame
551 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
553 // one pixel gap in front
554 preview_->draw(pi, x + 1, y);
556 setPosCache(pi, x, y);
560 ColorCode color = pi.selected && lyxrc.use_system_colors
561 ? Color_selectiontext : standardColor();
562 bool const really_change_color = pi.base.font.color() == Color_none;
563 ColorChanger dummy0(pi.base.font, color, really_change_color);
564 FontSetChanger dummy1(pi.base, standardFont());
565 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
567 InsetMathGrid::draw(pi, x + 1, y);
569 if (numberedType()) {
570 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
571 for (row_type row = 0; row < nrows(); ++row) {
572 int const yy = y + rowinfo_[row].offset_;
573 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
574 docstring const nl = nicelabel(row);
578 setPosCache(pi, x, y);
582 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
585 InsetMathGrid::metricsT(mi, dim);
588 TexRow texrow(false);
589 otexrowstream ots(os,texrow);
590 WriteStream wi(ots, false, true, WriteStream::wsDefault);
592 dim.wid = os.str().size();
599 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
602 InsetMathGrid::drawT(pain, x, y);
605 TexRow texrow(false);
606 otexrowstream ots(os,texrow);
607 WriteStream wi(ots, false, true, WriteStream::wsDefault);
609 pain.draw(x, y, os.str().c_str());
614 static docstring latexString(InsetMathHull const & inset)
617 // This has to be static, because a preview snippet or a math
618 // macro containing math in text mode (such as $\text{$\phi$}$ or
619 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
620 // first time as a whole, and the second time only the inner math.
621 // In this last case inset.buffer() would be invalid.
622 static Encoding const * encoding = 0;
623 if (inset.isBufferValid())
624 encoding = &(inset.buffer().params().encoding());
625 TexRow texrow(false);
626 otexrowstream ots(ls,texrow);
627 WriteStream wi(ots, false, true, WriteStream::wsPreview, encoding);
633 void InsetMathHull::initUnicodeMath() const
635 // Trigger classification of the unicode symbols in this inset
636 docstring const dummy = latexString(*this);
640 void InsetMathHull::addPreview(DocIterator const & inset_pos,
641 graphics::PreviewLoader & /*ploader*/) const
643 if (RenderPreview::previewMath()) {
644 preparePreview(inset_pos);
649 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
650 MacroNameSet & macros, MacroNameSet & defs) const
652 MacroNameSet::iterator const end = macros.end();
654 for (size_t i = 0; i < md.size(); ++i) {
655 MathMacro const * mi = md[i].nucleus()->asMacro();
656 MathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
657 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
658 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
659 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
660 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
662 // Look for macros in the arguments of this macro.
663 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
664 usedMacros(mi->cell(idx), pos, macros, defs);
665 // Make sure this is a macro defined in the document
666 // (as we also spot the macros in the symbols file)
667 // or that we have not already accounted for it.
668 docstring const name = mi->name();
669 if (macros.find(name) == end)
672 // Look for macros in the definition of this macro.
673 MathData ar(pos.buffer());
674 MacroData const * data =
675 pos.buffer()->getMacro(name, pos, true);
677 odocstringstream macro_def;
678 data->write(macro_def, true);
680 defs.insert(macro_def.str());
681 asArray(data->definition(), ar);
683 usedMacros(ar, pos, macros, defs);
685 MathData ar(pos.buffer());
686 asArray(mt->definition(), ar);
687 usedMacros(ar, pos, macros, defs);
689 if (!si->nuc().empty())
690 usedMacros(si->nuc(), pos, macros, defs);
692 usedMacros(si->down(), pos, macros, defs);
694 usedMacros(si->up(), pos, macros, defs);
695 } else if (fi || gi) {
696 idx_type nidx = fi ? fi->nargs() : gi->nargs();
697 for (idx_type idx = 0; idx < nidx; ++idx)
698 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
701 usedMacros(ni->cell(0), pos, macros, defs);
707 void InsetMathHull::preparePreview(DocIterator const & pos,
708 bool forexport) const
710 // there is no need to do all the macro stuff if we're not
711 // actually going to generate the preview.
712 if (!RenderPreview::previewMath() && !forexport)
715 Buffer const * buffer = pos.buffer();
717 // collect macros at this position
719 buffer->listMacroNames(macros);
721 // collect definitions only for the macros used in this inset
723 for (idx_type idx = 0; idx < nargs(); ++idx)
724 usedMacros(cell(idx), pos, macros, defs);
726 MacroNameSet::iterator it = defs.begin();
727 MacroNameSet::iterator end = defs.end();
728 docstring macro_preamble;
729 for (; it != end; ++it)
730 macro_preamble.append(*it);
732 // set the font series and size for this snippet
733 DocIterator dit = pos;
734 while (dit.inMathed())
736 Paragraph const & par = dit.paragraph();
737 Font font = par.getFontSettings(buffer->params(), dit.pos());
738 font.fontInfo().realize(par.layout().font);
739 string const lsize = font.latexSize();
742 if (font.fontInfo().series() == BOLD_SERIES) {
743 setfont += from_ascii("\\textbf{");
746 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
747 setfont += from_ascii("\\" + lsize + '\n');
750 if (forexport && haveNumbers()) {
751 docstring eqstr = from_ascii("equation");
752 CounterMap::const_iterator it = counter_map.find(eqstr);
753 if (it != counter_map.end()) {
754 int num = it->second;
756 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
757 '{' + convert<docstring>(num) + '}' + '\n';
759 for (size_t i = 0; i != numcnts; ++i) {
760 docstring cnt = from_ascii(counters_to_save[i]);
761 it = counter_map.find(cnt);
762 if (it == counter_map.end())
764 int num = it->second;
766 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
767 '{' + convert<docstring>(num) + '}';
770 docstring const snippet = macro_preamble + setfont + setcnt
771 + latexString(*this) + endfont;
772 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
773 preview_->addPreview(snippet, *buffer, forexport);
777 void InsetMathHull::reloadPreview(DocIterator const & pos) const
780 preview_->startLoading(*pos.buffer());
784 void InsetMathHull::loadPreview(DocIterator const & pos) const
786 bool const forexport = true;
787 preparePreview(pos, forexport);
788 preview_->startLoading(*pos.buffer(), forexport);
792 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
794 if (RenderPreview::previewMath()) {
796 cur.screenUpdateFlags(Update::Force);
802 docstring InsetMathHull::label(row_type row) const
804 LASSERT(row < nrows(), return docstring());
805 if (InsetLabel * il = label_[row])
806 return il->screenLabel();
811 void InsetMathHull::label(row_type row, docstring const & label)
813 //lyxerr << "setting label '" << label << "' for row " << row << endl;
817 label_[row] = dummy_pointer;
820 label_[row]->updateLabelAndRefs(label);
822 label_[row]->setParam("name", label);
826 InsetCommandParams p(LABEL_CODE);
828 label_[row] = new InsetLabel(buffer_, p);
830 label_[row]->setBuffer(buffer());
834 void InsetMathHull::numbered(row_type row, Numbered num)
836 numbered_[row] = num;
837 if (!numbered(row) && label_[row]) {
844 bool InsetMathHull::numbered(row_type row) const
846 return numbered_[row] == NUMBER;
850 bool InsetMathHull::ams() const
868 for (size_t row = 0; row < numbered_.size(); ++row)
869 if (numbered_[row] == NOTAG)
875 Inset::DisplayType InsetMathHull::display() const
877 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
882 bool InsetMathHull::numberedType() const
884 if (type_ == hullNone)
886 if (type_ == hullSimple)
888 if (type_ == hullXXAlignAt)
890 if (type_ == hullRegexp)
892 for (row_type row = 0; row < nrows(); ++row)
899 void InsetMathHull::validate(LaTeXFeatures & features) const
901 if (features.runparams().isLaTeX()) {
903 features.require("amsmath");
905 if (type_ == hullRegexp) {
906 features.require("color");
907 string frcol = lcolor.getLaTeXName(Color_regexpframe);
908 string bgcol = "white";
909 features.addPreambleSnippet(
910 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
911 + frcol + string("}{")
912 + bgcol + string("}{\\ensuremath{\\mathtt{#1}}}}"));
913 features.addPreambleSnippet(
914 string("\\newcommand{\\endregexp}{}"));
917 // Validation is necessary only if not using AMS math.
918 // To be safe, we will always run mathedvalidate.
919 //if (features.amsstyle)
922 //features.binom = true;
923 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
924 // it would be better to do this elsewhere, but we can't validate in
925 // InsetMathMatrix and we have no way, outside MathExtern, to know if
926 // we even have any matrices.
927 features.addCSSSnippet(
928 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
929 "table.matrix td{padding: 0.25px;}\n"
930 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
931 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
933 InsetMathGrid::validate(features);
937 void InsetMathHull::header_write(WriteStream & os) const
939 bool n = numberedType();
956 os << "\\begin{equation" << star(n) << "}\n";
968 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
975 os << "\\begin{" << hullName(type_) << star(n) << '}'
976 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
982 os << "\\begin{" << hullName(type_) << '}'
983 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
993 os << "\\begin{unknown" << star(n) << "}\n";
999 void InsetMathHull::footer_write(WriteStream & os) const
1001 bool n = numberedType();
1016 os << "\\end{equation" << star(n) << "}\n";
1030 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1036 os << "\\end{" << hullName(type_) << "}\n";
1040 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1041 os << "\\endregexp{}}";
1047 os << "\\end{unknown" << star(n) << "}\n";
1053 bool InsetMathHull::isTable() const
1075 bool InsetMathHull::rowChangeOK() const
1078 type_ == hullEqnArray || type_ == hullAlign ||
1079 type_ == hullFlAlign || type_ == hullAlignAt ||
1080 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1081 type_ == hullGather || type_ == hullMultline;
1085 bool InsetMathHull::colChangeOK() const
1088 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1089 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1093 void InsetMathHull::addRow(row_type row)
1098 bool numbered = numberedType();
1099 // Move the number and raw pointer, do not call label() (bug 7511)
1100 InsetLabel * label = dummy_pointer;
1101 docstring number = empty_docstring();
1102 if (type_ == hullMultline) {
1103 if (row + 1 == nrows()) {
1104 numbered_[row] = NONUMBER;
1105 swap(label, label_[row]);
1106 swap(number, numbers_[row]);
1111 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1112 numbers_.insert(numbers_.begin() + row + 1, number);
1113 label_.insert(label_.begin() + row + 1, label);
1114 InsetMathGrid::addRow(row);
1118 void InsetMathHull::swapRow(row_type row)
1122 if (row + 1 == nrows())
1124 swap(numbered_[row], numbered_[row + 1]);
1125 swap(numbers_[row], numbers_[row + 1]);
1126 swap(label_[row], label_[row + 1]);
1127 InsetMathGrid::swapRow(row);
1131 void InsetMathHull::delRow(row_type row)
1133 if (nrows() <= 1 || !rowChangeOK())
1135 if (row + 1 == nrows() && type_ == hullMultline) {
1136 swap(numbered_[row - 1], numbered_[row]);
1137 swap(numbers_[row - 1], numbers_[row]);
1138 swap(label_[row - 1], label_[row]);
1139 InsetMathGrid::delRow(row);
1142 InsetMathGrid::delRow(row);
1143 // The last dummy row has no number info nor a label.
1144 // Test nrows() + 1 because we have already erased the row.
1145 if (row == nrows() + 1)
1147 numbered_.erase(numbered_.begin() + row);
1148 numbers_.erase(numbers_.begin() + row);
1150 label_.erase(label_.begin() + row);
1154 void InsetMathHull::addCol(col_type col)
1158 InsetMathGrid::addCol(col);
1162 void InsetMathHull::delCol(col_type col)
1164 if (ncols() <= 1 || !colChangeOK())
1166 InsetMathGrid::delCol(col);
1170 docstring InsetMathHull::nicelabel(row_type row) const
1174 docstring const & val = numbers_[row];
1176 return '(' + val + ')';
1177 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1181 void InsetMathHull::glueall(HullType type)
1184 for (idx_type i = 0; i < nargs(); ++i)
1186 InsetLabel * label = 0;
1187 if (type == hullEquation) {
1188 // preserve first non-empty label
1189 for (row_type row = 0; row < nrows(); ++row) {
1191 label = label_[row];
1197 *this = InsetMathHull(buffer_, hullSimple);
1204 void InsetMathHull::splitTo2Cols()
1206 LASSERT(ncols() == 1, return);
1207 InsetMathGrid::addCol(1);
1208 for (row_type row = 0; row < nrows(); ++row) {
1209 idx_type const i = 2 * row;
1210 pos_type pos = firstRelOp(cell(i));
1211 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1212 cell(i).erase(pos, cell(i).size());
1217 void InsetMathHull::splitTo3Cols()
1219 LASSERT(ncols() < 3, return);
1222 InsetMathGrid::addCol(2);
1223 for (row_type row = 0; row < nrows(); ++row) {
1224 idx_type const i = 3 * row + 1;
1225 if (!cell(i).empty()) {
1226 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1227 cell(i).erase(1, cell(i).size());
1233 void InsetMathHull::changeCols(col_type cols)
1235 if (ncols() == cols)
1237 else if (ncols() < cols) {
1243 while (ncols() < cols)
1244 InsetMathGrid::addCol(ncols());
1250 for (row_type row = 0; row < nrows(); ++row) {
1251 idx_type const i = row * ncols();
1252 for (col_type col = cols; col < ncols(); ++col) {
1253 cell(i + cols - 1).append(cell(i + col));
1257 while (ncols() > cols) {
1258 InsetMathGrid::delCol(ncols() - 1);
1263 HullType InsetMathHull::getType() const
1269 void InsetMathHull::setType(HullType type)
1276 void InsetMathHull::mutate(HullType newtype)
1278 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1280 // we try to move along the chain
1281 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1283 // +-------------------------------------+
1284 // we use eqnarray as intermediate type for mutations that are not
1285 // directly supported because it handles labels and numbering for
1288 if (newtype == type_) {
1292 else if (newtype < hullNone) {
1297 else if (type_ == hullNone) {
1298 setType(hullSimple);
1303 else if (type_ == hullSimple) {
1304 if (newtype == hullNone) {
1308 setType(hullEquation);
1309 numbered(0, label_[0] ? true : false);
1314 else if (type_ == hullEquation) {
1315 if (newtype < type_) {
1316 setType(hullSimple);
1319 } else if (newtype == hullEqnArray) {
1320 // split it "nicely" on the first relop
1322 setType(hullEqnArray);
1323 } else if (newtype == hullMultline || newtype == hullGather) {
1326 // split it "nicely"
1333 else if (type_ == hullEqnArray) {
1334 if (newtype < type_) {
1337 } else { // align & Co.
1344 else if (type_ == hullAlign || type_ == hullAlignAt ||
1345 type_ == hullXAlignAt || type_ == hullFlAlign) {
1346 if (newtype < hullAlign) {
1348 setType(hullEqnArray);
1350 } else if (newtype == hullGather || newtype == hullMultline) {
1353 } else if (newtype == hullXXAlignAt) {
1354 for (row_type row = 0; row < nrows(); ++row)
1355 numbered(row, false);
1362 else if (type_ == hullXXAlignAt) {
1363 for (row_type row = 0; row < nrows(); ++row)
1364 numbered(row, false);
1365 if (newtype < hullAlign) {
1367 setType(hullEqnArray);
1369 } else if (newtype == hullGather || newtype == hullMultline) {
1377 else if (type_ == hullMultline || type_ == hullGather) {
1378 if (newtype == hullGather || newtype == hullMultline)
1380 else if (newtype == hullAlign || newtype == hullFlAlign ||
1381 newtype == hullAlignAt || newtype == hullXAlignAt) {
1384 } else if (newtype == hullXXAlignAt) {
1386 for (row_type row = 0; row < nrows(); ++row)
1387 numbered(row, false);
1391 setType(hullEqnArray);
1397 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1398 << "' to '" << to_utf8(hullName(newtype))
1399 << "' not implemented" << endl;
1404 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1405 bool last_eoln) const
1408 if (numberedType()) {
1409 if (label_[row] && numbered(row)) {
1410 docstring const name =
1411 latex ? escape(label_[row]->getParam("name"))
1412 : label_[row]->getParam("name");
1413 res += "\\label{" + name + '}';
1415 if (type_ != hullMultline) {
1416 if (numbered_[row] == NONUMBER)
1417 res += "\\nonumber ";
1418 else if (numbered_[row] == NOTAG)
1422 // Never add \\ on the last empty line of eqnarray and friends
1424 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1427 void InsetMathHull::write(WriteStream & os) const
1429 ModeSpecifier specifier(os, MATH_MODE);
1431 InsetMathGrid::write(os);
1436 void InsetMathHull::normalize(NormalStream & os) const
1438 os << "[formula " << hullName(type_) << ' ';
1439 InsetMathGrid::normalize(os);
1444 void InsetMathHull::infoize(odocstream & os) const
1446 os << bformat(_("Type: %1$s"), hullName(type_));
1450 void InsetMathHull::check() const
1452 LATTEST(numbered_.size() == nrows());
1453 LATTEST(numbers_.size() == nrows());
1454 LATTEST(label_.size() == nrows());
1458 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1462 idocstringstream iss(func.argument());
1463 iss >> dlang >> extra;
1465 extra = from_ascii("noextra");
1466 string const lang = to_ascii(dlang);
1468 // replace selection with result of computation
1469 if (reduceSelectionToOneCell(cur)) {
1471 asArray(grabAndEraseSelection(cur), ar);
1472 lyxerr << "use selection: " << ar << endl;
1473 cur.insert(pipeThroughExtern(lang, extra, ar));
1477 // only inline, display or eqnarray math is allowed
1478 if (getType() > hullEqnArray) {
1479 frontend::Alert::warning(_("Bad math environment"),
1480 _("Computation cannot be performed for AMS "
1481 "math environments.\nChange the math "
1482 "formula type and try again."));
1487 eq.push_back(MathAtom(new InsetMathChar('=')));
1489 // go to first item in line
1490 cur.idx() -= cur.idx() % ncols();
1493 if (getType() == hullSimple) {
1494 size_type pos = cur.cell().find_last(eq);
1496 if (pos == cur.cell().size()) {
1498 lyxerr << "use whole cell: " << ar << endl;
1500 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1501 lyxerr << "use partial cell form pos: " << pos << endl;
1503 cur.cell().append(eq);
1504 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1505 cur.pos() = cur.lastpos();
1509 if (getType() == hullEquation) {
1510 lyxerr << "use equation inset" << endl;
1511 mutate(hullEqnArray);
1512 MathData & ar = cur.cell();
1513 lyxerr << "use cell: " << ar << endl;
1517 cur.cell() = pipeThroughExtern(lang, extra, ar);
1518 // move to end of line
1519 cur.pos() = cur.lastpos();
1524 lyxerr << "use eqnarray" << endl;
1525 cur.idx() += 2 - cur.idx() % ncols();
1527 MathData ar = cur.cell();
1528 lyxerr << "use cell: " << ar << endl;
1529 // FIXME: temporarily disabled
1535 cur.cell() = pipeThroughExtern(lang, extra, ar);
1536 cur.pos() = cur.lastpos();
1541 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1543 //lyxerr << "action: " << cmd.action() << endl;
1544 switch (cmd.action()) {
1546 case LFUN_FINISHED_BACKWARD:
1547 case LFUN_FINISHED_FORWARD:
1548 case LFUN_FINISHED_RIGHT:
1549 case LFUN_FINISHED_LEFT:
1550 //lyxerr << "action: " << cmd.action() << endl;
1551 InsetMathGrid::doDispatch(cur, cmd);
1554 case LFUN_PARAGRAPH_BREAK:
1555 // just swallow this
1558 case LFUN_NEWLINE_INSERT:
1559 // some magic for the common case
1560 if (type_ == hullSimple || type_ == hullEquation) {
1561 cur.recordUndoInset();
1563 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1564 mutate(align ? hullAlign : hullEqnArray);
1565 // mutate() may change labels and such.
1566 cur.forceBufferUpdate();
1567 cur.idx() = nrows() * ncols() - 1;
1568 cur.pos() = cur.lastpos();
1570 InsetMathGrid::doDispatch(cur, cmd);
1573 case LFUN_MATH_NUMBER_TOGGLE: {
1574 //lyxerr << "toggling all numbers" << endl;
1575 cur.recordUndoInset();
1576 bool old = numberedType();
1577 if (type_ == hullMultline)
1578 numbered(nrows() - 1, !old);
1580 for (row_type row = 0; row < nrows(); ++row)
1581 numbered(row, !old);
1583 cur.message(old ? _("No number") : _("Number"));
1584 cur.forceBufferUpdate();
1588 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1589 cur.recordUndoInset();
1590 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1591 bool old = numbered(r);
1592 cur.message(old ? _("No number") : _("Number"));
1594 cur.forceBufferUpdate();
1598 case LFUN_LABEL_INSERT: {
1599 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1600 docstring old_label = label(r);
1601 docstring const default_label = from_ascii("eq:");
1602 if (old_label.empty())
1603 old_label = default_label;
1605 InsetCommandParams p(LABEL_CODE);
1606 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1607 string const data = InsetCommand::params2string(p);
1609 if (cmd.argument().empty())
1610 cur.bv().showDialog("label", data);
1612 FuncRequest fr(LFUN_INSET_INSERT, data);
1618 case LFUN_LABEL_COPY_AS_REFERENCE: {
1620 if (cmd.argument().empty() && &cur.inset() == this)
1621 // if there is no argument and we're inside math, we retrieve
1622 // the row number from the cursor position.
1623 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1625 // if there is an argument, find the corresponding label, else
1626 // check whether there is at least one label.
1627 for (row = 0; row != nrows(); ++row)
1628 if (numbered(row) && label_[row]
1629 && (cmd.argument().empty() || label(row) == cmd.argument()))
1636 InsetCommandParams p(REF_CODE, "ref");
1637 p["reference"] = label(row);
1638 cap::clearSelection();
1639 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1643 case LFUN_WORD_DELETE_FORWARD:
1644 case LFUN_CHAR_DELETE_FORWARD:
1645 if (col(cur.idx()) + 1 == ncols()
1646 && cur.pos() == cur.lastpos()
1647 && !cur.selection()) {
1648 if (!label(row(cur.idx())).empty()) {
1649 cur.recordUndoInset();
1650 label(row(cur.idx()), docstring());
1651 } else if (numbered(row(cur.idx()))) {
1652 cur.recordUndoInset();
1653 numbered(row(cur.idx()), false);
1654 cur.forceBufferUpdate();
1656 InsetMathGrid::doDispatch(cur, cmd);
1660 InsetMathGrid::doDispatch(cur, cmd);
1665 case LFUN_INSET_INSERT: {
1666 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1667 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1668 string const name = cmd.getArg(0);
1669 if (name == "label") {
1670 InsetCommandParams p(LABEL_CODE);
1671 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1672 docstring str = p["name"];
1673 cur.recordUndoInset();
1674 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1678 docstring old = label(r);
1681 // The label will take care of the reference update.
1685 // Newly created inset so initialize it.
1686 label_[r]->initView();
1689 cur.forceBufferUpdate();
1692 InsetMathGrid::doDispatch(cur, cmd);
1696 case LFUN_MATH_EXTERN:
1697 cur.recordUndoInset();
1701 case LFUN_MATH_MUTATE: {
1702 cur.recordUndoInset();
1703 row_type row = cur.row();
1704 col_type col = cur.col();
1705 mutate(hullType(cmd.argument()));
1706 cur.idx() = row * ncols() + col;
1707 if (cur.idx() > cur.lastidx()) {
1708 cur.idx() = cur.lastidx();
1709 cur.pos() = cur.lastpos();
1711 if (cur.pos() > cur.lastpos())
1712 cur.pos() = cur.lastpos();
1714 cur.forceBufferUpdate();
1715 // FIXME: find some more clever handling of the selection,
1716 // i.e. preserve it.
1717 cur.clearSelection();
1718 //cur.dispatched(FINISHED);
1722 case LFUN_MATH_DISPLAY: {
1723 cur.recordUndoInset();
1724 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1725 // if the cursor is in a cell that got merged, move it to
1726 // start of the hull inset.
1727 if (cur.idx() > 0) {
1731 if (cur.pos() > cur.lastpos())
1732 cur.pos() = cur.lastpos();
1737 case LFUN_TABULAR_FEATURE:
1741 InsetMathGrid::doDispatch(cur, cmd);
1745 InsetMathGrid::doDispatch(cur, cmd);
1751 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1752 FuncStatus & status) const
1754 switch (cmd.action()) {
1755 case LFUN_FINISHED_BACKWARD:
1756 case LFUN_FINISHED_FORWARD:
1757 case LFUN_FINISHED_RIGHT:
1758 case LFUN_FINISHED_LEFT:
1761 case LFUN_NEWLINE_INSERT:
1762 case LFUN_MATH_EXTERN:
1764 status.setEnabled(true);
1767 // we never allow this in math, and we want to bind enter
1768 // to another actions in command-alternatives
1769 case LFUN_PARAGRAPH_BREAK:
1770 status.setEnabled(false);
1772 case LFUN_MATH_MUTATE: {
1773 HullType const ht = hullType(cmd.argument());
1774 status.setOnOff(type_ == ht);
1775 status.setEnabled(true);
1777 if (ht != hullSimple) {
1778 Cursor tmpcur = cur;
1779 while (!tmpcur.empty()) {
1780 InsetCode code = tmpcur.inset().lyxCode();
1781 if (code == BOX_CODE) {
1783 } else if (code == TABULAR_CODE) {
1784 FuncRequest tmpcmd(LFUN_MATH_DISPLAY);
1785 if (tmpcur.getStatus(tmpcmd, status) && !status.enabled())
1793 case LFUN_MATH_DISPLAY: {
1795 if (cur.depth() > 1) {
1796 Inset const & in = cur[cur.depth()-2].inset();
1797 if (in.lyxCode() == SCRIPT_CODE)
1798 enable = display() != Inline;
1800 status.setEnabled(enable);
1801 status.setOnOff(display() != Inline);
1805 case LFUN_MATH_NUMBER_TOGGLE:
1806 // FIXME: what is the right test, this or the one of
1808 status.setEnabled(display() != Inline);
1809 status.setOnOff(numberedType());
1812 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1813 // FIXME: what is the right test, this or the one of
1815 bool const enable = (type_ == hullMultline)
1816 ? (nrows() - 1 == cur.row())
1817 : display() != Inline;
1818 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1819 status.setEnabled(enable);
1820 status.setOnOff(enable && numbered(r));
1824 case LFUN_LABEL_INSERT:
1825 status.setEnabled(type_ != hullSimple);
1828 case LFUN_LABEL_COPY_AS_REFERENCE: {
1829 bool enabled = false;
1831 if (cmd.argument().empty() && &cur.inset() == this) {
1832 // if there is no argument and we're inside math, we retrieve
1833 // the row number from the cursor position.
1834 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1835 enabled = numberedType() && label_[row] && numbered(row);
1837 // if there is an argument, find the corresponding label, else
1838 // check whether there is at least one label.
1839 for (row_type row = 0; row != nrows(); ++row) {
1840 if (numbered(row) && label_[row] &&
1841 (cmd.argument().empty() || label(row) == cmd.argument())) {
1847 status.setEnabled(enabled);
1851 case LFUN_INSET_INSERT:
1852 if (cmd.getArg(0) == "label") {
1853 status.setEnabled(type_ != hullSimple);
1856 return InsetMathGrid::getStatus(cur, cmd, status);
1858 case LFUN_TABULAR_FEATURE: {
1861 string s = cmd.getArg(0);
1863 && (s == "append-row"
1864 || s == "delete-row"
1865 || s == "copy-row")) {
1866 status.message(bformat(
1867 from_utf8(N_("Can't change number of rows in '%1$s'")),
1869 status.setEnabled(false);
1873 && (s == "append-column"
1874 || s == "delete-column"
1875 || s == "copy-column")) {
1876 status.message(bformat(
1877 from_utf8(N_("Can't change number of columns in '%1$s'")),
1879 status.setEnabled(false);
1882 if (s == "add-vline-left" || s == "add-vline-right") {
1883 status.message(bformat(
1884 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1886 status.setEnabled(false);
1889 if (s == "valign-top" || s == "valign-middle"
1890 || s == "valign-bottom" || s == "align-left"
1891 || s == "align-center" || s == "align-right") {
1892 status.setEnabled(false);
1895 return InsetMathGrid::getStatus(cur, cmd, status);
1899 return InsetMathGrid::getStatus(cur, cmd, status);
1902 // This cannot really happen, but inserted to shut-up gcc
1903 return InsetMathGrid::getStatus(cur, cmd, status);
1907 /////////////////////////////////////////////////////////////////////
1911 // simply scrap this function if you want
1912 void InsetMathHull::mutateToText()
1915 // translate to latex
1917 latex(os, false, false);
1918 string str = os.str();
1921 Text * lt = view_->cursor().innerText();
1922 string::const_iterator cit = str.begin();
1923 string::const_iterator end = str.end();
1924 for (; cit != end; ++cit)
1925 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1928 //dispatch(LFUN_ESCAPE);
1933 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1934 docstring const & font)
1936 // this whole function is a hack and won't work for incremental font
1939 if (cur.inset().asInsetMath()->name() == font)
1940 cur.handleFont(to_utf8(font));
1942 cur.handleNest(createInsetMath(font, cur.buffer()));
1948 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1953 font.fromString(to_utf8(arg), b);
1954 if (font.fontInfo().color() != Color_inherit) {
1955 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1956 cur.handleNest(at, 0);
1961 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1964 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1965 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1966 enter_front ? idxFirst(cur) : idxLast(cur);
1967 // The inset formula dimension is not necessarily the same as the
1968 // one of the instant preview image, so we have to indicate to the
1969 // BufferView that a metrics update is needed.
1970 cur.screenUpdateFlags(Update::Force);
1974 void InsetMathHull::revealCodes(Cursor & cur) const
1976 if (!cur.inMathed())
1978 odocstringstream os;
1980 cur.message(os.str());
1982 // write something to the minibuffer
1983 // translate to latex
1987 string str = os.str();
1989 string::size_type pos = 0;
1991 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1994 else if (*it == '\0') {
1996 pos = it - str.begin();
2002 res = res.substr(pos - 30);
2003 if (res.size() > 60)
2004 res = res.substr(0, 60);
2010 /////////////////////////////////////////////////////////////////////
2014 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2017 // FIXME: completely broken
2018 static InsetMathHull * lastformula = 0;
2019 static CursorBase current = DocIterator(ibegin(nucleus()));
2021 static string laststr;
2023 if (lastformula != this || laststr != str) {
2024 //lyxerr << "reset lastformula to " << this << endl;
2027 current = ibegin(nucleus());
2029 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2033 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2035 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2036 CursorSlice & top = it.back();
2037 MathData const & a = top.asInsetMath()->cell(top.idx_);
2038 if (a.matchpart(ar, top.pos_)) {
2039 bv->cursor().setSelection(it, ar.size());
2041 top.pos_ += ar.size();
2047 //lyxerr << "not found!" << endl;
2054 void InsetMathHull::write(ostream & os) const
2056 odocstringstream oss;
2057 TexRow texrow(false);
2058 otexrowstream ots(oss,texrow);
2059 WriteStream wi(ots, false, false, WriteStream::wsDefault);
2062 os << to_utf8(oss.str());
2066 void InsetMathHull::read(Lexer & lex)
2069 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2070 operator=(*at->asHullInset());
2074 bool InsetMathHull::readQuiet(Lexer & lex)
2077 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2079 operator=(*at->asHullInset());
2084 int InsetMathHull::plaintext(odocstringstream & os,
2085 OutputParams const & op, size_t max_length) const
2087 // disables ASCII-art for export of equations. See #2275.
2088 if (0 && display()) {
2092 TextPainter tpain(dim.width(), dim.height());
2093 drawT(tpain, 0, dim.ascent());
2095 // reset metrics cache to "real" values
2097 return tpain.textheight();
2100 odocstringstream oss;
2101 TexRow texrow(false);
2102 otexrowstream ots(oss,texrow);
2103 Encoding const * const enc = encodings.fromLyXName("utf8");
2104 WriteStream wi(ots, false, true, WriteStream::wsDefault, enc);
2107 if (type_ == hullRegexp)
2110 for (row_type r = 0; r < nrows(); ++r) {
2111 for (col_type c = 0; c < ncols(); ++c)
2112 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2113 // if it's for the TOC, we write just the first line
2114 // and do not include the newline.
2115 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2117 if (r < nrows() - 1)
2121 docstring const str = oss.str();
2127 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
2132 if (getType() == hullSimple)
2133 name = from_ascii("inlineequation");
2135 name = from_ascii("informalequation");
2137 docstring bname = name;
2138 if (!label(0).empty())
2139 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
2141 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
2143 odocstringstream ls;
2145 otexstream ols(ls, texrow);
2146 if (runparams.flavor == OutputParams::XML) {
2147 ms << MTag("alt role='tex' ");
2148 // Workaround for db2latex: db2latex always includes equations with
2149 // \ensuremath{} or \begin{display}\end{display}
2150 // so we strip LyX' math environment
2151 WriteStream wi(ols, false, false, WriteStream::wsDefault, runparams.encoding);
2152 InsetMathGrid::write(wi);
2153 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2158 InsetMathGrid::mathmlize(ms);
2161 ms << MTag("alt role='tex'");
2162 latex(ols, runparams);
2163 res = texrow.rows();
2164 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2168 ms << from_ascii("<graphic fileref=\"eqn/");
2169 if (!label(0).empty())
2170 ms << sgml::cleanID(buffer(), runparams, label(0));
2172 ms << sgml::uniqueID(from_ascii("anon"));
2174 if (runparams.flavor == OutputParams::XML)
2175 ms << from_ascii("\"/>");
2177 ms << from_ascii("\">");
2179 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2181 return ms.line() + res;
2185 bool InsetMathHull::haveNumbers() const
2187 bool havenumbers = false;
2188 // inline formulas are never numbered (bug 7351 part 3)
2189 if (getType() == hullSimple)
2191 for (size_t i = 0; i != numbered_.size(); ++i) {
2202 // We need to do something about alignment here.
2204 // This duplicates code from InsetMathGrid, but
2205 // we need access here to number information,
2206 // and we simply do not have that in InsetMathGrid.
2207 void InsetMathHull::htmlize(HtmlStream & os) const
2209 bool const havenumbers = haveNumbers();
2210 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2213 os << cell(index(0, 0));
2217 os << MTag("table", "class='mathtable'");
2218 for (row_type row = 0; row < nrows(); ++row) {
2220 for (col_type col = 0; col < ncols(); ++col) {
2222 os << cell(index(row, col));
2227 docstring const & num = numbers_[row];
2229 os << '(' << num << ')';
2234 os << ETag("table");
2238 // this duplicates code from InsetMathGrid, but
2239 // we need access here to number information,
2240 // and we simply do not have that in InsetMathGrid.
2241 void InsetMathHull::mathmlize(MathStream & os) const
2243 bool const havenumbers = haveNumbers();
2244 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2247 os << MTag("mtable");
2248 char const * const celltag = havetable ? "mtd" : "mrow";
2249 // FIXME There does not seem to be wide support at the moment
2250 // for mlabeledtr, so we have to use just mtr for now.
2251 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2252 char const * const rowtag = "mtr";
2253 for (row_type row = 0; row < nrows(); ++row) {
2256 for (col_type col = 0; col < ncols(); ++col) {
2258 << cell(index(row, col))
2264 docstring const & num = numbers_[row];
2266 os << '(' << num << ')';
2273 os << ETag("mtable");
2277 void InsetMathHull::mathAsLatex(WriteStream & os) const
2279 MathEnsurer ensurer(os, false);
2280 bool havenumbers = haveNumbers();
2281 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2284 os << cell(index(0, 0));
2288 os << "<table class='mathtable'>";
2289 for (row_type row = 0; row < nrows(); ++row) {
2291 for (col_type col = 0; col < ncols(); ++col) {
2292 os << "<td class='math'>";
2293 os << cell(index(row, col));
2298 docstring const & num = numbers_[row];
2300 os << '(' << num << ')';
2309 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2311 BufferParams::MathOutput const mathtype =
2312 buffer().masterBuffer()->params().html_math_output;
2314 bool success = false;
2316 // we output all the labels just at the beginning of the equation.
2317 // this should be fine.
2318 for (size_t i = 0; i != label_.size(); ++i) {
2319 InsetLabel const * const il = label_[i];
2325 // FIXME Eventually we would like to do this inset by inset.
2326 if (mathtype == BufferParams::MathML) {
2327 odocstringstream os;
2332 } catch (MathExportException const &) {}
2334 if (getType() == hullSimple)
2335 xs << html::StartTag("math",
2336 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2338 xs << html::StartTag("math",
2339 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2340 xs << XHTMLStream::ESCAPE_NONE
2342 << html::EndTag("math");
2344 } else if (mathtype == BufferParams::HTML) {
2345 odocstringstream os;
2350 } catch (MathExportException const &) {}
2352 string const tag = (getType() == hullSimple) ? "span" : "div";
2353 xs << html::StartTag(tag, "class='formula'", true)
2354 << XHTMLStream::ESCAPE_NONE
2356 << html::EndTag(tag);
2360 // what we actually want is this:
2362 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2364 // || mathtype == BufferParams::Images
2366 // but what follows is equivalent, since we'll enter only if either (a) we
2367 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2368 // aren't doing LaTeX, in which case we are doing Images.
2369 if (!success && mathtype != BufferParams::LaTeX) {
2370 graphics::PreviewImage const * pimage = 0;
2372 loadPreview(docit_);
2373 pimage = preview_->getPreviewImage(buffer());
2374 // FIXME Do we always have png?
2377 if (pimage || op.dryrun) {
2378 string const filename = pimage ? pimage->filename().onlyFileName()
2379 : "previewimage.png";
2381 // if we are not in the master buffer, then we need to see that the
2382 // generated image is copied there; otherwise, preview fails.
2383 Buffer const * mbuf = buffer().masterBuffer();
2384 if (mbuf != &buffer()) {
2385 string mbtmp = mbuf->temppath();
2386 FileName const mbufimg(support::addName(mbtmp, filename));
2387 pimage->filename().copyTo(mbufimg);
2389 // add the file to the list of files to be exported
2390 op.exportdata->addExternalFile("xhtml", pimage->filename());
2393 string const tag = (getType() == hullSimple) ? "span" : "div";
2395 << html::StartTag(tag)
2396 << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2397 << html::EndTag(tag)
2403 // so we'll pass this test if we've failed everything else, or
2404 // if mathtype was LaTeX, since we won't have entered any of the
2406 if (!success /* || mathtype != BufferParams::LaTeX */) {
2407 // Unfortunately, we cannot use latexString() because we do not want
2408 // $...$ or whatever.
2409 odocstringstream ls;
2410 TexRow texrow(false);
2411 otexrowstream ots(ls,texrow);
2412 WriteStream wi(ots, false, true, WriteStream::wsPreview);
2413 ModeSpecifier specifier(wi, MATH_MODE);
2415 docstring const latex = ls.str();
2417 // class='math' allows for use of jsMath
2418 // http://www.math.union.edu/~dpvc/jsMath/
2420 // probably should allow for some kind of customization here
2421 string const tag = (getType() == hullSimple) ? "span" : "div";
2422 xs << html::StartTag(tag, "class='math'")
2424 << html::EndTag(tag)
2431 void InsetMathHull::toString(odocstream & os) const
2433 odocstringstream ods;
2434 plaintext(ods, OutputParams(0));
2439 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2441 odocstringstream ods;
2444 // FIXME: this results in spilling TeX into the LyXHTML output since the
2445 // outliner is used to generate the LyXHTML list of figures/etc.
2451 string InsetMathHull::contextMenuName() const
2453 return "context-math";
2457 void InsetMathHull::recordLocation(DocIterator const & di)