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. I suspect
355 // that for the moment the values produced by defaultColAlign are not used,
356 // notably because 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::defaultColSpace(col_type col)
391 if (type_ == hullAlign || type_ == hullAlignAt)
393 if (type_ == hullXAlignAt)
394 return (col & 1) ? 20 : 0;
395 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
396 return (col & 1) ? 40 : 0;
401 docstring InsetMathHull::standardFont() const
406 font_name = from_ascii("texttt");
409 font_name = from_ascii("lyxnochange");
412 font_name = from_ascii("mathnormal");
418 ColorCode InsetMathHull::standardColor() const
424 color = Color_foreground;
433 bool InsetMathHull::previewState(const BufferView *const bv) const
435 if (!editing(bv) && RenderPreview::previewMath()
436 && type_ != hullRegexp)
438 graphics::PreviewImage const * pimage =
439 preview_->getPreviewImage(bv->buffer());
440 return pimage && pimage->image();
447 static const int ERROR_FRAME_WIDTH = 2;
450 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
452 if (previewState(mi.base.bv)) {
453 preview_->metrics(mi, dim);
454 if (previewTooSmall(dim)) {
455 // preview image is too small
456 dim.wid += 2 * ERROR_FRAME_WIDTH;
457 dim.asc += 2 * ERROR_FRAME_WIDTH;
459 // insert a one pixel gap in front of the formula
462 dim.des += displayMargin();
464 // Cache the inset dimension.
465 setDimCache(mi, dim);
469 FontSetChanger dummy1(mi.base, standardFont());
470 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
472 // let the cells adjust themselves
473 InsetMathGrid::metrics(mi, dim);
476 dim.asc += displayMargin();
477 dim.des += displayMargin();
480 if (numberedType()) {
481 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
483 for (row_type row = 0; row < nrows(); ++row)
484 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
490 if (type_ == hullRegexp)
492 // make it at least as high as the current font
495 math_font_max_dim(mi.base.font, asc, des);
496 dim.asc = max(dim.asc, asc);
497 dim.des = max(dim.des, des);
498 // Cache the inset dimension.
499 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
500 setDimCache(mi, dim);
504 bool InsetMathHull::previewTooSmall(Dimension const & dim) const
506 return dim.width() <= 10 && dim.height() <= 10;
510 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
512 BufferView const * const bv = pi.base.bv;
513 if (previewState(bv)) {
514 Dimension const dim = dimension(*pi.base.bv);
515 if (previewTooSmall(dim))
517 return graphics::PreviewLoader::backgroundColor();
523 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
525 Dimension const dim = dimension(*pi.base.bv);
526 if (previewTooSmall(dim)) {
527 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
528 dim.wid, dim.asc + dim.des, backgroundColor(pi));
531 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
532 dim.asc + dim.des - 1, pi.backgroundColor(this));
536 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
538 BufferView const * const bv = pi.base.bv;
540 if (type_ == hullRegexp) {
541 Dimension const dim = dimension(*bv);
542 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
543 dim.width() - 2, dim.height() - 2, Color_regexpframe);
546 if (previewState(bv)) {
547 Dimension const dim = dimension(*bv);
548 if (previewTooSmall(dim)) {
549 // we have an extra frame
550 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
552 // one pixel gap in front
553 preview_->draw(pi, x + 1, y);
555 setPosCache(pi, x, y);
559 ColorCode color = pi.selected && lyxrc.use_system_colors
560 ? Color_selectiontext : standardColor();
561 bool const really_change_color = pi.base.font.color() == Color_none;
562 ColorChanger dummy0(pi.base.font, color, really_change_color);
563 FontSetChanger dummy1(pi.base, standardFont());
564 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
566 InsetMathGrid::draw(pi, x + 1, y);
568 if (numberedType()) {
569 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
570 for (row_type row = 0; row < nrows(); ++row) {
571 int const yy = y + rowinfo_[row].offset_;
572 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
573 docstring const nl = nicelabel(row);
577 setPosCache(pi, x, y);
581 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
584 InsetMathGrid::metricsT(mi, dim);
587 TexRow texrow(false);
588 otexrowstream ots(os,texrow);
589 WriteStream wi(ots, false, true, WriteStream::wsDefault);
591 dim.wid = os.str().size();
598 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
601 InsetMathGrid::drawT(pain, x, y);
604 TexRow texrow(false);
605 otexrowstream ots(os,texrow);
606 WriteStream wi(ots, false, true, WriteStream::wsDefault);
608 pain.draw(x, y, os.str().c_str());
613 static docstring latexString(InsetMathHull const & inset)
616 // This has to be static, because a preview snippet or a math
617 // macro containing math in text mode (such as $\text{$\phi$}$ or
618 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
619 // first time as a whole, and the second time only the inner math.
620 // In this last case inset.buffer() would be invalid.
621 static Encoding const * encoding = 0;
622 if (inset.isBufferValid())
623 encoding = &(inset.buffer().params().encoding());
624 TexRow texrow(false);
625 otexrowstream ots(ls,texrow);
626 WriteStream wi(ots, false, true, WriteStream::wsPreview, encoding);
632 void InsetMathHull::initUnicodeMath() const
634 // Trigger classification of the unicode symbols in this inset
635 docstring const dummy = latexString(*this);
639 void InsetMathHull::addPreview(DocIterator const & inset_pos,
640 graphics::PreviewLoader & /*ploader*/) const
642 if (RenderPreview::previewMath()) {
643 preparePreview(inset_pos);
648 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
649 MacroNameSet & macros, MacroNameSet & defs) const
651 MacroNameSet::iterator const end = macros.end();
653 for (size_t i = 0; i < md.size(); ++i) {
654 MathMacro const * mi = md[i].nucleus()->asMacro();
655 MathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
656 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
657 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
658 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
659 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
661 // Look for macros in the arguments of this macro.
662 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
663 usedMacros(mi->cell(idx), pos, macros, defs);
664 // Make sure this is a macro defined in the document
665 // (as we also spot the macros in the symbols file)
666 // or that we have not already accounted for it.
667 docstring const name = mi->name();
668 if (macros.find(name) == end)
671 // Look for macros in the definition of this macro.
672 MathData ar(pos.buffer());
673 MacroData const * data =
674 pos.buffer()->getMacro(name, pos, true);
676 odocstringstream macro_def;
677 data->write(macro_def, true);
679 defs.insert(macro_def.str());
680 asArray(data->definition(), ar);
682 usedMacros(ar, pos, macros, defs);
684 MathData ar(pos.buffer());
685 asArray(mt->definition(), ar);
686 usedMacros(ar, pos, macros, defs);
688 if (!si->nuc().empty())
689 usedMacros(si->nuc(), pos, macros, defs);
691 usedMacros(si->down(), pos, macros, defs);
693 usedMacros(si->up(), pos, macros, defs);
694 } else if (fi || gi) {
695 idx_type nidx = fi ? fi->nargs() : gi->nargs();
696 for (idx_type idx = 0; idx < nidx; ++idx)
697 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
700 usedMacros(ni->cell(0), pos, macros, defs);
706 void InsetMathHull::preparePreview(DocIterator const & pos,
707 bool forexport) const
709 // there is no need to do all the macro stuff if we're not
710 // actually going to generate the preview.
711 if (!RenderPreview::previewMath() && !forexport)
714 Buffer const * buffer = pos.buffer();
716 // collect macros at this position
718 buffer->listMacroNames(macros);
720 // collect definitions only for the macros used in this inset
722 for (idx_type idx = 0; idx < nargs(); ++idx)
723 usedMacros(cell(idx), pos, macros, defs);
725 MacroNameSet::iterator it = defs.begin();
726 MacroNameSet::iterator end = defs.end();
727 docstring macro_preamble;
728 for (; it != end; ++it)
729 macro_preamble.append(*it);
731 // set the font series and size for this snippet
732 DocIterator dit = pos;
733 while (dit.inMathed())
735 Paragraph const & par = dit.paragraph();
736 Font font = par.getFontSettings(buffer->params(), dit.pos());
737 font.fontInfo().realize(par.layout().font);
738 string const lsize = font.latexSize();
741 if (font.fontInfo().series() == BOLD_SERIES) {
742 setfont += from_ascii("\\textbf{");
745 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
746 setfont += from_ascii("\\" + lsize + '\n');
749 if (forexport && haveNumbers()) {
750 docstring eqstr = from_ascii("equation");
751 CounterMap::const_iterator it = counter_map.find(eqstr);
752 if (it != counter_map.end()) {
753 int num = it->second;
755 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
756 '{' + convert<docstring>(num) + '}' + '\n';
758 for (size_t i = 0; i != numcnts; ++i) {
759 docstring cnt = from_ascii(counters_to_save[i]);
760 it = counter_map.find(cnt);
761 if (it == counter_map.end())
763 int num = it->second;
765 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
766 '{' + convert<docstring>(num) + '}';
769 docstring const snippet = macro_preamble + setfont + setcnt
770 + latexString(*this) + endfont;
771 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
772 preview_->addPreview(snippet, *buffer, forexport);
776 void InsetMathHull::reloadPreview(DocIterator const & pos) const
779 preview_->startLoading(*pos.buffer());
783 void InsetMathHull::loadPreview(DocIterator const & pos) const
785 bool const forexport = true;
786 preparePreview(pos, forexport);
787 preview_->startLoading(*pos.buffer(), forexport);
791 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
793 if (RenderPreview::previewMath()) {
795 cur.screenUpdateFlags(Update::Force);
801 docstring InsetMathHull::label(row_type row) const
803 LASSERT(row < nrows(), return docstring());
804 if (InsetLabel * il = label_[row])
805 return il->screenLabel();
810 void InsetMathHull::label(row_type row, docstring const & label)
812 //lyxerr << "setting label '" << label << "' for row " << row << endl;
816 label_[row] = dummy_pointer;
819 label_[row]->updateLabelAndRefs(label);
821 label_[row]->setParam("name", label);
825 InsetCommandParams p(LABEL_CODE);
827 label_[row] = new InsetLabel(buffer_, p);
829 label_[row]->setBuffer(buffer());
833 void InsetMathHull::numbered(row_type row, Numbered num)
835 numbered_[row] = num;
836 if (!numbered(row) && label_[row]) {
843 bool InsetMathHull::numbered(row_type row) const
845 return numbered_[row] == NUMBER;
849 bool InsetMathHull::ams() const
867 for (size_t row = 0; row < numbered_.size(); ++row)
868 if (numbered_[row] == NOTAG)
874 Inset::DisplayType InsetMathHull::display() const
876 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
881 bool InsetMathHull::numberedType() const
883 if (type_ == hullNone)
885 if (type_ == hullSimple)
887 if (type_ == hullXXAlignAt)
889 if (type_ == hullRegexp)
891 for (row_type row = 0; row < nrows(); ++row)
898 void InsetMathHull::validate(LaTeXFeatures & features) const
900 if (features.runparams().isLaTeX()) {
902 features.require("amsmath");
904 if (type_ == hullRegexp) {
905 features.require("color");
906 string frcol = lcolor.getLaTeXName(Color_regexpframe);
907 string bgcol = "white";
908 features.addPreambleSnippet(
909 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
910 + frcol + string("}{")
911 + bgcol + string("}{\\ensuremath{\\mathtt{#1}}}}"));
912 features.addPreambleSnippet(
913 string("\\newcommand{\\endregexp}{}"));
916 // Validation is necessary only if not using AMS math.
917 // To be safe, we will always run mathedvalidate.
918 //if (features.amsstyle)
921 //features.binom = true;
922 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
923 // it would be better to do this elsewhere, but we can't validate in
924 // InsetMathMatrix and we have no way, outside MathExtern, to know if
925 // we even have any matrices.
926 features.addCSSSnippet(
927 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
928 "table.matrix td{padding: 0.25px;}\n"
929 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
930 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
932 InsetMathGrid::validate(features);
936 void InsetMathHull::header_write(WriteStream & os) const
938 bool n = numberedType();
955 os << "\\begin{equation" << star(n) << "}\n";
967 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
974 os << "\\begin{" << hullName(type_) << star(n) << '}'
975 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
981 os << "\\begin{" << hullName(type_) << '}'
982 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
992 os << "\\begin{unknown" << star(n) << "}\n";
998 void InsetMathHull::footer_write(WriteStream & os) const
1000 bool n = numberedType();
1015 os << "\\end{equation" << star(n) << "}\n";
1029 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1035 os << "\\end{" << hullName(type_) << "}\n";
1039 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1040 os << "\\endregexp{}}";
1046 os << "\\end{unknown" << star(n) << "}\n";
1052 bool InsetMathHull::isTable() const
1074 bool InsetMathHull::rowChangeOK() const
1077 type_ == hullEqnArray || type_ == hullAlign ||
1078 type_ == hullFlAlign || type_ == hullAlignAt ||
1079 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1080 type_ == hullGather || type_ == hullMultline;
1084 bool InsetMathHull::colChangeOK() const
1087 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1088 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1092 void InsetMathHull::addRow(row_type row)
1097 bool numbered = numberedType();
1098 // Move the number and raw pointer, do not call label() (bug 7511)
1099 InsetLabel * label = dummy_pointer;
1100 docstring number = empty_docstring();
1101 if (type_ == hullMultline) {
1102 if (row + 1 == nrows()) {
1103 numbered_[row] = NONUMBER;
1104 swap(label, label_[row]);
1105 swap(number, numbers_[row]);
1110 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1111 numbers_.insert(numbers_.begin() + row + 1, number);
1112 label_.insert(label_.begin() + row + 1, label);
1113 InsetMathGrid::addRow(row);
1117 void InsetMathHull::swapRow(row_type row)
1121 if (row + 1 == nrows())
1123 swap(numbered_[row], numbered_[row + 1]);
1124 swap(numbers_[row], numbers_[row + 1]);
1125 swap(label_[row], label_[row + 1]);
1126 InsetMathGrid::swapRow(row);
1130 void InsetMathHull::delRow(row_type row)
1132 if (nrows() <= 1 || !rowChangeOK())
1134 if (row + 1 == nrows() && type_ == hullMultline) {
1135 swap(numbered_[row - 1], numbered_[row]);
1136 swap(numbers_[row - 1], numbers_[row]);
1137 swap(label_[row - 1], label_[row]);
1138 InsetMathGrid::delRow(row);
1141 InsetMathGrid::delRow(row);
1142 // The last dummy row has no number info nor a label.
1143 // Test nrows() + 1 because we have already erased the row.
1144 if (row == nrows() + 1)
1146 numbered_.erase(numbered_.begin() + row);
1147 numbers_.erase(numbers_.begin() + row);
1149 label_.erase(label_.begin() + row);
1153 void InsetMathHull::addCol(col_type col)
1157 InsetMathGrid::addCol(col);
1161 void InsetMathHull::delCol(col_type col)
1163 if (ncols() <= 1 || !colChangeOK())
1165 InsetMathGrid::delCol(col);
1169 docstring InsetMathHull::nicelabel(row_type row) const
1173 docstring const & val = numbers_[row];
1175 return '(' + val + ')';
1176 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1180 void InsetMathHull::glueall(HullType type)
1183 for (idx_type i = 0; i < nargs(); ++i)
1185 InsetLabel * label = 0;
1186 if (type == hullEquation) {
1187 // preserve first non-empty label
1188 for (row_type row = 0; row < nrows(); ++row) {
1190 label = label_[row];
1196 *this = InsetMathHull(buffer_, hullSimple);
1203 void InsetMathHull::splitTo2Cols()
1205 LASSERT(ncols() == 1, return);
1206 InsetMathGrid::addCol(1);
1207 for (row_type row = 0; row < nrows(); ++row) {
1208 idx_type const i = 2 * row;
1209 pos_type pos = firstRelOp(cell(i));
1210 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1211 cell(i).erase(pos, cell(i).size());
1216 void InsetMathHull::splitTo3Cols()
1218 LASSERT(ncols() < 3, return);
1221 InsetMathGrid::addCol(2);
1222 for (row_type row = 0; row < nrows(); ++row) {
1223 idx_type const i = 3 * row + 1;
1224 if (!cell(i).empty()) {
1225 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1226 cell(i).erase(1, cell(i).size());
1232 void InsetMathHull::changeCols(col_type cols)
1234 if (ncols() == cols)
1236 else if (ncols() < cols) {
1242 while (ncols() < cols)
1243 InsetMathGrid::addCol(ncols());
1249 for (row_type row = 0; row < nrows(); ++row) {
1250 idx_type const i = row * ncols();
1251 for (col_type col = cols; col < ncols(); ++col) {
1252 cell(i + cols - 1).append(cell(i + col));
1256 while (ncols() > cols) {
1257 InsetMathGrid::delCol(ncols() - 1);
1262 HullType InsetMathHull::getType() const
1268 void InsetMathHull::setType(HullType type)
1275 void InsetMathHull::mutate(HullType newtype)
1277 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1279 // we try to move along the chain
1280 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1282 // +-------------------------------------+
1283 // we use eqnarray as intermediate type for mutations that are not
1284 // directly supported because it handles labels and numbering for
1287 if (newtype == type_) {
1291 else if (newtype < hullNone) {
1296 else if (type_ == hullNone) {
1297 setType(hullSimple);
1302 else if (type_ == hullSimple) {
1303 if (newtype == hullNone) {
1307 setType(hullEquation);
1308 numbered(0, label_[0] ? true : false);
1313 else if (type_ == hullEquation) {
1314 if (newtype < type_) {
1315 setType(hullSimple);
1318 } else if (newtype == hullEqnArray) {
1319 // split it "nicely" on the first relop
1321 setType(hullEqnArray);
1322 } else if (newtype == hullMultline || newtype == hullGather) {
1325 // split it "nicely"
1332 else if (type_ == hullEqnArray) {
1333 if (newtype < type_) {
1336 } else { // align & Co.
1343 else if (type_ == hullAlign || type_ == hullAlignAt ||
1344 type_ == hullXAlignAt || type_ == hullFlAlign) {
1345 if (newtype < hullAlign) {
1347 setType(hullEqnArray);
1349 } else if (newtype == hullGather || newtype == hullMultline) {
1352 } else if (newtype == hullXXAlignAt) {
1353 for (row_type row = 0; row < nrows(); ++row)
1354 numbered(row, false);
1361 else if (type_ == hullXXAlignAt) {
1362 for (row_type row = 0; row < nrows(); ++row)
1363 numbered(row, false);
1364 if (newtype < hullAlign) {
1366 setType(hullEqnArray);
1368 } else if (newtype == hullGather || newtype == hullMultline) {
1376 else if (type_ == hullMultline || type_ == hullGather) {
1377 if (newtype == hullGather || newtype == hullMultline)
1379 else if (newtype == hullAlign || newtype == hullFlAlign ||
1380 newtype == hullAlignAt || newtype == hullXAlignAt) {
1383 } else if (newtype == hullXXAlignAt) {
1385 for (row_type row = 0; row < nrows(); ++row)
1386 numbered(row, false);
1390 setType(hullEqnArray);
1396 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1397 << "' to '" << to_utf8(hullName(newtype))
1398 << "' not implemented" << endl;
1403 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1404 bool last_eoln) const
1407 if (numberedType()) {
1408 if (label_[row] && numbered(row)) {
1409 docstring const name =
1410 latex ? escape(label_[row]->getParam("name"))
1411 : label_[row]->getParam("name");
1412 res += "\\label{" + name + '}';
1414 if (type_ != hullMultline) {
1415 if (numbered_[row] == NONUMBER)
1416 res += "\\nonumber ";
1417 else if (numbered_[row] == NOTAG)
1421 // Never add \\ on the last empty line of eqnarray and friends
1423 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1426 void InsetMathHull::write(WriteStream & os) const
1428 ModeSpecifier specifier(os, MATH_MODE);
1430 InsetMathGrid::write(os);
1435 void InsetMathHull::normalize(NormalStream & os) const
1437 os << "[formula " << hullName(type_) << ' ';
1438 InsetMathGrid::normalize(os);
1443 void InsetMathHull::infoize(odocstream & os) const
1445 os << bformat(_("Type: %1$s"), hullName(type_));
1449 void InsetMathHull::check() const
1451 LATTEST(numbered_.size() == nrows());
1452 LATTEST(numbers_.size() == nrows());
1453 LATTEST(label_.size() == nrows());
1457 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1461 idocstringstream iss(func.argument());
1462 iss >> dlang >> extra;
1464 extra = from_ascii("noextra");
1465 string const lang = to_ascii(dlang);
1467 // replace selection with result of computation
1468 if (reduceSelectionToOneCell(cur)) {
1470 asArray(grabAndEraseSelection(cur), ar);
1471 lyxerr << "use selection: " << ar << endl;
1472 cur.insert(pipeThroughExtern(lang, extra, ar));
1476 // only inline, display or eqnarray math is allowed
1477 if (getType() > hullEqnArray) {
1478 frontend::Alert::warning(_("Bad math environment"),
1479 _("Computation cannot be performed for AMS "
1480 "math environments.\nChange the math "
1481 "formula type and try again."));
1486 eq.push_back(MathAtom(new InsetMathChar('=')));
1488 // go to first item in line
1489 cur.idx() -= cur.idx() % ncols();
1492 if (getType() == hullSimple) {
1493 size_type pos = cur.cell().find_last(eq);
1495 if (pos == cur.cell().size()) {
1497 lyxerr << "use whole cell: " << ar << endl;
1499 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1500 lyxerr << "use partial cell form pos: " << pos << endl;
1502 cur.cell().append(eq);
1503 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1504 cur.pos() = cur.lastpos();
1508 if (getType() == hullEquation) {
1509 lyxerr << "use equation inset" << endl;
1510 mutate(hullEqnArray);
1511 MathData & ar = cur.cell();
1512 lyxerr << "use cell: " << ar << endl;
1516 cur.cell() = pipeThroughExtern(lang, extra, ar);
1517 // move to end of line
1518 cur.pos() = cur.lastpos();
1523 lyxerr << "use eqnarray" << endl;
1524 cur.idx() += 2 - cur.idx() % ncols();
1526 MathData ar = cur.cell();
1527 lyxerr << "use cell: " << ar << endl;
1528 // FIXME: temporarily disabled
1534 cur.cell() = pipeThroughExtern(lang, extra, ar);
1535 cur.pos() = cur.lastpos();
1540 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1542 //lyxerr << "action: " << cmd.action() << endl;
1543 switch (cmd.action()) {
1545 case LFUN_FINISHED_BACKWARD:
1546 case LFUN_FINISHED_FORWARD:
1547 case LFUN_FINISHED_RIGHT:
1548 case LFUN_FINISHED_LEFT:
1549 //lyxerr << "action: " << cmd.action() << endl;
1550 InsetMathGrid::doDispatch(cur, cmd);
1553 case LFUN_PARAGRAPH_BREAK:
1554 // just swallow this
1557 case LFUN_NEWLINE_INSERT:
1558 // some magic for the common case
1559 if (type_ == hullSimple || type_ == hullEquation) {
1560 cur.recordUndoInset();
1562 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1563 mutate(align ? hullAlign : hullEqnArray);
1564 // mutate() may change labels and such.
1565 cur.forceBufferUpdate();
1566 cur.idx() = nrows() * ncols() - 1;
1567 cur.pos() = cur.lastpos();
1569 InsetMathGrid::doDispatch(cur, cmd);
1572 case LFUN_MATH_NUMBER_TOGGLE: {
1573 //lyxerr << "toggling all numbers" << endl;
1574 cur.recordUndoInset();
1575 bool old = numberedType();
1576 if (type_ == hullMultline)
1577 numbered(nrows() - 1, !old);
1579 for (row_type row = 0; row < nrows(); ++row)
1580 numbered(row, !old);
1582 cur.message(old ? _("No number") : _("Number"));
1583 cur.forceBufferUpdate();
1587 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1588 cur.recordUndoInset();
1589 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1590 bool old = numbered(r);
1591 cur.message(old ? _("No number") : _("Number"));
1593 cur.forceBufferUpdate();
1597 case LFUN_LABEL_INSERT: {
1598 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1599 docstring old_label = label(r);
1600 docstring const default_label = from_ascii("eq:");
1601 if (old_label.empty())
1602 old_label = default_label;
1604 InsetCommandParams p(LABEL_CODE);
1605 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1606 string const data = InsetCommand::params2string(p);
1608 if (cmd.argument().empty())
1609 cur.bv().showDialog("label", data);
1611 FuncRequest fr(LFUN_INSET_INSERT, data);
1617 case LFUN_LABEL_COPY_AS_REFERENCE: {
1619 if (cmd.argument().empty() && &cur.inset() == this)
1620 // if there is no argument and we're inside math, we retrieve
1621 // the row number from the cursor position.
1622 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1624 // if there is an argument, find the corresponding label, else
1625 // check whether there is at least one label.
1626 for (row = 0; row != nrows(); ++row)
1627 if (numbered(row) && label_[row]
1628 && (cmd.argument().empty() || label(row) == cmd.argument()))
1635 InsetCommandParams p(REF_CODE, "ref");
1636 p["reference"] = label(row);
1637 cap::clearSelection();
1638 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1642 case LFUN_WORD_DELETE_FORWARD:
1643 case LFUN_CHAR_DELETE_FORWARD:
1644 if (col(cur.idx()) + 1 == ncols()
1645 && cur.pos() == cur.lastpos()
1646 && !cur.selection()) {
1647 if (!label(row(cur.idx())).empty()) {
1648 cur.recordUndoInset();
1649 label(row(cur.idx()), docstring());
1650 } else if (numbered(row(cur.idx()))) {
1651 cur.recordUndoInset();
1652 numbered(row(cur.idx()), false);
1653 cur.forceBufferUpdate();
1655 InsetMathGrid::doDispatch(cur, cmd);
1659 InsetMathGrid::doDispatch(cur, cmd);
1664 case LFUN_INSET_INSERT: {
1665 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1666 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1667 string const name = cmd.getArg(0);
1668 if (name == "label") {
1669 InsetCommandParams p(LABEL_CODE);
1670 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1671 docstring str = p["name"];
1672 cur.recordUndoInset();
1673 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1677 docstring old = label(r);
1680 // The label will take care of the reference update.
1684 // Newly created inset so initialize it.
1685 label_[r]->initView();
1688 cur.forceBufferUpdate();
1691 InsetMathGrid::doDispatch(cur, cmd);
1695 case LFUN_MATH_EXTERN:
1696 cur.recordUndoInset();
1700 case LFUN_MATH_MUTATE: {
1701 cur.recordUndoInset();
1702 row_type row = cur.row();
1703 col_type col = cur.col();
1704 mutate(hullType(cmd.argument()));
1705 cur.idx() = row * ncols() + col;
1706 if (cur.idx() > cur.lastidx()) {
1707 cur.idx() = cur.lastidx();
1708 cur.pos() = cur.lastpos();
1710 if (cur.pos() > cur.lastpos())
1711 cur.pos() = cur.lastpos();
1713 cur.forceBufferUpdate();
1714 // FIXME: find some more clever handling of the selection,
1715 // i.e. preserve it.
1716 cur.clearSelection();
1717 //cur.dispatched(FINISHED);
1721 case LFUN_MATH_DISPLAY: {
1722 cur.recordUndoInset();
1723 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1724 // if the cursor is in a cell that got merged, move it to
1725 // start of the hull inset.
1726 if (cur.idx() > 0) {
1730 if (cur.pos() > cur.lastpos())
1731 cur.pos() = cur.lastpos();
1736 case LFUN_TABULAR_FEATURE:
1740 InsetMathGrid::doDispatch(cur, cmd);
1744 InsetMathGrid::doDispatch(cur, cmd);
1750 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1751 FuncStatus & status) const
1753 switch (cmd.action()) {
1754 case LFUN_FINISHED_BACKWARD:
1755 case LFUN_FINISHED_FORWARD:
1756 case LFUN_FINISHED_RIGHT:
1757 case LFUN_FINISHED_LEFT:
1760 case LFUN_NEWLINE_INSERT:
1761 case LFUN_MATH_EXTERN:
1763 status.setEnabled(true);
1766 // we never allow this in math, and we want to bind enter
1767 // to another actions in command-alternatives
1768 case LFUN_PARAGRAPH_BREAK:
1769 status.setEnabled(false);
1771 case LFUN_MATH_MUTATE: {
1772 HullType const ht = hullType(cmd.argument());
1773 status.setOnOff(type_ == ht);
1774 status.setEnabled(true);
1776 if (ht != hullSimple) {
1777 Cursor tmpcur = cur;
1778 while (!tmpcur.empty()) {
1779 InsetCode code = tmpcur.inset().lyxCode();
1780 if (code == BOX_CODE) {
1782 } else if (code == TABULAR_CODE) {
1783 FuncRequest tmpcmd(LFUN_MATH_DISPLAY);
1784 if (tmpcur.getStatus(tmpcmd, status) && !status.enabled())
1792 case LFUN_MATH_DISPLAY: {
1794 if (cur.depth() > 1) {
1795 Inset const & in = cur[cur.depth()-2].inset();
1796 if (in.lyxCode() == SCRIPT_CODE)
1797 enable = display() != Inline;
1799 status.setEnabled(enable);
1800 status.setOnOff(display() != Inline);
1804 case LFUN_MATH_NUMBER_TOGGLE:
1805 // FIXME: what is the right test, this or the one of
1807 status.setEnabled(display() != Inline);
1808 status.setOnOff(numberedType());
1811 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1812 // FIXME: what is the right test, this or the one of
1814 bool const enable = (type_ == hullMultline)
1815 ? (nrows() - 1 == cur.row())
1816 : display() != Inline;
1817 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1818 status.setEnabled(enable);
1819 status.setOnOff(enable && numbered(r));
1823 case LFUN_LABEL_INSERT:
1824 status.setEnabled(type_ != hullSimple);
1827 case LFUN_LABEL_COPY_AS_REFERENCE: {
1828 bool enabled = false;
1830 if (cmd.argument().empty() && &cur.inset() == this) {
1831 // if there is no argument and we're inside math, we retrieve
1832 // the row number from the cursor position.
1833 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1834 enabled = numberedType() && label_[row] && numbered(row);
1836 // if there is an argument, find the corresponding label, else
1837 // check whether there is at least one label.
1838 for (row_type row = 0; row != nrows(); ++row) {
1839 if (numbered(row) && label_[row] &&
1840 (cmd.argument().empty() || label(row) == cmd.argument())) {
1846 status.setEnabled(enabled);
1850 case LFUN_INSET_INSERT:
1851 if (cmd.getArg(0) == "label") {
1852 status.setEnabled(type_ != hullSimple);
1855 return InsetMathGrid::getStatus(cur, cmd, status);
1857 case LFUN_TABULAR_FEATURE: {
1860 string s = cmd.getArg(0);
1862 && (s == "append-row"
1863 || s == "delete-row"
1864 || s == "copy-row")) {
1865 status.message(bformat(
1866 from_utf8(N_("Can't change number of rows in '%1$s'")),
1868 status.setEnabled(false);
1872 && (s == "append-column"
1873 || s == "delete-column"
1874 || s == "copy-column")) {
1875 status.message(bformat(
1876 from_utf8(N_("Can't change number of columns in '%1$s'")),
1878 status.setEnabled(false);
1881 if (s == "add-vline-left" || s == "add-vline-right") {
1882 status.message(bformat(
1883 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1885 status.setEnabled(false);
1888 if (s == "valign-top" || s == "valign-middle"
1889 || s == "valign-bottom" || s == "align-left"
1890 || s == "align-center" || s == "align-right") {
1891 status.setEnabled(false);
1894 return InsetMathGrid::getStatus(cur, cmd, status);
1898 return InsetMathGrid::getStatus(cur, cmd, status);
1901 // This cannot really happen, but inserted to shut-up gcc
1902 return InsetMathGrid::getStatus(cur, cmd, status);
1906 /////////////////////////////////////////////////////////////////////
1910 // simply scrap this function if you want
1911 void InsetMathHull::mutateToText()
1914 // translate to latex
1916 latex(os, false, false);
1917 string str = os.str();
1920 Text * lt = view_->cursor().innerText();
1921 string::const_iterator cit = str.begin();
1922 string::const_iterator end = str.end();
1923 for (; cit != end; ++cit)
1924 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1927 //dispatch(LFUN_ESCAPE);
1932 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1933 docstring const & font)
1935 // this whole function is a hack and won't work for incremental font
1938 if (cur.inset().asInsetMath()->name() == font)
1939 cur.handleFont(to_utf8(font));
1941 cur.handleNest(createInsetMath(font, cur.buffer()));
1947 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1952 font.fromString(to_utf8(arg), b);
1953 if (font.fontInfo().color() != Color_inherit) {
1954 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1955 cur.handleNest(at, 0);
1960 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1963 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1964 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1965 enter_front ? idxFirst(cur) : idxLast(cur);
1966 // The inset formula dimension is not necessarily the same as the
1967 // one of the instant preview image, so we have to indicate to the
1968 // BufferView that a metrics update is needed.
1969 cur.screenUpdateFlags(Update::Force);
1973 void InsetMathHull::revealCodes(Cursor & cur) const
1975 if (!cur.inMathed())
1977 odocstringstream os;
1979 cur.message(os.str());
1981 // write something to the minibuffer
1982 // translate to latex
1986 string str = os.str();
1988 string::size_type pos = 0;
1990 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1993 else if (*it == '\0') {
1995 pos = it - str.begin();
2001 res = res.substr(pos - 30);
2002 if (res.size() > 60)
2003 res = res.substr(0, 60);
2009 /////////////////////////////////////////////////////////////////////
2013 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2016 // FIXME: completely broken
2017 static InsetMathHull * lastformula = 0;
2018 static CursorBase current = DocIterator(ibegin(nucleus()));
2020 static string laststr;
2022 if (lastformula != this || laststr != str) {
2023 //lyxerr << "reset lastformula to " << this << endl;
2026 current = ibegin(nucleus());
2028 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2032 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2034 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2035 CursorSlice & top = it.back();
2036 MathData const & a = top.asInsetMath()->cell(top.idx_);
2037 if (a.matchpart(ar, top.pos_)) {
2038 bv->cursor().setSelection(it, ar.size());
2040 top.pos_ += ar.size();
2046 //lyxerr << "not found!" << endl;
2053 void InsetMathHull::write(ostream & os) const
2055 odocstringstream oss;
2056 TexRow texrow(false);
2057 otexrowstream ots(oss,texrow);
2058 WriteStream wi(ots, false, false, WriteStream::wsDefault);
2061 os << to_utf8(oss.str());
2065 void InsetMathHull::read(Lexer & lex)
2068 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2069 operator=(*at->asHullInset());
2073 bool InsetMathHull::readQuiet(Lexer & lex)
2076 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2078 operator=(*at->asHullInset());
2083 int InsetMathHull::plaintext(odocstringstream & os,
2084 OutputParams const & op, size_t max_length) const
2086 // disables ASCII-art for export of equations. See #2275.
2087 if (0 && display()) {
2091 TextPainter tpain(dim.width(), dim.height());
2092 drawT(tpain, 0, dim.ascent());
2094 // reset metrics cache to "real" values
2096 return tpain.textheight();
2099 odocstringstream oss;
2100 TexRow texrow(false);
2101 otexrowstream ots(oss,texrow);
2102 Encoding const * const enc = encodings.fromLyXName("utf8");
2103 WriteStream wi(ots, false, true, WriteStream::wsDefault, enc);
2106 if (type_ == hullRegexp)
2109 for (row_type r = 0; r < nrows(); ++r) {
2110 for (col_type c = 0; c < ncols(); ++c)
2111 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2112 // if it's for the TOC, we write just the first line
2113 // and do not include the newline.
2114 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2116 if (r < nrows() - 1)
2120 docstring const str = oss.str();
2126 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
2131 if (getType() == hullSimple)
2132 name = from_ascii("inlineequation");
2134 name = from_ascii("informalequation");
2136 docstring bname = name;
2137 if (!label(0).empty())
2138 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
2140 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
2142 odocstringstream ls;
2144 otexstream ols(ls, texrow);
2145 if (runparams.flavor == OutputParams::XML) {
2146 ms << MTag("alt role='tex' ");
2147 // Workaround for db2latex: db2latex always includes equations with
2148 // \ensuremath{} or \begin{display}\end{display}
2149 // so we strip LyX' math environment
2150 WriteStream wi(ols, false, false, WriteStream::wsDefault, runparams.encoding);
2151 InsetMathGrid::write(wi);
2152 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2157 InsetMathGrid::mathmlize(ms);
2160 ms << MTag("alt role='tex'");
2161 latex(ols, runparams);
2162 res = texrow.rows();
2163 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2167 ms << from_ascii("<graphic fileref=\"eqn/");
2168 if (!label(0).empty())
2169 ms << sgml::cleanID(buffer(), runparams, label(0));
2171 ms << sgml::uniqueID(from_ascii("anon"));
2173 if (runparams.flavor == OutputParams::XML)
2174 ms << from_ascii("\"/>");
2176 ms << from_ascii("\">");
2178 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2180 return ms.line() + res;
2184 bool InsetMathHull::haveNumbers() const
2186 bool havenumbers = false;
2187 // inline formulas are never numbered (bug 7351 part 3)
2188 if (getType() == hullSimple)
2190 for (size_t i = 0; i != numbered_.size(); ++i) {
2201 // We need to do something about alignment here.
2203 // This duplicates code from InsetMathGrid, but
2204 // we need access here to number information,
2205 // and we simply do not have that in InsetMathGrid.
2206 void InsetMathHull::htmlize(HtmlStream & os) const
2208 bool const havenumbers = haveNumbers();
2209 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2212 os << cell(index(0, 0));
2216 os << MTag("table", "class='mathtable'");
2217 for (row_type row = 0; row < nrows(); ++row) {
2219 for (col_type col = 0; col < ncols(); ++col) {
2221 os << cell(index(row, col));
2226 docstring const & num = numbers_[row];
2228 os << '(' << num << ')';
2233 os << ETag("table");
2237 // this duplicates code from InsetMathGrid, but
2238 // we need access here to number information,
2239 // and we simply do not have that in InsetMathGrid.
2240 void InsetMathHull::mathmlize(MathStream & os) const
2242 bool const havenumbers = haveNumbers();
2243 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2246 os << MTag("mtable");
2247 char const * const celltag = havetable ? "mtd" : "mrow";
2248 // FIXME There does not seem to be wide support at the moment
2249 // for mlabeledtr, so we have to use just mtr for now.
2250 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2251 char const * const rowtag = "mtr";
2252 for (row_type row = 0; row < nrows(); ++row) {
2255 for (col_type col = 0; col < ncols(); ++col) {
2257 << cell(index(row, col))
2263 docstring const & num = numbers_[row];
2265 os << '(' << num << ')';
2272 os << ETag("mtable");
2276 void InsetMathHull::mathAsLatex(WriteStream & os) const
2278 MathEnsurer ensurer(os, false);
2279 bool havenumbers = haveNumbers();
2280 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2283 os << cell(index(0, 0));
2287 os << "<table class='mathtable'>";
2288 for (row_type row = 0; row < nrows(); ++row) {
2290 for (col_type col = 0; col < ncols(); ++col) {
2291 os << "<td class='math'>";
2292 os << cell(index(row, col));
2297 docstring const & num = numbers_[row];
2299 os << '(' << num << ')';
2308 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2310 BufferParams::MathOutput const mathtype =
2311 buffer().masterBuffer()->params().html_math_output;
2313 bool success = false;
2315 // we output all the labels just at the beginning of the equation.
2316 // this should be fine.
2317 for (size_t i = 0; i != label_.size(); ++i) {
2318 InsetLabel const * const il = label_[i];
2324 // FIXME Eventually we would like to do this inset by inset.
2325 if (mathtype == BufferParams::MathML) {
2326 odocstringstream os;
2331 } catch (MathExportException const &) {}
2333 if (getType() == hullSimple)
2334 xs << html::StartTag("math",
2335 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2337 xs << html::StartTag("math",
2338 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2339 xs << XHTMLStream::ESCAPE_NONE
2341 << html::EndTag("math");
2343 } else if (mathtype == BufferParams::HTML) {
2344 odocstringstream os;
2349 } catch (MathExportException const &) {}
2351 string const tag = (getType() == hullSimple) ? "span" : "div";
2352 xs << html::StartTag(tag, "class='formula'", true)
2353 << XHTMLStream::ESCAPE_NONE
2355 << html::EndTag(tag);
2359 // what we actually want is this:
2361 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2363 // || mathtype == BufferParams::Images
2365 // but what follows is equivalent, since we'll enter only if either (a) we
2366 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2367 // aren't doing LaTeX, in which case we are doing Images.
2368 if (!success && mathtype != BufferParams::LaTeX) {
2369 graphics::PreviewImage const * pimage = 0;
2371 loadPreview(docit_);
2372 pimage = preview_->getPreviewImage(buffer());
2373 // FIXME Do we always have png?
2376 if (pimage || op.dryrun) {
2377 string const filename = pimage ? pimage->filename().onlyFileName()
2378 : "previewimage.png";
2380 // if we are not in the master buffer, then we need to see that the
2381 // generated image is copied there; otherwise, preview fails.
2382 Buffer const * mbuf = buffer().masterBuffer();
2383 if (mbuf != &buffer()) {
2384 string mbtmp = mbuf->temppath();
2385 FileName const mbufimg(support::addName(mbtmp, filename));
2386 pimage->filename().copyTo(mbufimg);
2388 // add the file to the list of files to be exported
2389 op.exportdata->addExternalFile("xhtml", pimage->filename());
2392 string const tag = (getType() == hullSimple) ? "span" : "div";
2394 << html::StartTag(tag)
2395 << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2396 << html::EndTag(tag)
2402 // so we'll pass this test if we've failed everything else, or
2403 // if mathtype was LaTeX, since we won't have entered any of the
2405 if (!success /* || mathtype != BufferParams::LaTeX */) {
2406 // Unfortunately, we cannot use latexString() because we do not want
2407 // $...$ or whatever.
2408 odocstringstream ls;
2409 TexRow texrow(false);
2410 otexrowstream ots(ls,texrow);
2411 WriteStream wi(ots, false, true, WriteStream::wsPreview);
2412 ModeSpecifier specifier(wi, MATH_MODE);
2414 docstring const latex = ls.str();
2416 // class='math' allows for use of jsMath
2417 // http://www.math.union.edu/~dpvc/jsMath/
2419 // probably should allow for some kind of customization here
2420 string const tag = (getType() == hullSimple) ? "span" : "div";
2421 xs << html::StartTag(tag, "class='math'")
2423 << html::EndTag(tag)
2430 void InsetMathHull::toString(odocstream & os) const
2432 odocstringstream ods;
2433 plaintext(ods, OutputParams(0));
2438 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2440 odocstringstream ods;
2443 // FIXME: this results in spilling TeX into the LyXHTML output since the
2444 // outliner is used to generate the LyXHTML list of figures/etc.
2450 string InsetMathHull::contextMenuName() const
2452 return "context-math";
2456 void InsetMathHull::recordLocation(DocIterator const & di)