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::defaultColSpace(col_type col)
387 if (type_ == hullAlign || type_ == hullAlignAt)
389 if (type_ == hullXAlignAt)
390 return (col & 1) ? 20 : 0;
391 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
392 return (col & 1) ? 40 : 0;
397 docstring InsetMathHull::standardFont() const
402 font_name = from_ascii("texttt");
405 font_name = from_ascii("lyxnochange");
408 font_name = from_ascii("mathnormal");
414 ColorCode InsetMathHull::standardColor() const
420 color = Color_foreground;
429 bool InsetMathHull::previewState(const BufferView *const bv) const
431 if (!editing(bv) && RenderPreview::previewMath()
432 && type_ != hullRegexp)
434 graphics::PreviewImage const * pimage =
435 preview_->getPreviewImage(bv->buffer());
436 return pimage && pimage->image();
443 static const int ERROR_FRAME_WIDTH = 2;
446 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
448 if (previewState(mi.base.bv)) {
449 preview_->metrics(mi, dim);
450 if (previewTooSmall(dim)) {
451 // preview image is too small
452 dim.wid += 2 * ERROR_FRAME_WIDTH;
453 dim.asc += 2 * ERROR_FRAME_WIDTH;
455 // insert a one pixel gap in front of the formula
458 dim.des += displayMargin();
460 // Cache the inset dimension.
461 setDimCache(mi, dim);
465 FontSetChanger dummy1(mi.base, standardFont());
466 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
468 // let the cells adjust themselves
469 InsetMathGrid::metrics(mi, dim);
472 dim.asc += displayMargin();
473 dim.des += displayMargin();
476 if (numberedType()) {
477 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
479 for (row_type row = 0; row < nrows(); ++row)
480 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
486 if (type_ == hullRegexp)
488 // make it at least as high as the current font
491 math_font_max_dim(mi.base.font, asc, des);
492 dim.asc = max(dim.asc, asc);
493 dim.des = max(dim.des, des);
494 // Cache the inset dimension.
495 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
496 setDimCache(mi, dim);
500 bool InsetMathHull::previewTooSmall(Dimension const & dim) const
502 return dim.width() <= 10 && dim.height() <= 10;
506 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
508 BufferView const * const bv = pi.base.bv;
509 if (previewState(bv)) {
510 Dimension const dim = dimension(*pi.base.bv);
511 if (previewTooSmall(dim))
513 return graphics::PreviewLoader::backgroundColor();
519 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
521 Dimension const dim = dimension(*pi.base.bv);
522 if (previewTooSmall(dim)) {
523 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
524 dim.wid, dim.asc + dim.des, backgroundColor(pi));
527 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
528 dim.asc + dim.des - 1, pi.backgroundColor(this));
532 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
534 BufferView const * const bv = pi.base.bv;
535 use_preview_ = previewState(bv);
537 if (type_ == hullRegexp) {
538 Dimension const dim = dimension(*bv);
539 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
540 dim.width() - 2, dim.height() - 2, Color_regexpframe);
544 Dimension const dim = dimension(*bv);
545 if (previewTooSmall(dim)) {
546 // we have an extra frame
547 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
549 // one pixel gap in front
550 preview_->draw(pi, x + 1, y);
552 setPosCache(pi, x, y);
556 ColorCode color = pi.selected && lyxrc.use_system_colors
557 ? Color_selectiontext : standardColor();
558 bool const really_change_color = pi.base.font.color() == Color_none;
559 ColorChanger dummy0(pi.base.font, color, really_change_color);
560 FontSetChanger dummy1(pi.base, standardFont());
561 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
563 InsetMathGrid::draw(pi, x + 1, y);
565 if (numberedType()) {
566 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
567 for (row_type row = 0; row < nrows(); ++row) {
568 int const yy = y + rowinfo_[row].offset_;
569 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
570 docstring const nl = nicelabel(row);
574 setPosCache(pi, x, y);
578 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
581 InsetMathGrid::metricsT(mi, dim);
584 TexRow texrow(false);
585 otexrowstream ots(os,texrow);
586 WriteStream wi(ots, false, true, WriteStream::wsDefault);
588 dim.wid = os.str().size();
595 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
598 InsetMathGrid::drawT(pain, x, y);
601 TexRow texrow(false);
602 otexrowstream ots(os,texrow);
603 WriteStream wi(ots, false, true, WriteStream::wsDefault);
605 pain.draw(x, y, os.str().c_str());
610 static docstring latexString(InsetMathHull const & inset)
613 // This has to be static, because a preview snippet or a math
614 // macro containing math in text mode (such as $\text{$\phi$}$ or
615 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
616 // first time as a whole, and the second time only the inner math.
617 // In this last case inset.buffer() would be invalid.
618 static Encoding const * encoding = 0;
619 if (inset.isBufferValid())
620 encoding = &(inset.buffer().params().encoding());
621 TexRow texrow(false);
622 otexrowstream ots(ls,texrow);
623 WriteStream wi(ots, false, true, WriteStream::wsPreview, encoding);
629 void InsetMathHull::initUnicodeMath() const
631 // Trigger classification of the unicode symbols in this inset
632 docstring const dummy = latexString(*this);
636 void InsetMathHull::addPreview(DocIterator const & inset_pos,
637 graphics::PreviewLoader & /*ploader*/) const
639 if (RenderPreview::previewMath()) {
640 preparePreview(inset_pos);
645 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
646 MacroNameSet & macros, MacroNameSet & defs) const
648 MacroNameSet::iterator const end = macros.end();
650 for (size_t i = 0; i < md.size(); ++i) {
651 MathMacro const * mi = md[i].nucleus()->asMacro();
652 MathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
653 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
654 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
655 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
656 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
658 // Look for macros in the arguments of this macro.
659 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
660 usedMacros(mi->cell(idx), pos, macros, defs);
661 // Make sure this is a macro defined in the document
662 // (as we also spot the macros in the symbols file)
663 // or that we have not already accounted for it.
664 docstring const name = mi->name();
665 if (macros.find(name) == end)
668 // Look for macros in the definition of this macro.
669 MathData ar(pos.buffer());
670 MacroData const * data =
671 pos.buffer()->getMacro(name, pos, true);
673 odocstringstream macro_def;
674 data->write(macro_def, true);
676 defs.insert(macro_def.str());
677 asArray(data->definition(), ar);
679 usedMacros(ar, pos, macros, defs);
681 MathData ar(pos.buffer());
682 asArray(mt->definition(), ar);
683 usedMacros(ar, pos, macros, defs);
685 if (!si->nuc().empty())
686 usedMacros(si->nuc(), pos, macros, defs);
688 usedMacros(si->down(), pos, macros, defs);
690 usedMacros(si->up(), pos, macros, defs);
691 } else if (fi || gi) {
692 idx_type nidx = fi ? fi->nargs() : gi->nargs();
693 for (idx_type idx = 0; idx < nidx; ++idx)
694 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
697 usedMacros(ni->cell(0), pos, macros, defs);
703 void InsetMathHull::preparePreview(DocIterator const & pos,
704 bool forexport) const
706 // there is no need to do all the macro stuff if we're not
707 // actually going to generate the preview.
708 if (!RenderPreview::previewMath() && !forexport)
711 Buffer const * buffer = pos.buffer();
713 // collect macros at this position
715 buffer->listMacroNames(macros);
717 // collect definitions only for the macros used in this inset
719 for (idx_type idx = 0; idx < nargs(); ++idx)
720 usedMacros(cell(idx), pos, macros, defs);
722 MacroNameSet::iterator it = defs.begin();
723 MacroNameSet::iterator end = defs.end();
724 docstring macro_preamble;
725 for (; it != end; ++it)
726 macro_preamble.append(*it);
728 // set the font series and size for this snippet
729 DocIterator dit = pos;
730 while (dit.inMathed())
732 Paragraph const & par = dit.paragraph();
733 Font font = par.getFontSettings(buffer->params(), dit.pos());
734 font.fontInfo().realize(par.layout().font);
735 string const lsize = font.latexSize();
738 if (font.fontInfo().series() == BOLD_SERIES) {
739 setfont += from_ascii("\\textbf{");
742 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
743 setfont += from_ascii("\\" + lsize + '\n');
746 if (forexport && haveNumbers()) {
747 docstring eqstr = from_ascii("equation");
748 CounterMap::const_iterator it = counter_map.find(eqstr);
749 if (it != counter_map.end()) {
750 int num = it->second;
752 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
753 '{' + convert<docstring>(num) + '}' + '\n';
755 for (size_t i = 0; i != numcnts; ++i) {
756 docstring cnt = from_ascii(counters_to_save[i]);
757 it = counter_map.find(cnt);
758 if (it == counter_map.end())
760 int num = it->second;
762 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
763 '{' + convert<docstring>(num) + '}';
766 docstring const snippet = macro_preamble + setfont + setcnt
767 + latexString(*this) + endfont;
768 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
769 preview_->addPreview(snippet, *buffer, forexport);
773 void InsetMathHull::reloadPreview(DocIterator const & pos) const
776 preview_->startLoading(*pos.buffer());
780 void InsetMathHull::loadPreview(DocIterator const & pos) const
782 bool const forexport = true;
783 preparePreview(pos, forexport);
784 preview_->startLoading(*pos.buffer(), forexport);
788 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
790 if (RenderPreview::previewMath()) {
792 cur.screenUpdateFlags(Update::Force);
798 docstring InsetMathHull::label(row_type row) const
800 LASSERT(row < nrows(), return docstring());
801 if (InsetLabel * il = label_[row])
802 return il->screenLabel();
807 void InsetMathHull::label(row_type row, docstring const & label)
809 //lyxerr << "setting label '" << label << "' for row " << row << endl;
813 label_[row] = dummy_pointer;
816 label_[row]->updateLabelAndRefs(label);
818 label_[row]->setParam("name", label);
822 InsetCommandParams p(LABEL_CODE);
824 label_[row] = new InsetLabel(buffer_, p);
826 label_[row]->setBuffer(buffer());
830 void InsetMathHull::numbered(row_type row, Numbered num)
832 numbered_[row] = num;
833 if (!numbered(row) && label_[row]) {
840 bool InsetMathHull::numbered(row_type row) const
842 return numbered_[row] == NUMBER;
846 bool InsetMathHull::ams() const
864 for (size_t row = 0; row < numbered_.size(); ++row)
865 if (numbered_[row] == NOTAG)
871 Inset::DisplayType InsetMathHull::display() const
873 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
878 bool InsetMathHull::numberedType() const
880 if (type_ == hullNone)
882 if (type_ == hullSimple)
884 if (type_ == hullXXAlignAt)
886 if (type_ == hullRegexp)
888 for (row_type row = 0; row < nrows(); ++row)
895 void InsetMathHull::validate(LaTeXFeatures & features) const
897 if (features.runparams().isLaTeX()) {
899 features.require("amsmath");
901 if (type_ == hullRegexp) {
902 features.require("color");
903 string frcol = lcolor.getLaTeXName(Color_regexpframe);
904 string bgcol = "white";
905 features.addPreambleSnippet(
906 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
907 + frcol + string("}{")
908 + bgcol + string("}{\\ensuremath{\\mathtt{#1}}}}"));
909 features.addPreambleSnippet(
910 string("\\newcommand{\\endregexp}{}"));
913 // Validation is necessary only if not using AMS math.
914 // To be safe, we will always run mathedvalidate.
915 //if (features.amsstyle)
918 //features.binom = true;
919 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
920 // it would be better to do this elsewhere, but we can't validate in
921 // InsetMathMatrix and we have no way, outside MathExtern, to know if
922 // we even have any matrices.
923 features.addCSSSnippet(
924 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
925 "table.matrix td{padding: 0.25px;}\n"
926 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
927 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
929 InsetMathGrid::validate(features);
933 void InsetMathHull::header_write(WriteStream & os) const
935 bool n = numberedType();
952 os << "\\begin{equation" << star(n) << "}\n";
964 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
971 os << "\\begin{" << hullName(type_) << star(n) << '}'
972 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
978 os << "\\begin{" << hullName(type_) << '}'
979 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
989 os << "\\begin{unknown" << star(n) << "}\n";
995 void InsetMathHull::footer_write(WriteStream & os) const
997 bool n = numberedType();
1012 os << "\\end{equation" << star(n) << "}\n";
1026 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1032 os << "\\end{" << hullName(type_) << "}\n";
1036 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1037 os << "\\endregexp{}}";
1043 os << "\\end{unknown" << star(n) << "}\n";
1049 bool InsetMathHull::rowChangeOK() const
1052 type_ == hullEqnArray || type_ == hullAlign ||
1053 type_ == hullFlAlign || type_ == hullAlignAt ||
1054 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1055 type_ == hullGather || type_ == hullMultline;
1059 bool InsetMathHull::colChangeOK() const
1062 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1063 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1067 void InsetMathHull::addRow(row_type row)
1072 bool numbered = numberedType();
1073 // Move the number and raw pointer, do not call label() (bug 7511)
1074 InsetLabel * label = dummy_pointer;
1075 docstring number = empty_docstring();
1076 if (type_ == hullMultline) {
1077 if (row + 1 == nrows()) {
1078 numbered_[row] = NONUMBER;
1079 swap(label, label_[row]);
1080 swap(number, numbers_[row]);
1085 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1086 numbers_.insert(numbers_.begin() + row + 1, number);
1087 label_.insert(label_.begin() + row + 1, label);
1088 InsetMathGrid::addRow(row);
1092 void InsetMathHull::swapRow(row_type row)
1096 if (row + 1 == nrows())
1098 swap(numbered_[row], numbered_[row + 1]);
1099 swap(numbers_[row], numbers_[row + 1]);
1100 swap(label_[row], label_[row + 1]);
1101 InsetMathGrid::swapRow(row);
1105 void InsetMathHull::delRow(row_type row)
1107 if (nrows() <= 1 || !rowChangeOK())
1109 if (row + 1 == nrows() && type_ == hullMultline) {
1110 swap(numbered_[row - 1], numbered_[row]);
1111 swap(numbers_[row - 1], numbers_[row]);
1112 swap(label_[row - 1], label_[row]);
1113 InsetMathGrid::delRow(row);
1116 InsetMathGrid::delRow(row);
1117 // The last dummy row has no number info nor a label.
1118 // Test nrows() + 1 because we have already erased the row.
1119 if (row == nrows() + 1)
1121 numbered_.erase(numbered_.begin() + row);
1122 numbers_.erase(numbers_.begin() + row);
1124 label_.erase(label_.begin() + row);
1128 void InsetMathHull::addCol(col_type col)
1132 InsetMathGrid::addCol(col);
1136 void InsetMathHull::delCol(col_type col)
1138 if (ncols() <= 1 || !colChangeOK())
1140 InsetMathGrid::delCol(col);
1144 docstring InsetMathHull::nicelabel(row_type row) const
1148 docstring const & val = numbers_[row];
1150 return '(' + val + ')';
1151 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1155 void InsetMathHull::glueall(HullType type)
1158 for (idx_type i = 0; i < nargs(); ++i)
1160 InsetLabel * label = 0;
1161 if (type == hullEquation) {
1162 // preserve first non-empty label
1163 for (row_type row = 0; row < nrows(); ++row) {
1165 label = label_[row];
1171 *this = InsetMathHull(buffer_, hullSimple);
1178 void InsetMathHull::splitTo2Cols()
1180 LASSERT(ncols() == 1, return);
1181 InsetMathGrid::addCol(1);
1182 for (row_type row = 0; row < nrows(); ++row) {
1183 idx_type const i = 2 * row;
1184 pos_type pos = firstRelOp(cell(i));
1185 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1186 cell(i).erase(pos, cell(i).size());
1191 void InsetMathHull::splitTo3Cols()
1193 LASSERT(ncols() < 3, return);
1196 InsetMathGrid::addCol(2);
1197 for (row_type row = 0; row < nrows(); ++row) {
1198 idx_type const i = 3 * row + 1;
1199 if (!cell(i).empty()) {
1200 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1201 cell(i).erase(1, cell(i).size());
1207 void InsetMathHull::changeCols(col_type cols)
1209 if (ncols() == cols)
1211 else if (ncols() < cols) {
1217 while (ncols() < cols)
1218 InsetMathGrid::addCol(ncols());
1224 for (row_type row = 0; row < nrows(); ++row) {
1225 idx_type const i = row * ncols();
1226 for (col_type col = cols; col < ncols(); ++col) {
1227 cell(i + cols - 1).append(cell(i + col));
1231 while (ncols() > cols) {
1232 InsetMathGrid::delCol(ncols() - 1);
1237 HullType InsetMathHull::getType() const
1243 void InsetMathHull::setType(HullType type)
1250 bool InsetMathHull::isMutable(HullType type)
\r
1255 case hullEquation:
\r
1256 case hullEqnArray:
\r
1260 case hullXAlignAt:
\r
1261 case hullXXAlignAt:
\r
1262 case hullMultline:
\r
1271 void InsetMathHull::mutate(HullType newtype)
1273 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1275 // we try to move along the chain
1276 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1278 // +-------------------------------------+
1279 // we use eqnarray as intermediate type for mutations that are not
1280 // directly supported because it handles labels and numbering for
1283 if (newtype == type_) {
1287 else if (newtype < hullNone) {
1292 else if (type_ == hullNone) {
1293 setType(hullSimple);
1298 else if (type_ == hullSimple) {
1299 if (newtype == hullNone) {
1303 setType(hullEquation);
1304 numbered(0, label_[0] ? true : false);
1309 else if (type_ == hullEquation) {
1310 if (newtype < type_) {
1311 setType(hullSimple);
1314 } else if (newtype == hullEqnArray) {
1315 // split it "nicely" on the first relop
1317 setType(hullEqnArray);
1318 } else if (newtype == hullMultline || newtype == hullGather) {
1321 // split it "nicely"
1328 else if (type_ == hullEqnArray) {
1329 if (newtype < type_) {
1332 } else { // align & Co.
1339 else if (type_ == hullAlign || type_ == hullAlignAt ||
1340 type_ == hullXAlignAt || type_ == hullFlAlign) {
1341 if (newtype < hullAlign) {
1343 setType(hullEqnArray);
1345 } else if (newtype == hullGather || newtype == hullMultline) {
1348 } else if (newtype == hullXXAlignAt) {
1349 for (row_type row = 0; row < nrows(); ++row)
1350 numbered(row, false);
1357 else if (type_ == hullXXAlignAt) {
1358 for (row_type row = 0; row < nrows(); ++row)
1359 numbered(row, false);
1360 if (newtype < hullAlign) {
1362 setType(hullEqnArray);
1364 } else if (newtype == hullGather || newtype == hullMultline) {
1372 else if (type_ == hullMultline || type_ == hullGather) {
1373 if (newtype == hullGather || newtype == hullMultline)
1375 else if (newtype == hullAlign || newtype == hullFlAlign ||
1376 newtype == hullAlignAt || newtype == hullXAlignAt) {
1379 } else if (newtype == hullXXAlignAt) {
1381 for (row_type row = 0; row < nrows(); ++row)
1382 numbered(row, false);
1386 setType(hullEqnArray);
1392 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1393 << "' to '" << to_utf8(hullName(newtype))
1394 << "' not implemented" << endl;
1399 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1400 bool last_eoln) const
1403 if (numberedType()) {
1404 if (label_[row] && numbered(row)) {
1405 docstring const name =
1406 latex ? escape(label_[row]->getParam("name"))
1407 : label_[row]->getParam("name");
1408 res += "\\label{" + name + '}';
1410 if (type_ != hullMultline) {
1411 if (numbered_[row] == NONUMBER)
1412 res += "\\nonumber ";
1413 else if (numbered_[row] == NOTAG)
1417 // Never add \\ on the last empty line of eqnarray and friends
1419 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1422 void InsetMathHull::write(WriteStream & os) const
1424 ModeSpecifier specifier(os, MATH_MODE);
1426 InsetMathGrid::write(os);
1431 void InsetMathHull::normalize(NormalStream & os) const
1433 os << "[formula " << hullName(type_) << ' ';
1434 InsetMathGrid::normalize(os);
1439 void InsetMathHull::infoize(odocstream & os) const
1441 os << bformat(_("Type: %1$s"), hullName(type_));
1445 void InsetMathHull::check() const
1447 LATTEST(numbered_.size() == nrows());
1448 LATTEST(numbers_.size() == nrows());
1449 LATTEST(label_.size() == nrows());
1453 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1457 idocstringstream iss(func.argument());
1458 iss >> dlang >> extra;
1460 extra = from_ascii("noextra");
1461 string const lang = to_ascii(dlang);
1463 // replace selection with result of computation
1464 if (reduceSelectionToOneCell(cur)) {
1466 asArray(grabAndEraseSelection(cur), ar);
1467 lyxerr << "use selection: " << ar << endl;
1468 cur.insert(pipeThroughExtern(lang, extra, ar));
1472 // only inline, display or eqnarray math is allowed
1473 if (getType() > hullEqnArray) {
1474 frontend::Alert::warning(_("Bad math environment"),
1475 _("Computation cannot be performed for AMS "
1476 "math environments.\nChange the math "
1477 "formula type and try again."));
1482 eq.push_back(MathAtom(new InsetMathChar('=')));
1484 // go to first item in line
1485 cur.idx() -= cur.idx() % ncols();
1488 if (getType() == hullSimple) {
1489 size_type pos = cur.cell().find_last(eq);
1491 if (pos == cur.cell().size()) {
1493 lyxerr << "use whole cell: " << ar << endl;
1495 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1496 lyxerr << "use partial cell form pos: " << pos << endl;
1498 cur.cell().append(eq);
1499 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1500 cur.pos() = cur.lastpos();
1504 if (getType() == hullEquation) {
1505 lyxerr << "use equation inset" << endl;
1506 mutate(hullEqnArray);
1507 MathData & ar = cur.cell();
1508 lyxerr << "use cell: " << ar << endl;
1512 cur.cell() = pipeThroughExtern(lang, extra, ar);
1513 // move to end of line
1514 cur.pos() = cur.lastpos();
1519 lyxerr << "use eqnarray" << endl;
1520 cur.idx() += 2 - cur.idx() % ncols();
1522 MathData ar = cur.cell();
1523 lyxerr << "use cell: " << ar << endl;
1524 // FIXME: temporarily disabled
1530 cur.cell() = pipeThroughExtern(lang, extra, ar);
1531 cur.pos() = cur.lastpos();
1536 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1538 //lyxerr << "action: " << cmd.action() << endl;
1539 switch (cmd.action()) {
1541 case LFUN_FINISHED_BACKWARD:
1542 case LFUN_FINISHED_FORWARD:
1543 case LFUN_FINISHED_RIGHT:
1544 case LFUN_FINISHED_LEFT:
1545 //lyxerr << "action: " << cmd.action() << endl;
1546 InsetMathGrid::doDispatch(cur, cmd);
1549 case LFUN_PARAGRAPH_BREAK:
1550 // just swallow this
1553 case LFUN_NEWLINE_INSERT:
1554 // some magic for the common case
1555 if (type_ == hullSimple || type_ == hullEquation) {
1556 cur.recordUndoInset();
1558 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1559 mutate(align ? hullAlign : hullEqnArray);
1560 // mutate() may change labels and such.
1561 cur.forceBufferUpdate();
1562 cur.idx() = nrows() * ncols() - 1;
1563 cur.pos() = cur.lastpos();
1565 InsetMathGrid::doDispatch(cur, cmd);
1568 case LFUN_MATH_NUMBER_TOGGLE: {
1569 //lyxerr << "toggling all numbers" << endl;
1570 cur.recordUndoInset();
1571 bool old = numberedType();
1572 if (type_ == hullMultline)
1573 numbered(nrows() - 1, !old);
1575 for (row_type row = 0; row < nrows(); ++row)
1576 numbered(row, !old);
1578 cur.message(old ? _("No number") : _("Number"));
1579 cur.forceBufferUpdate();
1583 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1584 cur.recordUndoInset();
1585 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1586 bool old = numbered(r);
1587 cur.message(old ? _("No number") : _("Number"));
1589 cur.forceBufferUpdate();
1593 case LFUN_LABEL_INSERT: {
1594 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1595 docstring old_label = label(r);
1596 docstring const default_label = from_ascii("eq:");
1597 if (old_label.empty())
1598 old_label = default_label;
1600 InsetCommandParams p(LABEL_CODE);
1601 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1602 string const data = InsetCommand::params2string(p);
1604 if (cmd.argument().empty())
1605 cur.bv().showDialog("label", data);
1607 FuncRequest fr(LFUN_INSET_INSERT, data);
1613 case LFUN_LABEL_COPY_AS_REFERENCE: {
1615 if (cmd.argument().empty() && &cur.inset() == this)
1616 // if there is no argument and we're inside math, we retrieve
1617 // the row number from the cursor position.
1618 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1620 // if there is an argument, find the corresponding label, else
1621 // check whether there is at least one label.
1622 for (row = 0; row != nrows(); ++row)
1623 if (numbered(row) && label_[row]
1624 && (cmd.argument().empty() || label(row) == cmd.argument()))
1631 InsetCommandParams p(REF_CODE, "ref");
1632 p["reference"] = label(row);
1633 cap::clearSelection();
1634 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1638 case LFUN_WORD_DELETE_FORWARD:
1639 case LFUN_CHAR_DELETE_FORWARD:
1640 if (col(cur.idx()) + 1 == ncols()
1641 && cur.pos() == cur.lastpos()
1642 && !cur.selection()) {
1643 if (!label(row(cur.idx())).empty()) {
1644 cur.recordUndoInset();
1645 label(row(cur.idx()), docstring());
1646 } else if (numbered(row(cur.idx()))) {
1647 cur.recordUndoInset();
1648 numbered(row(cur.idx()), false);
1649 cur.forceBufferUpdate();
1651 InsetMathGrid::doDispatch(cur, cmd);
1655 InsetMathGrid::doDispatch(cur, cmd);
1660 case LFUN_INSET_INSERT: {
1661 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1662 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1663 string const name = cmd.getArg(0);
1664 if (name == "label") {
1665 InsetCommandParams p(LABEL_CODE);
1666 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1667 docstring str = p["name"];
1668 cur.recordUndoInset();
1669 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1673 docstring old = label(r);
1676 // The label will take care of the reference update.
1680 // Newly created inset so initialize it.
1681 label_[r]->initView();
1684 cur.forceBufferUpdate();
1687 InsetMathGrid::doDispatch(cur, cmd);
1691 case LFUN_MATH_EXTERN:
1692 cur.recordUndoInset();
1696 case LFUN_MATH_MUTATE: {
1697 cur.recordUndoInset();
1698 row_type row = cur.row();
1699 col_type col = cur.col();
1700 mutate(hullType(cmd.argument()));
1701 cur.idx() = row * ncols() + col;
1702 if (cur.idx() > cur.lastidx()) {
1703 cur.idx() = cur.lastidx();
1704 cur.pos() = cur.lastpos();
1706 if (cur.pos() > cur.lastpos())
1707 cur.pos() = cur.lastpos();
1709 cur.forceBufferUpdate();
1710 // FIXME: find some more clever handling of the selection,
1711 // i.e. preserve it.
1712 cur.clearSelection();
1713 //cur.dispatched(FINISHED);
1717 case LFUN_MATH_DISPLAY: {
1718 cur.recordUndoInset();
1719 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1720 // if the cursor is in a cell that got merged, move it to
1721 // start of the hull inset.
1722 if (cur.idx() > 0) {
1726 if (cur.pos() > cur.lastpos())
1727 cur.pos() = cur.lastpos();
1733 InsetMathGrid::doDispatch(cur, cmd);
1739 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1740 FuncStatus & status) const
1742 switch (cmd.action()) {
1743 case LFUN_FINISHED_BACKWARD:
1744 case LFUN_FINISHED_FORWARD:
1745 case LFUN_FINISHED_RIGHT:
1746 case LFUN_FINISHED_LEFT:
1749 case LFUN_NEWLINE_INSERT:
1750 case LFUN_MATH_EXTERN:
1752 status.setEnabled(true);
1755 // we never allow this in math, and we want to bind enter
1756 // to another actions in command-alternatives
1757 case LFUN_PARAGRAPH_BREAK:
1758 status.setEnabled(false);
1760 case LFUN_MATH_MUTATE: {
1761 HullType const ht = hullType(cmd.argument());
1762 status.setOnOff(type_ == ht);
1763 status.setEnabled(true);
1765 if (ht != hullSimple) {
1766 Cursor tmpcur = cur;
1767 while (!tmpcur.empty()) {
1768 InsetCode code = tmpcur.inset().lyxCode();
1769 if (code == BOX_CODE) {
1771 } else if (code == TABULAR_CODE) {
1772 FuncRequest tmpcmd(LFUN_MATH_DISPLAY);
1773 if (tmpcur.getStatus(tmpcmd, status) && !status.enabled())
1781 case LFUN_MATH_DISPLAY: {
1783 if (cur.depth() > 1) {
1784 Inset const & in = cur[cur.depth()-2].inset();
1785 if (in.lyxCode() == SCRIPT_CODE)
1786 enable = display() != Inline;
1788 status.setEnabled(enable);
1789 status.setOnOff(display() != Inline);
1793 case LFUN_MATH_NUMBER_TOGGLE:
1794 // FIXME: what is the right test, this or the one of
1796 status.setEnabled(display() != Inline);
1797 status.setOnOff(numberedType());
1800 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1801 // FIXME: what is the right test, this or the one of
1803 bool const enable = (type_ == hullMultline)
1804 ? (nrows() - 1 == cur.row())
1805 : display() != Inline;
1806 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1807 status.setEnabled(enable);
1808 status.setOnOff(enable && numbered(r));
1812 case LFUN_LABEL_INSERT:
1813 status.setEnabled(type_ != hullSimple);
1816 case LFUN_LABEL_COPY_AS_REFERENCE: {
1817 bool enabled = false;
1819 if (cmd.argument().empty() && &cur.inset() == this) {
1820 // if there is no argument and we're inside math, we retrieve
1821 // the row number from the cursor position.
1822 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1823 enabled = numberedType() && label_[row] && numbered(row);
1825 // if there is an argument, find the corresponding label, else
1826 // check whether there is at least one label.
1827 for (row_type row = 0; row != nrows(); ++row) {
1828 if (numbered(row) && label_[row] &&
1829 (cmd.argument().empty() || label(row) == cmd.argument())) {
1835 status.setEnabled(enabled);
1839 case LFUN_INSET_INSERT:
1840 if (cmd.getArg(0) == "label") {
1841 status.setEnabled(type_ != hullSimple);
1844 return InsetMathGrid::getStatus(cur, cmd, status);
1846 case LFUN_INSET_MODIFY: {
1847 istringstream is(to_utf8(cmd.argument()));
1851 return InsetMathGrid::getStatus(cur, cmd, status);
1854 && (s == "append-row"
1855 || s == "delete-row"
1856 || s == "copy-row")) {
1857 status.message(bformat(
1858 from_utf8(N_("Can't change number of rows in '%1$s'")),
1860 status.setEnabled(false);
1864 && (s == "append-column"
1865 || s == "delete-column"
1866 || s == "copy-column")) {
1867 status.message(bformat(
1868 from_utf8(N_("Can't change number of columns in '%1$s'")),
1870 status.setEnabled(false);
1873 if ((type_ == hullSimple
1874 || type_ == hullEquation
1875 || type_ == hullNone) &&
1876 (s == "add-hline-above" || s == "add-hline-below")) {
1877 status.message(bformat(
1878 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1880 status.setEnabled(false);
1883 if (s == "add-vline-left" || s == "add-vline-right") {
1884 status.message(bformat(
1885 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1887 status.setEnabled(false);
1890 if (s == "valign-top" || s == "valign-middle"
1891 || s == "valign-bottom" || s == "align-left"
1892 || s == "align-center" || s == "align-right") {
1893 status.setEnabled(false);
1896 return InsetMathGrid::getStatus(cur, cmd, status);
1900 return InsetMathGrid::getStatus(cur, cmd, status);
1903 // This cannot really happen, but inserted to shut-up gcc
1904 return InsetMathGrid::getStatus(cur, cmd, status);
1908 /////////////////////////////////////////////////////////////////////
1912 // simply scrap this function if you want
1913 void InsetMathHull::mutateToText()
1916 // translate to latex
1918 latex(os, false, false);
1919 string str = os.str();
1922 Text * lt = view_->cursor().innerText();
1923 string::const_iterator cit = str.begin();
1924 string::const_iterator end = str.end();
1925 for (; cit != end; ++cit)
1926 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1929 //dispatch(LFUN_ESCAPE);
1934 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1935 docstring const & font)
1937 // this whole function is a hack and won't work for incremental font
1940 if (cur.inset().asInsetMath()->name() == font)
1941 cur.handleFont(to_utf8(font));
1943 cur.handleNest(createInsetMath(font, cur.buffer()));
1949 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1954 font.fromString(to_utf8(arg), b);
1955 if (font.fontInfo().color() != Color_inherit) {
1956 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1957 cur.handleNest(at, 0);
1962 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1965 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1966 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1967 enter_front ? idxFirst(cur) : idxLast(cur);
1968 // The inset formula dimension is not necessarily the same as the
1969 // one of the instant preview image, so we have to indicate to the
1970 // BufferView that a metrics update is needed.
1971 cur.screenUpdateFlags(Update::Force);
1975 void InsetMathHull::revealCodes(Cursor & cur) const
1977 if (!cur.inMathed())
1979 odocstringstream os;
1981 cur.message(os.str());
1983 // write something to the minibuffer
1984 // translate to latex
1988 string str = os.str();
1990 string::size_type pos = 0;
1992 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1995 else if (*it == '\0') {
1997 pos = it - str.begin();
2003 res = res.substr(pos - 30);
2004 if (res.size() > 60)
2005 res = res.substr(0, 60);
2011 /////////////////////////////////////////////////////////////////////
2015 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2018 // FIXME: completely broken
2019 static InsetMathHull * lastformula = 0;
2020 static CursorBase current = DocIterator(ibegin(nucleus()));
2022 static string laststr;
2024 if (lastformula != this || laststr != str) {
2025 //lyxerr << "reset lastformula to " << this << endl;
2028 current = ibegin(nucleus());
2030 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2034 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2036 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2037 CursorSlice & top = it.back();
2038 MathData const & a = top.asInsetMath()->cell(top.idx_);
2039 if (a.matchpart(ar, top.pos_)) {
2040 bv->cursor().setSelection(it, ar.size());
2042 top.pos_ += ar.size();
2048 //lyxerr << "not found!" << endl;
2055 void InsetMathHull::write(ostream & os) const
2057 odocstringstream oss;
2058 TexRow texrow(false);
2059 otexrowstream ots(oss,texrow);
2060 WriteStream wi(ots, false, false, WriteStream::wsDefault);
2063 os << to_utf8(oss.str());
2067 void InsetMathHull::read(Lexer & lex)
2070 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2071 operator=(*at->asHullInset());
2075 bool InsetMathHull::readQuiet(Lexer & lex)
2078 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2080 operator=(*at->asHullInset());
2085 int InsetMathHull::plaintext(odocstringstream & os,
2086 OutputParams const & op, size_t max_length) const
2088 // disables ASCII-art for export of equations. See #2275.
2089 if (0 && display()) {
2093 TextPainter tpain(dim.width(), dim.height());
2094 drawT(tpain, 0, dim.ascent());
2096 // reset metrics cache to "real" values
2098 return tpain.textheight();
2101 odocstringstream oss;
2102 TexRow texrow(false);
2103 otexrowstream ots(oss,texrow);
2104 Encoding const * const enc = encodings.fromLyXName("utf8");
2105 WriteStream wi(ots, false, true, WriteStream::wsDefault, enc);
2108 if (type_ == hullRegexp)
2111 for (row_type r = 0; r < nrows(); ++r) {
2112 for (col_type c = 0; c < ncols(); ++c)
2113 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2114 // if it's for the TOC, we write just the first line
2115 // and do not include the newline.
2116 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2118 if (r < nrows() - 1)
2122 docstring const str = oss.str();
2128 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
2133 if (getType() == hullSimple)
2134 name = from_ascii("inlineequation");
2136 name = from_ascii("informalequation");
2138 docstring bname = name;
2139 if (!label(0).empty())
2140 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
2142 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
2144 odocstringstream ls;
2146 otexstream ols(ls, texrow);
2147 if (runparams.flavor == OutputParams::XML) {
2148 ms << MTag("alt role='tex' ");
2149 // Workaround for db2latex: db2latex always includes equations with
2150 // \ensuremath{} or \begin{display}\end{display}
2151 // so we strip LyX' math environment
2152 WriteStream wi(ols, false, false, WriteStream::wsDefault, runparams.encoding);
2153 InsetMathGrid::write(wi);
2154 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2159 InsetMathGrid::mathmlize(ms);
2162 ms << MTag("alt role='tex'");
2163 latex(ols, runparams);
2164 res = texrow.rows();
2165 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2169 ms << from_ascii("<graphic fileref=\"eqn/");
2170 if (!label(0).empty())
2171 ms << sgml::cleanID(buffer(), runparams, label(0));
2173 ms << sgml::uniqueID(from_ascii("anon"));
2175 if (runparams.flavor == OutputParams::XML)
2176 ms << from_ascii("\"/>");
2178 ms << from_ascii("\">");
2180 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2182 return ms.line() + res;
2186 bool InsetMathHull::haveNumbers() const
2188 bool havenumbers = false;
2189 // inline formulas are never numbered (bug 7351 part 3)
2190 if (getType() == hullSimple)
2192 for (size_t i = 0; i != numbered_.size(); ++i) {
2203 // We need to do something about alignment here.
2205 // This duplicates code from InsetMathGrid, but
2206 // we need access here to number information,
2207 // and we simply do not have that in InsetMathGrid.
2208 void InsetMathHull::htmlize(HtmlStream & os) const
2210 bool const havenumbers = haveNumbers();
2211 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2214 os << cell(index(0, 0));
2218 os << MTag("table", "class='mathtable'");
2219 for (row_type row = 0; row < nrows(); ++row) {
2221 for (col_type col = 0; col < ncols(); ++col) {
2223 os << cell(index(row, col));
2228 docstring const & num = numbers_[row];
2230 os << '(' << num << ')';
2235 os << ETag("table");
2239 // this duplicates code from InsetMathGrid, but
2240 // we need access here to number information,
2241 // and we simply do not have that in InsetMathGrid.
2242 void InsetMathHull::mathmlize(MathStream & os) const
2244 bool const havenumbers = haveNumbers();
2245 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2248 os << MTag("mtable");
2249 char const * const celltag = havetable ? "mtd" : "mrow";
2250 // FIXME There does not seem to be wide support at the moment
2251 // for mlabeledtr, so we have to use just mtr for now.
2252 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2253 char const * const rowtag = "mtr";
2254 for (row_type row = 0; row < nrows(); ++row) {
2257 for (col_type col = 0; col < ncols(); ++col) {
2259 << cell(index(row, col))
2265 docstring const & num = numbers_[row];
2267 os << '(' << num << ')';
2274 os << ETag("mtable");
2278 void InsetMathHull::mathAsLatex(WriteStream & os) const
2280 MathEnsurer ensurer(os, false);
2281 bool havenumbers = haveNumbers();
2282 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2285 os << cell(index(0, 0));
2289 os << "<table class='mathtable'>";
2290 for (row_type row = 0; row < nrows(); ++row) {
2292 for (col_type col = 0; col < ncols(); ++col) {
2293 os << "<td class='math'>";
2294 os << cell(index(row, col));
2299 docstring const & num = numbers_[row];
2301 os << '(' << num << ')';
2310 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2312 BufferParams::MathOutput const mathtype =
2313 buffer().masterBuffer()->params().html_math_output;
2315 bool success = false;
2317 // we output all the labels just at the beginning of the equation.
2318 // this should be fine.
2319 for (size_t i = 0; i != label_.size(); ++i) {
2320 InsetLabel const * const il = label_[i];
2326 // FIXME Eventually we would like to do this inset by inset.
2327 if (mathtype == BufferParams::MathML) {
2328 odocstringstream os;
2333 } catch (MathExportException const &) {}
2335 if (getType() == hullSimple)
2336 xs << html::StartTag("math",
2337 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2339 xs << html::StartTag("math",
2340 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2341 xs << XHTMLStream::ESCAPE_NONE
2343 << html::EndTag("math");
2345 } else if (mathtype == BufferParams::HTML) {
2346 odocstringstream os;
2351 } catch (MathExportException const &) {}
2353 string const tag = (getType() == hullSimple) ? "span" : "div";
2354 xs << html::StartTag(tag, "class='formula'", true)
2355 << XHTMLStream::ESCAPE_NONE
2357 << html::EndTag(tag);
2361 // what we actually want is this:
2363 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2365 // || mathtype == BufferParams::Images
2367 // but what follows is equivalent, since we'll enter only if either (a) we
2368 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2369 // aren't doing LaTeX, in which case we are doing Images.
2370 if (!success && mathtype != BufferParams::LaTeX) {
2371 graphics::PreviewImage const * pimage = 0;
2373 loadPreview(docit_);
2374 pimage = preview_->getPreviewImage(buffer());
2375 // FIXME Do we always have png?
2378 if (pimage || op.dryrun) {
2379 string const filename = pimage ? pimage->filename().onlyFileName()
2380 : "previewimage.png";
2382 // if we are not in the master buffer, then we need to see that the
2383 // generated image is copied there; otherwise, preview fails.
2384 Buffer const * mbuf = buffer().masterBuffer();
2385 if (mbuf != &buffer()) {
2386 string mbtmp = mbuf->temppath();
2387 FileName const mbufimg(support::addName(mbtmp, filename));
2388 pimage->filename().copyTo(mbufimg);
2390 // add the file to the list of files to be exported
2391 op.exportdata->addExternalFile("xhtml", pimage->filename());
2394 string const tag = (getType() == hullSimple) ? "span" : "div";
2396 << html::StartTag(tag)
2397 << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2398 << html::EndTag(tag)
2404 // so we'll pass this test if we've failed everything else, or
2405 // if mathtype was LaTeX, since we won't have entered any of the
2407 if (!success /* || mathtype != BufferParams::LaTeX */) {
2408 // Unfortunately, we cannot use latexString() because we do not want
2409 // $...$ or whatever.
2410 odocstringstream ls;
2411 TexRow texrow(false);
2412 otexrowstream ots(ls,texrow);
2413 WriteStream wi(ots, false, true, WriteStream::wsPreview);
2414 ModeSpecifier specifier(wi, MATH_MODE);
2416 docstring const latex = ls.str();
2418 // class='math' allows for use of jsMath
2419 // http://www.math.union.edu/~dpvc/jsMath/
2421 // probably should allow for some kind of customization here
2422 string const tag = (getType() == hullSimple) ? "span" : "div";
2423 xs << html::StartTag(tag, "class='math'")
2425 << html::EndTag(tag)
2432 void InsetMathHull::toString(odocstream & os) const
2434 odocstringstream ods;
2435 plaintext(ods, OutputParams(0));
2440 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2442 odocstringstream ods;
2445 // FIXME: this results in spilling TeX into the LyXHTML output since the
2446 // outliner is used to generate the LyXHTML list of figures/etc.
2452 string InsetMathHull::contextMenuName() const
2454 return "context-math";
2458 void InsetMathHull::recordLocation(DocIterator const & di)