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)), use_preview_(false)
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)), use_preview_(false)
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)
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: This has probably no effect and can be removed.
\r
353 char InsetMathHull::defaultColAlign(col_type col)
355 return colAlign(type_, col);
\r
359 char InsetMathHull::displayColAlign(idx_type idx) const
362 case hullMultline: {
\r
363 row_type const r = row(idx);
366 if (r == nrows() - 1)
375 case hullXXAlignAt:
\r
377 return colAlign(type_, col(idx));
\r
381 return InsetMathGrid::displayColAlign(idx);
385 int InsetMathHull::displayColSpace(col_type col) const
\r
387 return colSpace(type_, col);
\r
391 //FIXME: This has probably no effect and can be removed.
\r
392 int InsetMathHull::defaultColSpace(col_type col)
394 if (type_ == hullAlign || type_ == hullAlignAt)
396 if (type_ == hullXAlignAt)
397 return (col & 1) ? 20 : 0;
398 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
399 return (col & 1) ? 40 : 0;
404 docstring InsetMathHull::standardFont() const
409 font_name = from_ascii("texttt");
412 font_name = from_ascii("lyxnochange");
415 font_name = from_ascii("mathnormal");
421 ColorCode InsetMathHull::standardColor() const
427 color = Color_foreground;
436 bool InsetMathHull::previewState(const BufferView *const bv) const
438 if (!editing(bv) && RenderPreview::previewMath()
439 && type_ != hullRegexp)
441 graphics::PreviewImage const * pimage =
442 preview_->getPreviewImage(bv->buffer());
443 return pimage && pimage->image();
450 static const int ERROR_FRAME_WIDTH = 2;
453 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
455 if (previewState(mi.base.bv)) {
456 preview_->metrics(mi, dim);
457 if (previewTooSmall(dim)) {
458 // preview image is too small
459 dim.wid += 2 * ERROR_FRAME_WIDTH;
460 dim.asc += 2 * ERROR_FRAME_WIDTH;
462 // insert a one pixel gap in front of the formula
465 dim.des += displayMargin();
467 // Cache the inset dimension.
468 setDimCache(mi, dim);
472 FontSetChanger dummy1(mi.base, standardFont());
473 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
475 // let the cells adjust themselves
476 InsetMathGrid::metrics(mi, dim);
479 dim.asc += displayMargin();
480 dim.des += displayMargin();
483 if (numberedType()) {
484 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
486 for (row_type row = 0; row < nrows(); ++row)
487 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
493 if (type_ == hullRegexp)
495 // make it at least as high as the current font
498 math_font_max_dim(mi.base.font, asc, des);
499 dim.asc = max(dim.asc, asc);
500 dim.des = max(dim.des, des);
501 // Cache the inset dimension.
502 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
503 setDimCache(mi, dim);
507 bool InsetMathHull::previewTooSmall(Dimension const & dim) const
509 return dim.width() <= 10 && dim.height() <= 10;
513 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
515 BufferView const * const bv = pi.base.bv;
516 if (previewState(bv)) {
517 Dimension const dim = dimension(*pi.base.bv);
518 if (previewTooSmall(dim))
520 return graphics::PreviewLoader::backgroundColor();
526 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
528 Dimension const dim = dimension(*pi.base.bv);
529 if (previewTooSmall(dim)) {
530 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
531 dim.wid, dim.asc + dim.des, backgroundColor(pi));
534 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
535 dim.asc + dim.des - 1, pi.backgroundColor(this));
539 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
541 BufferView const * const bv = pi.base.bv;
542 use_preview_ = previewState(bv);
544 if (type_ == hullRegexp) {
545 Dimension const dim = dimension(*bv);
546 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
547 dim.width() - 2, dim.height() - 2, Color_regexpframe);
551 Dimension const dim = dimension(*bv);
552 if (previewTooSmall(dim)) {
553 // we have an extra frame
554 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
556 // one pixel gap in front
557 preview_->draw(pi, x + 1, y);
559 setPosCache(pi, x, y);
563 ColorCode color = pi.selected && lyxrc.use_system_colors
564 ? Color_selectiontext : standardColor();
565 bool const really_change_color = pi.base.font.color() == Color_none;
566 ColorChanger dummy0(pi.base.font, color, really_change_color);
567 FontSetChanger dummy1(pi.base, standardFont());
568 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
570 InsetMathGrid::draw(pi, x + 1, y);
572 if (numberedType()) {
573 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
574 for (row_type row = 0; row < nrows(); ++row) {
575 int const yy = y + rowinfo_[row].offset_;
576 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
577 docstring const nl = nicelabel(row);
581 setPosCache(pi, x, y);
585 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
588 InsetMathGrid::metricsT(mi, dim);
591 TexRow texrow(false);
592 otexrowstream ots(os,texrow);
593 WriteStream wi(ots, false, true, WriteStream::wsDefault);
595 dim.wid = os.str().size();
602 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
605 InsetMathGrid::drawT(pain, x, y);
608 TexRow texrow(false);
609 otexrowstream ots(os,texrow);
610 WriteStream wi(ots, false, true, WriteStream::wsDefault);
612 pain.draw(x, y, os.str().c_str());
617 static docstring latexString(InsetMathHull const & inset)
620 // This has to be static, because a preview snippet or a math
621 // macro containing math in text mode (such as $\text{$\phi$}$ or
622 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
623 // first time as a whole, and the second time only the inner math.
624 // In this last case inset.buffer() would be invalid.
625 static Encoding const * encoding = 0;
626 if (inset.isBufferValid())
627 encoding = &(inset.buffer().params().encoding());
628 TexRow texrow(false);
629 otexrowstream ots(ls,texrow);
630 WriteStream wi(ots, false, true, WriteStream::wsPreview, encoding);
636 void InsetMathHull::initUnicodeMath() const
638 // Trigger classification of the unicode symbols in this inset
639 docstring const dummy = latexString(*this);
643 void InsetMathHull::addPreview(DocIterator const & inset_pos,
644 graphics::PreviewLoader & /*ploader*/) const
646 if (RenderPreview::previewMath()) {
647 preparePreview(inset_pos);
652 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
653 MacroNameSet & macros, MacroNameSet & defs) const
655 MacroNameSet::iterator const end = macros.end();
657 for (size_t i = 0; i < md.size(); ++i) {
658 MathMacro const * mi = md[i].nucleus()->asMacro();
659 MathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
660 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
661 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
662 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
663 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
665 // Look for macros in the arguments of this macro.
666 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
667 usedMacros(mi->cell(idx), pos, macros, defs);
668 // Make sure this is a macro defined in the document
669 // (as we also spot the macros in the symbols file)
670 // or that we have not already accounted for it.
671 docstring const name = mi->name();
672 if (macros.find(name) == end)
675 // Look for macros in the definition of this macro.
676 MathData ar(pos.buffer());
677 MacroData const * data =
678 pos.buffer()->getMacro(name, pos, true);
680 odocstringstream macro_def;
681 data->write(macro_def, true);
683 defs.insert(macro_def.str());
684 asArray(data->definition(), ar);
686 usedMacros(ar, pos, macros, defs);
688 MathData ar(pos.buffer());
689 asArray(mt->definition(), ar);
690 usedMacros(ar, pos, macros, defs);
692 if (!si->nuc().empty())
693 usedMacros(si->nuc(), pos, macros, defs);
695 usedMacros(si->down(), pos, macros, defs);
697 usedMacros(si->up(), pos, macros, defs);
698 } else if (fi || gi) {
699 idx_type nidx = fi ? fi->nargs() : gi->nargs();
700 for (idx_type idx = 0; idx < nidx; ++idx)
701 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
704 usedMacros(ni->cell(0), pos, macros, defs);
710 void InsetMathHull::preparePreview(DocIterator const & pos,
711 bool forexport) const
713 // there is no need to do all the macro stuff if we're not
714 // actually going to generate the preview.
715 if (!RenderPreview::previewMath() && !forexport)
718 Buffer const * buffer = pos.buffer();
720 // collect macros at this position
722 buffer->listMacroNames(macros);
724 // collect definitions only for the macros used in this inset
726 for (idx_type idx = 0; idx < nargs(); ++idx)
727 usedMacros(cell(idx), pos, macros, defs);
729 MacroNameSet::iterator it = defs.begin();
730 MacroNameSet::iterator end = defs.end();
731 docstring macro_preamble;
732 for (; it != end; ++it)
733 macro_preamble.append(*it);
735 // set the font series and size for this snippet
736 DocIterator dit = pos;
737 while (dit.inMathed())
739 Paragraph const & par = dit.paragraph();
740 Font font = par.getFontSettings(buffer->params(), dit.pos());
741 font.fontInfo().realize(par.layout().font);
742 string const lsize = font.latexSize();
745 if (font.fontInfo().series() == BOLD_SERIES) {
746 setfont += from_ascii("\\textbf{");
749 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
750 setfont += from_ascii("\\" + lsize + '\n');
753 if (forexport && haveNumbers()) {
754 docstring eqstr = from_ascii("equation");
755 CounterMap::const_iterator it = counter_map.find(eqstr);
756 if (it != counter_map.end()) {
757 int num = it->second;
759 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
760 '{' + convert<docstring>(num) + '}' + '\n';
762 for (size_t i = 0; i != numcnts; ++i) {
763 docstring cnt = from_ascii(counters_to_save[i]);
764 it = counter_map.find(cnt);
765 if (it == counter_map.end())
767 int num = it->second;
769 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
770 '{' + convert<docstring>(num) + '}';
773 docstring const snippet = macro_preamble + setfont + setcnt
774 + latexString(*this) + endfont;
775 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
776 preview_->addPreview(snippet, *buffer, forexport);
780 void InsetMathHull::reloadPreview(DocIterator const & pos) const
783 preview_->startLoading(*pos.buffer());
787 void InsetMathHull::loadPreview(DocIterator const & pos) const
789 bool const forexport = true;
790 preparePreview(pos, forexport);
791 preview_->startLoading(*pos.buffer(), forexport);
795 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
797 if (RenderPreview::previewMath()) {
799 cur.screenUpdateFlags(Update::Force);
805 docstring InsetMathHull::label(row_type row) const
807 LASSERT(row < nrows(), return docstring());
808 if (InsetLabel * il = label_[row])
809 return il->screenLabel();
814 void InsetMathHull::label(row_type row, docstring const & label)
816 //lyxerr << "setting label '" << label << "' for row " << row << endl;
820 label_[row] = dummy_pointer;
823 label_[row]->updateLabelAndRefs(label);
825 label_[row]->setParam("name", label);
829 InsetCommandParams p(LABEL_CODE);
831 label_[row] = new InsetLabel(buffer_, p);
833 label_[row]->setBuffer(buffer());
837 void InsetMathHull::numbered(row_type row, Numbered num)
839 numbered_[row] = num;
840 if (!numbered(row) && label_[row]) {
847 bool InsetMathHull::numbered(row_type row) const
849 return numbered_[row] == NUMBER;
853 bool InsetMathHull::ams() const
871 for (size_t row = 0; row < numbered_.size(); ++row)
872 if (numbered_[row] == NOTAG)
878 Inset::DisplayType InsetMathHull::display() const
880 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
885 bool InsetMathHull::numberedType() const
887 if (type_ == hullNone)
889 if (type_ == hullSimple)
891 if (type_ == hullXXAlignAt)
893 if (type_ == hullRegexp)
895 for (row_type row = 0; row < nrows(); ++row)
902 void InsetMathHull::validate(LaTeXFeatures & features) const
904 if (features.runparams().isLaTeX()) {
906 features.require("amsmath");
908 if (type_ == hullRegexp) {
909 features.require("color");
910 string frcol = lcolor.getLaTeXName(Color_regexpframe);
911 string bgcol = "white";
912 features.addPreambleSnippet(
913 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
914 + frcol + string("}{")
915 + bgcol + string("}{\\ensuremath{\\mathtt{#1}}}}"));
916 features.addPreambleSnippet(
917 string("\\newcommand{\\endregexp}{}"));
920 // Validation is necessary only if not using AMS math.
921 // To be safe, we will always run mathedvalidate.
922 //if (features.amsstyle)
925 //features.binom = true;
926 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
927 // it would be better to do this elsewhere, but we can't validate in
928 // InsetMathMatrix and we have no way, outside MathExtern, to know if
929 // we even have any matrices.
930 features.addCSSSnippet(
931 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
932 "table.matrix td{padding: 0.25px;}\n"
933 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
934 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
936 InsetMathGrid::validate(features);
940 void InsetMathHull::header_write(WriteStream & os) const
942 bool n = numberedType();
959 os << "\\begin{equation" << star(n) << "}\n";
971 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
978 os << "\\begin{" << hullName(type_) << star(n) << '}'
979 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
985 os << "\\begin{" << hullName(type_) << '}'
986 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
996 os << "\\begin{unknown" << star(n) << "}\n";
1002 void InsetMathHull::footer_write(WriteStream & os) const
1004 bool n = numberedType();
1019 os << "\\end{equation" << star(n) << "}\n";
1033 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1039 os << "\\end{" << hullName(type_) << "}\n";
1043 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1044 os << "\\endregexp{}}";
1050 os << "\\end{unknown" << star(n) << "}\n";
1056 bool InsetMathHull::rowChangeOK() const
1059 type_ == hullEqnArray || type_ == hullAlign ||
1060 type_ == hullFlAlign || type_ == hullAlignAt ||
1061 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1062 type_ == hullGather || type_ == hullMultline;
1066 bool InsetMathHull::colChangeOK() const
1069 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1070 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1074 void InsetMathHull::addRow(row_type row)
1079 bool numbered = numberedType();
1080 // Move the number and raw pointer, do not call label() (bug 7511)
1081 InsetLabel * label = dummy_pointer;
1082 docstring number = empty_docstring();
1083 if (type_ == hullMultline) {
1084 if (row + 1 == nrows()) {
1085 numbered_[row] = NONUMBER;
1086 swap(label, label_[row]);
1087 swap(number, numbers_[row]);
1092 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1093 numbers_.insert(numbers_.begin() + row + 1, number);
1094 label_.insert(label_.begin() + row + 1, label);
1095 InsetMathGrid::addRow(row);
1099 void InsetMathHull::swapRow(row_type row)
1103 if (row + 1 == nrows())
1105 swap(numbered_[row], numbered_[row + 1]);
1106 swap(numbers_[row], numbers_[row + 1]);
1107 swap(label_[row], label_[row + 1]);
1108 InsetMathGrid::swapRow(row);
1112 void InsetMathHull::delRow(row_type row)
1114 if (nrows() <= 1 || !rowChangeOK())
1116 if (row + 1 == nrows() && type_ == hullMultline) {
1117 swap(numbered_[row - 1], numbered_[row]);
1118 swap(numbers_[row - 1], numbers_[row]);
1119 swap(label_[row - 1], label_[row]);
1120 InsetMathGrid::delRow(row);
1123 InsetMathGrid::delRow(row);
1124 // The last dummy row has no number info nor a label.
1125 // Test nrows() + 1 because we have already erased the row.
1126 if (row == nrows() + 1)
1128 numbered_.erase(numbered_.begin() + row);
1129 numbers_.erase(numbers_.begin() + row);
1131 label_.erase(label_.begin() + row);
1135 void InsetMathHull::addCol(col_type col)
1139 InsetMathGrid::addCol(col);
1143 void InsetMathHull::delCol(col_type col)
1145 if (ncols() <= 1 || !colChangeOK())
1147 InsetMathGrid::delCol(col);
1151 docstring InsetMathHull::nicelabel(row_type row) const
1155 docstring const & val = numbers_[row];
1157 return '(' + val + ')';
1158 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1162 void InsetMathHull::glueall(HullType type)
1165 for (idx_type i = 0; i < nargs(); ++i)
1167 InsetLabel * label = 0;
1168 if (type == hullEquation) {
1169 // preserve first non-empty label
1170 for (row_type row = 0; row < nrows(); ++row) {
1172 label = label_[row];
1178 *this = InsetMathHull(buffer_, hullSimple);
1185 void InsetMathHull::splitTo2Cols()
1187 LASSERT(ncols() == 1, return);
1188 InsetMathGrid::addCol(1);
1189 for (row_type row = 0; row < nrows(); ++row) {
1190 idx_type const i = 2 * row;
1191 pos_type pos = firstRelOp(cell(i));
1192 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1193 cell(i).erase(pos, cell(i).size());
1198 void InsetMathHull::splitTo3Cols()
1200 LASSERT(ncols() < 3, return);
1203 InsetMathGrid::addCol(2);
1204 for (row_type row = 0; row < nrows(); ++row) {
1205 idx_type const i = 3 * row + 1;
1206 if (!cell(i).empty()) {
1207 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1208 cell(i).erase(1, cell(i).size());
1214 void InsetMathHull::changeCols(col_type cols)
1216 if (ncols() == cols)
1218 else if (ncols() < cols) {
1224 while (ncols() < cols)
1225 InsetMathGrid::addCol(ncols());
1231 for (row_type row = 0; row < nrows(); ++row) {
1232 idx_type const i = row * ncols();
1233 for (col_type col = cols; col < ncols(); ++col) {
1234 cell(i + cols - 1).append(cell(i + col));
1238 while (ncols() > cols) {
1239 InsetMathGrid::delCol(ncols() - 1);
1244 HullType InsetMathHull::getType() const
1250 void InsetMathHull::setType(HullType type)
1257 bool InsetMathHull::isMutable(HullType type)
\r
1262 case hullEquation:
\r
1263 case hullEqnArray:
\r
1267 case hullXAlignAt:
\r
1268 case hullXXAlignAt:
\r
1269 case hullMultline:
\r
1278 void InsetMathHull::mutate(HullType newtype)
1280 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1282 // we try to move along the chain
1283 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1285 // +-------------------------------------+
1286 // we use eqnarray as intermediate type for mutations that are not
1287 // directly supported because it handles labels and numbering for
1290 if (newtype == type_) {
1294 else if (newtype < hullNone) {
1299 else if (type_ == hullNone) {
1300 setType(hullSimple);
1305 else if (type_ == hullSimple) {
1306 if (newtype == hullNone) {
1310 setType(hullEquation);
1311 numbered(0, label_[0] ? true : false);
1316 else if (type_ == hullEquation) {
1317 if (newtype < type_) {
1318 setType(hullSimple);
1321 } else if (newtype == hullEqnArray) {
1322 // split it "nicely" on the first relop
1324 setType(hullEqnArray);
1325 } else if (newtype == hullMultline || newtype == hullGather) {
1328 // split it "nicely"
1335 else if (type_ == hullEqnArray) {
1336 if (newtype < type_) {
1339 } else { // align & Co.
1346 else if (type_ == hullAlign || type_ == hullAlignAt ||
1347 type_ == hullXAlignAt || type_ == hullFlAlign) {
1348 if (newtype < hullAlign) {
1350 setType(hullEqnArray);
1352 } else if (newtype == hullGather || newtype == hullMultline) {
1355 } else if (newtype == hullXXAlignAt) {
1356 for (row_type row = 0; row < nrows(); ++row)
1357 numbered(row, false);
1364 else if (type_ == hullXXAlignAt) {
1365 for (row_type row = 0; row < nrows(); ++row)
1366 numbered(row, false);
1367 if (newtype < hullAlign) {
1369 setType(hullEqnArray);
1371 } else if (newtype == hullGather || newtype == hullMultline) {
1379 else if (type_ == hullMultline || type_ == hullGather) {
1380 if (newtype == hullGather || newtype == hullMultline)
1382 else if (newtype == hullAlign || newtype == hullFlAlign ||
1383 newtype == hullAlignAt || newtype == hullXAlignAt) {
1386 } else if (newtype == hullXXAlignAt) {
1388 for (row_type row = 0; row < nrows(); ++row)
1389 numbered(row, false);
1393 setType(hullEqnArray);
1399 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1400 << "' to '" << to_utf8(hullName(newtype))
1401 << "' not implemented" << endl;
1406 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1407 bool last_eoln) const
1410 if (numberedType()) {
1411 if (label_[row] && numbered(row)) {
1412 docstring const name =
1413 latex ? escape(label_[row]->getParam("name"))
1414 : label_[row]->getParam("name");
1415 res += "\\label{" + name + '}';
1417 if (type_ != hullMultline) {
1418 if (numbered_[row] == NONUMBER)
1419 res += "\\nonumber ";
1420 else if (numbered_[row] == NOTAG)
1424 // Never add \\ on the last empty line of eqnarray and friends
1426 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1429 void InsetMathHull::write(WriteStream & os) const
1431 ModeSpecifier specifier(os, MATH_MODE);
1433 InsetMathGrid::write(os);
1438 void InsetMathHull::normalize(NormalStream & os) const
1440 os << "[formula " << hullName(type_) << ' ';
1441 InsetMathGrid::normalize(os);
1446 void InsetMathHull::infoize(odocstream & os) const
1448 os << bformat(_("Type: %1$s"), hullName(type_));
1452 void InsetMathHull::check() const
1454 LATTEST(numbered_.size() == nrows());
1455 LATTEST(numbers_.size() == nrows());
1456 LATTEST(label_.size() == nrows());
1460 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1464 idocstringstream iss(func.argument());
1465 iss >> dlang >> extra;
1467 extra = from_ascii("noextra");
1468 string const lang = to_ascii(dlang);
1470 // replace selection with result of computation
1471 if (reduceSelectionToOneCell(cur)) {
1473 asArray(grabAndEraseSelection(cur), ar);
1474 lyxerr << "use selection: " << ar << endl;
1475 cur.insert(pipeThroughExtern(lang, extra, ar));
1479 // only inline, display or eqnarray math is allowed
1480 if (getType() > hullEqnArray) {
1481 frontend::Alert::warning(_("Bad math environment"),
1482 _("Computation cannot be performed for AMS "
1483 "math environments.\nChange the math "
1484 "formula type and try again."));
1489 eq.push_back(MathAtom(new InsetMathChar('=')));
1491 // go to first item in line
1492 cur.idx() -= cur.idx() % ncols();
1495 if (getType() == hullSimple) {
1496 size_type pos = cur.cell().find_last(eq);
1498 if (pos == cur.cell().size()) {
1500 lyxerr << "use whole cell: " << ar << endl;
1502 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1503 lyxerr << "use partial cell form pos: " << pos << endl;
1505 cur.cell().append(eq);
1506 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1507 cur.pos() = cur.lastpos();
1511 if (getType() == hullEquation) {
1512 lyxerr << "use equation inset" << endl;
1513 mutate(hullEqnArray);
1514 MathData & ar = cur.cell();
1515 lyxerr << "use cell: " << ar << endl;
1519 cur.cell() = pipeThroughExtern(lang, extra, ar);
1520 // move to end of line
1521 cur.pos() = cur.lastpos();
1526 lyxerr << "use eqnarray" << endl;
1527 cur.idx() += 2 - cur.idx() % ncols();
1529 MathData ar = cur.cell();
1530 lyxerr << "use cell: " << ar << endl;
1531 // FIXME: temporarily disabled
1537 cur.cell() = pipeThroughExtern(lang, extra, ar);
1538 cur.pos() = cur.lastpos();
1543 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1545 //lyxerr << "action: " << cmd.action() << endl;
1546 switch (cmd.action()) {
1548 case LFUN_FINISHED_BACKWARD:
1549 case LFUN_FINISHED_FORWARD:
1550 case LFUN_FINISHED_RIGHT:
1551 case LFUN_FINISHED_LEFT:
1552 //lyxerr << "action: " << cmd.action() << endl;
1553 InsetMathGrid::doDispatch(cur, cmd);
1556 case LFUN_PARAGRAPH_BREAK:
1557 // just swallow this
1560 case LFUN_NEWLINE_INSERT:
1561 // some magic for the common case
1562 if (type_ == hullSimple || type_ == hullEquation) {
1563 cur.recordUndoInset();
1565 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1566 mutate(align ? hullAlign : hullEqnArray);
1567 // mutate() may change labels and such.
1568 cur.forceBufferUpdate();
1569 cur.idx() = nrows() * ncols() - 1;
1570 cur.pos() = cur.lastpos();
1572 InsetMathGrid::doDispatch(cur, cmd);
1575 case LFUN_MATH_NUMBER_TOGGLE: {
1576 //lyxerr << "toggling all numbers" << endl;
1577 cur.recordUndoInset();
1578 bool old = numberedType();
1579 if (type_ == hullMultline)
1580 numbered(nrows() - 1, !old);
1582 for (row_type row = 0; row < nrows(); ++row)
1583 numbered(row, !old);
1585 cur.message(old ? _("No number") : _("Number"));
1586 cur.forceBufferUpdate();
1590 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1591 cur.recordUndoInset();
1592 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1593 bool old = numbered(r);
1594 cur.message(old ? _("No number") : _("Number"));
1596 cur.forceBufferUpdate();
1600 case LFUN_LABEL_INSERT: {
1601 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1602 docstring old_label = label(r);
1603 docstring const default_label = from_ascii("eq:");
1604 if (old_label.empty())
1605 old_label = default_label;
1607 InsetCommandParams p(LABEL_CODE);
1608 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1609 string const data = InsetCommand::params2string(p);
1611 if (cmd.argument().empty())
1612 cur.bv().showDialog("label", data);
1614 FuncRequest fr(LFUN_INSET_INSERT, data);
1620 case LFUN_LABEL_COPY_AS_REFERENCE: {
1622 if (cmd.argument().empty() && &cur.inset() == this)
1623 // if there is no argument and we're inside math, we retrieve
1624 // the row number from the cursor position.
1625 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1627 // if there is an argument, find the corresponding label, else
1628 // check whether there is at least one label.
1629 for (row = 0; row != nrows(); ++row)
1630 if (numbered(row) && label_[row]
1631 && (cmd.argument().empty() || label(row) == cmd.argument()))
1638 InsetCommandParams p(REF_CODE, "ref");
1639 p["reference"] = label(row);
1640 cap::clearSelection();
1641 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1645 case LFUN_WORD_DELETE_FORWARD:
1646 case LFUN_CHAR_DELETE_FORWARD:
1647 if (col(cur.idx()) + 1 == ncols()
1648 && cur.pos() == cur.lastpos()
1649 && !cur.selection()) {
1650 if (!label(row(cur.idx())).empty()) {
1651 cur.recordUndoInset();
1652 label(row(cur.idx()), docstring());
1653 } else if (numbered(row(cur.idx()))) {
1654 cur.recordUndoInset();
1655 numbered(row(cur.idx()), false);
1656 cur.forceBufferUpdate();
1658 InsetMathGrid::doDispatch(cur, cmd);
1662 InsetMathGrid::doDispatch(cur, cmd);
1667 case LFUN_INSET_INSERT: {
1668 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1669 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1670 string const name = cmd.getArg(0);
1671 if (name == "label") {
1672 InsetCommandParams p(LABEL_CODE);
1673 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1674 docstring str = p["name"];
1675 cur.recordUndoInset();
1676 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1680 docstring old = label(r);
1683 // The label will take care of the reference update.
1687 // Newly created inset so initialize it.
1688 label_[r]->initView();
1691 cur.forceBufferUpdate();
1694 InsetMathGrid::doDispatch(cur, cmd);
1698 case LFUN_MATH_EXTERN:
1699 cur.recordUndoInset();
1703 case LFUN_MATH_MUTATE: {
1704 cur.recordUndoInset();
1705 row_type row = cur.row();
1706 col_type col = cur.col();
1707 mutate(hullType(cmd.argument()));
1708 cur.idx() = row * ncols() + col;
1709 if (cur.idx() > cur.lastidx()) {
1710 cur.idx() = cur.lastidx();
1711 cur.pos() = cur.lastpos();
1713 if (cur.pos() > cur.lastpos())
1714 cur.pos() = cur.lastpos();
1716 cur.forceBufferUpdate();
1717 // FIXME: find some more clever handling of the selection,
1718 // i.e. preserve it.
1719 cur.clearSelection();
1720 //cur.dispatched(FINISHED);
1724 case LFUN_MATH_DISPLAY: {
1725 cur.recordUndoInset();
1726 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1727 // if the cursor is in a cell that got merged, move it to
1728 // start of the hull inset.
1729 if (cur.idx() > 0) {
1733 if (cur.pos() > cur.lastpos())
1734 cur.pos() = cur.lastpos();
1740 InsetMathGrid::doDispatch(cur, cmd);
1746 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1747 FuncStatus & status) const
1749 switch (cmd.action()) {
1750 case LFUN_FINISHED_BACKWARD:
1751 case LFUN_FINISHED_FORWARD:
1752 case LFUN_FINISHED_RIGHT:
1753 case LFUN_FINISHED_LEFT:
1756 case LFUN_NEWLINE_INSERT:
1757 case LFUN_MATH_EXTERN:
1759 status.setEnabled(true);
1762 // we never allow this in math, and we want to bind enter
1763 // to another actions in command-alternatives
1764 case LFUN_PARAGRAPH_BREAK:
1765 status.setEnabled(false);
1767 case LFUN_MATH_MUTATE: {
1768 HullType const ht = hullType(cmd.argument());
1769 status.setOnOff(type_ == ht);
1770 status.setEnabled(true);
1772 if (ht != hullSimple) {
1773 Cursor tmpcur = cur;
1774 while (!tmpcur.empty()) {
1775 InsetCode code = tmpcur.inset().lyxCode();
1776 if (code == BOX_CODE) {
1778 } else if (code == TABULAR_CODE) {
1779 FuncRequest tmpcmd(LFUN_MATH_DISPLAY);
1780 if (tmpcur.getStatus(tmpcmd, status) && !status.enabled())
1788 case LFUN_MATH_DISPLAY: {
1790 if (cur.depth() > 1) {
1791 Inset const & in = cur[cur.depth()-2].inset();
1792 if (in.lyxCode() == SCRIPT_CODE)
1793 enable = display() != Inline;
1795 status.setEnabled(enable);
1796 status.setOnOff(display() != Inline);
1800 case LFUN_MATH_NUMBER_TOGGLE:
1801 // FIXME: what is the right test, this or the one of
1803 status.setEnabled(display() != Inline);
1804 status.setOnOff(numberedType());
1807 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1808 // FIXME: what is the right test, this or the one of
1810 bool const enable = (type_ == hullMultline)
1811 ? (nrows() - 1 == cur.row())
1812 : display() != Inline;
1813 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1814 status.setEnabled(enable);
1815 status.setOnOff(enable && numbered(r));
1819 case LFUN_LABEL_INSERT:
1820 status.setEnabled(type_ != hullSimple);
1823 case LFUN_LABEL_COPY_AS_REFERENCE: {
1824 bool enabled = false;
1826 if (cmd.argument().empty() && &cur.inset() == this) {
1827 // if there is no argument and we're inside math, we retrieve
1828 // the row number from the cursor position.
1829 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1830 enabled = numberedType() && label_[row] && numbered(row);
1832 // if there is an argument, find the corresponding label, else
1833 // check whether there is at least one label.
1834 for (row_type row = 0; row != nrows(); ++row) {
1835 if (numbered(row) && label_[row] &&
1836 (cmd.argument().empty() || label(row) == cmd.argument())) {
1842 status.setEnabled(enabled);
1846 case LFUN_INSET_INSERT:
1847 if (cmd.getArg(0) == "label") {
1848 status.setEnabled(type_ != hullSimple);
1851 return InsetMathGrid::getStatus(cur, cmd, status);
1853 case LFUN_INSET_MODIFY: {
1854 istringstream is(to_utf8(cmd.argument()));
1858 return InsetMathGrid::getStatus(cur, cmd, status);
1861 && (s == "append-row"
1862 || s == "delete-row"
1863 || s == "copy-row")) {
1864 status.message(bformat(
1865 from_utf8(N_("Can't change number of rows in '%1$s'")),
1867 status.setEnabled(false);
1871 && (s == "append-column"
1872 || s == "delete-column"
1873 || s == "copy-column")) {
1874 status.message(bformat(
1875 from_utf8(N_("Can't change number of columns in '%1$s'")),
1877 status.setEnabled(false);
1880 if ((type_ == hullSimple
1881 || type_ == hullEquation
1882 || type_ == hullNone) &&
1883 (s == "add-hline-above" || s == "add-hline-below")) {
1884 status.message(bformat(
1885 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1887 status.setEnabled(false);
1890 if (s == "add-vline-left" || s == "add-vline-right") {
1891 status.message(bformat(
1892 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1894 status.setEnabled(false);
1897 if (s == "valign-top" || s == "valign-middle"
1898 || s == "valign-bottom" || s == "align-left"
1899 || s == "align-center" || s == "align-right") {
1900 status.setEnabled(false);
1903 return InsetMathGrid::getStatus(cur, cmd, status);
1907 return InsetMathGrid::getStatus(cur, cmd, status);
1910 // This cannot really happen, but inserted to shut-up gcc
1911 return InsetMathGrid::getStatus(cur, cmd, status);
1915 /////////////////////////////////////////////////////////////////////
1919 // simply scrap this function if you want
1920 void InsetMathHull::mutateToText()
1923 // translate to latex
1925 latex(os, false, false);
1926 string str = os.str();
1929 Text * lt = view_->cursor().innerText();
1930 string::const_iterator cit = str.begin();
1931 string::const_iterator end = str.end();
1932 for (; cit != end; ++cit)
1933 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1936 //dispatch(LFUN_ESCAPE);
1941 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1942 docstring const & font)
1944 // this whole function is a hack and won't work for incremental font
1947 if (cur.inset().asInsetMath()->name() == font)
1948 cur.handleFont(to_utf8(font));
1950 cur.handleNest(createInsetMath(font, cur.buffer()));
1956 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1961 font.fromString(to_utf8(arg), b);
1962 if (font.fontInfo().color() != Color_inherit) {
1963 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1964 cur.handleNest(at, 0);
1969 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1972 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1973 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1974 enter_front ? idxFirst(cur) : idxLast(cur);
1975 // The inset formula dimension is not necessarily the same as the
1976 // one of the instant preview image, so we have to indicate to the
1977 // BufferView that a metrics update is needed.
1978 cur.screenUpdateFlags(Update::Force);
1982 void InsetMathHull::revealCodes(Cursor & cur) const
1984 if (!cur.inMathed())
1986 odocstringstream os;
1988 cur.message(os.str());
1990 // write something to the minibuffer
1991 // translate to latex
1995 string str = os.str();
1997 string::size_type pos = 0;
1999 for (string::iterator it = str.begin(); it != str.end(); ++it) {
2002 else if (*it == '\0') {
2004 pos = it - str.begin();
2010 res = res.substr(pos - 30);
2011 if (res.size() > 60)
2012 res = res.substr(0, 60);
2018 /////////////////////////////////////////////////////////////////////
2022 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2025 // FIXME: completely broken
2026 static InsetMathHull * lastformula = 0;
2027 static CursorBase current = DocIterator(ibegin(nucleus()));
2029 static string laststr;
2031 if (lastformula != this || laststr != str) {
2032 //lyxerr << "reset lastformula to " << this << endl;
2035 current = ibegin(nucleus());
2037 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2041 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2043 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2044 CursorSlice & top = it.back();
2045 MathData const & a = top.asInsetMath()->cell(top.idx_);
2046 if (a.matchpart(ar, top.pos_)) {
2047 bv->cursor().setSelection(it, ar.size());
2049 top.pos_ += ar.size();
2055 //lyxerr << "not found!" << endl;
2062 void InsetMathHull::write(ostream & os) const
2064 odocstringstream oss;
2065 TexRow texrow(false);
2066 otexrowstream ots(oss,texrow);
2067 WriteStream wi(ots, false, false, WriteStream::wsDefault);
2070 os << to_utf8(oss.str());
2074 void InsetMathHull::read(Lexer & lex)
2077 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2078 operator=(*at->asHullInset());
2082 bool InsetMathHull::readQuiet(Lexer & lex)
2085 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2087 operator=(*at->asHullInset());
2092 int InsetMathHull::plaintext(odocstringstream & os,
2093 OutputParams const & op, size_t max_length) const
2095 // disables ASCII-art for export of equations. See #2275.
2096 if (0 && display()) {
2100 TextPainter tpain(dim.width(), dim.height());
2101 drawT(tpain, 0, dim.ascent());
2103 // reset metrics cache to "real" values
2105 return tpain.textheight();
2108 odocstringstream oss;
2109 TexRow texrow(false);
2110 otexrowstream ots(oss,texrow);
2111 Encoding const * const enc = encodings.fromLyXName("utf8");
2112 WriteStream wi(ots, false, true, WriteStream::wsDefault, enc);
2115 if (type_ == hullRegexp)
2118 for (row_type r = 0; r < nrows(); ++r) {
2119 for (col_type c = 0; c < ncols(); ++c)
2120 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2121 // if it's for the TOC, we write just the first line
2122 // and do not include the newline.
2123 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2125 if (r < nrows() - 1)
2129 docstring const str = oss.str();
2135 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
2140 if (getType() == hullSimple)
2141 name = from_ascii("inlineequation");
2143 name = from_ascii("informalequation");
2145 docstring bname = name;
2146 if (!label(0).empty())
2147 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
2149 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
2151 odocstringstream ls;
2153 otexstream ols(ls, texrow);
2154 if (runparams.flavor == OutputParams::XML) {
2155 ms << MTag("alt role='tex' ");
2156 // Workaround for db2latex: db2latex always includes equations with
2157 // \ensuremath{} or \begin{display}\end{display}
2158 // so we strip LyX' math environment
2159 WriteStream wi(ols, false, false, WriteStream::wsDefault, runparams.encoding);
2160 InsetMathGrid::write(wi);
2161 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2166 InsetMathGrid::mathmlize(ms);
2169 ms << MTag("alt role='tex'");
2170 latex(ols, runparams);
2171 res = texrow.rows();
2172 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2176 ms << from_ascii("<graphic fileref=\"eqn/");
2177 if (!label(0).empty())
2178 ms << sgml::cleanID(buffer(), runparams, label(0));
2180 ms << sgml::uniqueID(from_ascii("anon"));
2182 if (runparams.flavor == OutputParams::XML)
2183 ms << from_ascii("\"/>");
2185 ms << from_ascii("\">");
2187 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2189 return ms.line() + res;
2193 bool InsetMathHull::haveNumbers() const
2195 bool havenumbers = false;
2196 // inline formulas are never numbered (bug 7351 part 3)
2197 if (getType() == hullSimple)
2199 for (size_t i = 0; i != numbered_.size(); ++i) {
2210 // We need to do something about alignment here.
2212 // This duplicates code from InsetMathGrid, but
2213 // we need access here to number information,
2214 // and we simply do not have that in InsetMathGrid.
2215 void InsetMathHull::htmlize(HtmlStream & os) const
2217 bool const havenumbers = haveNumbers();
2218 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2221 os << cell(index(0, 0));
2225 os << MTag("table", "class='mathtable'");
2226 for (row_type row = 0; row < nrows(); ++row) {
2228 for (col_type col = 0; col < ncols(); ++col) {
2230 os << cell(index(row, col));
2235 docstring const & num = numbers_[row];
2237 os << '(' << num << ')';
2242 os << ETag("table");
2246 // this duplicates code from InsetMathGrid, but
2247 // we need access here to number information,
2248 // and we simply do not have that in InsetMathGrid.
2249 void InsetMathHull::mathmlize(MathStream & os) const
2251 bool const havenumbers = haveNumbers();
2252 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2255 os << MTag("mtable");
2256 char const * const celltag = havetable ? "mtd" : "mrow";
2257 // FIXME There does not seem to be wide support at the moment
2258 // for mlabeledtr, so we have to use just mtr for now.
2259 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2260 char const * const rowtag = "mtr";
2261 for (row_type row = 0; row < nrows(); ++row) {
2264 for (col_type col = 0; col < ncols(); ++col) {
2266 << cell(index(row, col))
2272 docstring const & num = numbers_[row];
2274 os << '(' << num << ')';
2281 os << ETag("mtable");
2285 void InsetMathHull::mathAsLatex(WriteStream & os) const
2287 MathEnsurer ensurer(os, false);
2288 bool havenumbers = haveNumbers();
2289 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2292 os << cell(index(0, 0));
2296 os << "<table class='mathtable'>";
2297 for (row_type row = 0; row < nrows(); ++row) {
2299 for (col_type col = 0; col < ncols(); ++col) {
2300 os << "<td class='math'>";
2301 os << cell(index(row, col));
2306 docstring const & num = numbers_[row];
2308 os << '(' << num << ')';
2317 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2319 BufferParams::MathOutput const mathtype =
2320 buffer().masterBuffer()->params().html_math_output;
2322 bool success = false;
2324 // we output all the labels just at the beginning of the equation.
2325 // this should be fine.
2326 for (size_t i = 0; i != label_.size(); ++i) {
2327 InsetLabel const * const il = label_[i];
2333 // FIXME Eventually we would like to do this inset by inset.
2334 if (mathtype == BufferParams::MathML) {
2335 odocstringstream os;
2340 } catch (MathExportException const &) {}
2342 if (getType() == hullSimple)
2343 xs << html::StartTag("math",
2344 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2346 xs << html::StartTag("math",
2347 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2348 xs << XHTMLStream::ESCAPE_NONE
2350 << html::EndTag("math");
2352 } else if (mathtype == BufferParams::HTML) {
2353 odocstringstream os;
2358 } catch (MathExportException const &) {}
2360 string const tag = (getType() == hullSimple) ? "span" : "div";
2361 xs << html::StartTag(tag, "class='formula'", true)
2362 << XHTMLStream::ESCAPE_NONE
2364 << html::EndTag(tag);
2368 // what we actually want is this:
2370 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2372 // || mathtype == BufferParams::Images
2374 // but what follows is equivalent, since we'll enter only if either (a) we
2375 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2376 // aren't doing LaTeX, in which case we are doing Images.
2377 if (!success && mathtype != BufferParams::LaTeX) {
2378 graphics::PreviewImage const * pimage = 0;
2380 loadPreview(docit_);
2381 pimage = preview_->getPreviewImage(buffer());
2382 // FIXME Do we always have png?
2385 if (pimage || op.dryrun) {
2386 string const filename = pimage ? pimage->filename().onlyFileName()
2387 : "previewimage.png";
2389 // if we are not in the master buffer, then we need to see that the
2390 // generated image is copied there; otherwise, preview fails.
2391 Buffer const * mbuf = buffer().masterBuffer();
2392 if (mbuf != &buffer()) {
2393 string mbtmp = mbuf->temppath();
2394 FileName const mbufimg(support::addName(mbtmp, filename));
2395 pimage->filename().copyTo(mbufimg);
2397 // add the file to the list of files to be exported
2398 op.exportdata->addExternalFile("xhtml", pimage->filename());
2401 string const tag = (getType() == hullSimple) ? "span" : "div";
2403 << html::StartTag(tag)
2404 << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2405 << html::EndTag(tag)
2411 // so we'll pass this test if we've failed everything else, or
2412 // if mathtype was LaTeX, since we won't have entered any of the
2414 if (!success /* || mathtype != BufferParams::LaTeX */) {
2415 // Unfortunately, we cannot use latexString() because we do not want
2416 // $...$ or whatever.
2417 odocstringstream ls;
2418 TexRow texrow(false);
2419 otexrowstream ots(ls,texrow);
2420 WriteStream wi(ots, false, true, WriteStream::wsPreview);
2421 ModeSpecifier specifier(wi, MATH_MODE);
2423 docstring const latex = ls.str();
2425 // class='math' allows for use of jsMath
2426 // http://www.math.union.edu/~dpvc/jsMath/
2428 // probably should allow for some kind of customization here
2429 string const tag = (getType() == hullSimple) ? "span" : "div";
2430 xs << html::StartTag(tag, "class='math'")
2432 << html::EndTag(tag)
2439 void InsetMathHull::toString(odocstream & os) const
2441 odocstringstream ods;
2442 plaintext(ods, OutputParams(0));
2447 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2449 odocstringstream ods;
2452 // FIXME: this results in spilling TeX into the LyXHTML output since the
2453 // outliner is used to generate the LyXHTML list of figures/etc.
2459 string InsetMathHull::contextMenuName() const
2461 return "context-math";
2465 void InsetMathHull::recordLocation(DocIterator const & di)