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 char InsetMathHull::defaultColAlign(col_type col)
354 if (type_ == hullEqnArray)
356 if (type_ == hullMultline)
358 if (type_ == hullGather)
360 if (type_ >= hullAlign)
361 return "rl"[col & 1];
366 char InsetMathHull::displayColAlign(idx_type idx) const
368 if (type_ == hullMultline) {
369 row_type const r = row(idx);
372 if (r == nrows() - 1)
375 return InsetMathGrid::displayColAlign(idx);
379 int InsetMathHull::defaultColSpace(col_type col)
381 if (type_ == hullAlign || type_ == hullAlignAt)
383 if (type_ == hullXAlignAt)
384 return (col & 1) ? 20 : 0;
385 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
386 return (col & 1) ? 40 : 0;
391 docstring InsetMathHull::standardFont() const
396 font_name = from_ascii("texttt");
399 font_name = from_ascii("lyxnochange");
402 font_name = from_ascii("mathnormal");
408 ColorCode InsetMathHull::standardColor() const
414 color = Color_foreground;
423 bool InsetMathHull::previewState(const BufferView *const bv) const
425 if (!editing(bv) && RenderPreview::previewMath()
426 && type_ != hullRegexp)
428 graphics::PreviewImage const * pimage =
429 preview_->getPreviewImage(bv->buffer());
430 return pimage && pimage->image();
437 static const int ERROR_FRAME_WIDTH = 2;
440 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
442 if (previewState(mi.base.bv)) {
443 preview_->metrics(mi, dim);
444 if (previewTooSmall(dim)) {
445 // preview image is too small
446 dim.wid += 2 * ERROR_FRAME_WIDTH;
447 dim.asc += 2 * ERROR_FRAME_WIDTH;
449 // insert a one pixel gap in front of the formula
452 dim.des += displayMargin();
454 // Cache the inset dimension.
455 setDimCache(mi, dim);
459 FontSetChanger dummy1(mi.base, standardFont());
460 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
462 // let the cells adjust themselves
463 InsetMathGrid::metrics(mi, dim);
466 dim.asc += displayMargin();
467 dim.des += displayMargin();
470 if (numberedType()) {
471 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
473 for (row_type row = 0; row < nrows(); ++row)
474 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
480 if (type_ == hullRegexp)
482 // make it at least as high as the current font
485 math_font_max_dim(mi.base.font, asc, des);
486 dim.asc = max(dim.asc, asc);
487 dim.des = max(dim.des, des);
488 // Cache the inset dimension.
489 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
490 setDimCache(mi, dim);
494 bool InsetMathHull::previewTooSmall(Dimension const & dim) const
496 return dim.width() <= 10 && dim.height() <= 10;
500 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
502 BufferView const * const bv = pi.base.bv;
503 if (previewState(bv)) {
504 Dimension const dim = dimension(*pi.base.bv);
505 if (previewTooSmall(dim))
507 return graphics::PreviewLoader::backgroundColor();
513 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
515 Dimension const dim = dimension(*pi.base.bv);
516 if (previewTooSmall(dim)) {
517 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
518 dim.wid, dim.asc + dim.des, backgroundColor(pi));
521 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
522 dim.asc + dim.des - 1, pi.backgroundColor(this));
526 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
528 BufferView const * const bv = pi.base.bv;
529 use_preview_ = previewState(bv);
531 if (type_ == hullRegexp) {
532 Dimension const dim = dimension(*bv);
533 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
534 dim.width() - 2, dim.height() - 2, Color_regexpframe);
538 Dimension const dim = dimension(*bv);
539 if (previewTooSmall(dim)) {
540 // we have an extra frame
541 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
543 // one pixel gap in front
544 preview_->draw(pi, x + 1, y);
546 setPosCache(pi, x, y);
550 ColorCode color = pi.selected && lyxrc.use_system_colors
551 ? Color_selectiontext : standardColor();
552 bool const really_change_color = pi.base.font.color() == Color_none;
553 ColorChanger dummy0(pi.base.font, color, really_change_color);
554 FontSetChanger dummy1(pi.base, standardFont());
555 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
557 InsetMathGrid::draw(pi, x + 1, y);
559 if (numberedType()) {
560 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
561 for (row_type row = 0; row < nrows(); ++row) {
562 int const yy = y + rowinfo_[row].offset_;
563 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
564 docstring const nl = nicelabel(row);
568 setPosCache(pi, x, y);
572 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
575 InsetMathGrid::metricsT(mi, dim);
578 TexRow texrow(false);
579 otexrowstream ots(os,texrow);
580 WriteStream wi(ots, false, true, WriteStream::wsDefault);
582 dim.wid = os.str().size();
589 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
592 InsetMathGrid::drawT(pain, x, y);
595 TexRow texrow(false);
596 otexrowstream ots(os,texrow);
597 WriteStream wi(ots, false, true, WriteStream::wsDefault);
599 pain.draw(x, y, os.str().c_str());
604 static docstring latexString(InsetMathHull const & inset)
607 // This has to be static, because a preview snippet or a math
608 // macro containing math in text mode (such as $\text{$\phi$}$ or
609 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
610 // first time as a whole, and the second time only the inner math.
611 // In this last case inset.buffer() would be invalid.
612 static Encoding const * encoding = 0;
613 if (inset.isBufferValid())
614 encoding = &(inset.buffer().params().encoding());
615 TexRow texrow(false);
616 otexrowstream ots(ls,texrow);
617 WriteStream wi(ots, false, true, WriteStream::wsPreview, encoding);
623 void InsetMathHull::initUnicodeMath() const
625 // Trigger classification of the unicode symbols in this inset
626 docstring const dummy = latexString(*this);
630 void InsetMathHull::addPreview(DocIterator const & inset_pos,
631 graphics::PreviewLoader & /*ploader*/) const
633 if (RenderPreview::previewMath()) {
634 preparePreview(inset_pos);
639 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
640 MacroNameSet & macros, MacroNameSet & defs) const
642 MacroNameSet::iterator const end = macros.end();
644 for (size_t i = 0; i < md.size(); ++i) {
645 MathMacro const * mi = md[i].nucleus()->asMacro();
646 MathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
647 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
648 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
649 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
650 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
652 // Look for macros in the arguments of this macro.
653 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
654 usedMacros(mi->cell(idx), pos, macros, defs);
655 // Make sure this is a macro defined in the document
656 // (as we also spot the macros in the symbols file)
657 // or that we have not already accounted for it.
658 docstring const name = mi->name();
659 if (macros.find(name) == end)
662 // Look for macros in the definition of this macro.
663 MathData ar(pos.buffer());
664 MacroData const * data =
665 pos.buffer()->getMacro(name, pos, true);
667 odocstringstream macro_def;
668 data->write(macro_def, true);
670 defs.insert(macro_def.str());
671 asArray(data->definition(), ar);
673 usedMacros(ar, pos, macros, defs);
675 MathData ar(pos.buffer());
676 asArray(mt->definition(), ar);
677 usedMacros(ar, pos, macros, defs);
679 if (!si->nuc().empty())
680 usedMacros(si->nuc(), pos, macros, defs);
682 usedMacros(si->down(), pos, macros, defs);
684 usedMacros(si->up(), pos, macros, defs);
685 } else if (fi || gi) {
686 idx_type nidx = fi ? fi->nargs() : gi->nargs();
687 for (idx_type idx = 0; idx < nidx; ++idx)
688 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
691 usedMacros(ni->cell(0), pos, macros, defs);
697 void InsetMathHull::preparePreview(DocIterator const & pos,
698 bool forexport) const
700 // there is no need to do all the macro stuff if we're not
701 // actually going to generate the preview.
702 if (!RenderPreview::previewMath() && !forexport)
705 Buffer const * buffer = pos.buffer();
707 // collect macros at this position
709 buffer->listMacroNames(macros);
711 // collect definitions only for the macros used in this inset
713 for (idx_type idx = 0; idx < nargs(); ++idx)
714 usedMacros(cell(idx), pos, macros, defs);
716 MacroNameSet::iterator it = defs.begin();
717 MacroNameSet::iterator end = defs.end();
718 docstring macro_preamble;
719 for (; it != end; ++it)
720 macro_preamble.append(*it);
722 // set the font series and size for this snippet
723 DocIterator dit = pos;
724 while (dit.inMathed())
726 Paragraph const & par = dit.paragraph();
727 Font font = par.getFontSettings(buffer->params(), dit.pos());
728 font.fontInfo().realize(par.layout().font);
729 string const lsize = font.latexSize();
732 if (font.fontInfo().series() == BOLD_SERIES) {
733 setfont += from_ascii("\\textbf{");
736 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
737 setfont += from_ascii("\\" + lsize + '\n');
740 if (forexport && haveNumbers()) {
741 docstring eqstr = from_ascii("equation");
742 CounterMap::const_iterator it = counter_map.find(eqstr);
743 if (it != counter_map.end()) {
744 int num = it->second;
746 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
747 '{' + convert<docstring>(num) + '}' + '\n';
749 for (size_t i = 0; i != numcnts; ++i) {
750 docstring cnt = from_ascii(counters_to_save[i]);
751 it = counter_map.find(cnt);
752 if (it == counter_map.end())
754 int num = it->second;
756 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
757 '{' + convert<docstring>(num) + '}';
760 docstring const snippet = macro_preamble + setfont + setcnt
761 + latexString(*this) + endfont;
762 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
763 preview_->addPreview(snippet, *buffer, forexport);
767 void InsetMathHull::reloadPreview(DocIterator const & pos) const
770 preview_->startLoading(*pos.buffer());
774 void InsetMathHull::loadPreview(DocIterator const & pos) const
776 bool const forexport = true;
777 preparePreview(pos, forexport);
778 preview_->startLoading(*pos.buffer(), forexport);
782 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
784 if (RenderPreview::previewMath()) {
786 cur.screenUpdateFlags(Update::Force);
792 docstring InsetMathHull::label(row_type row) const
794 LASSERT(row < nrows(), return docstring());
795 if (InsetLabel * il = label_[row])
796 return il->screenLabel();
801 void InsetMathHull::label(row_type row, docstring const & label)
803 //lyxerr << "setting label '" << label << "' for row " << row << endl;
807 label_[row] = dummy_pointer;
810 label_[row]->updateLabelAndRefs(label);
812 label_[row]->setParam("name", label);
816 InsetCommandParams p(LABEL_CODE);
818 label_[row] = new InsetLabel(buffer_, p);
820 label_[row]->setBuffer(buffer());
824 void InsetMathHull::numbered(row_type row, Numbered num)
826 numbered_[row] = num;
827 if (!numbered(row) && label_[row]) {
834 bool InsetMathHull::numbered(row_type row) const
836 return numbered_[row] == NUMBER;
840 bool InsetMathHull::ams() const
858 for (size_t row = 0; row < numbered_.size(); ++row)
859 if (numbered_[row] == NOTAG)
865 Inset::DisplayType InsetMathHull::display() const
867 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
872 bool InsetMathHull::numberedType() const
874 if (type_ == hullNone)
876 if (type_ == hullSimple)
878 if (type_ == hullXXAlignAt)
880 if (type_ == hullRegexp)
882 for (row_type row = 0; row < nrows(); ++row)
889 void InsetMathHull::validate(LaTeXFeatures & features) const
891 if (features.runparams().isLaTeX()) {
893 features.require("amsmath");
895 if (type_ == hullRegexp) {
896 features.require("color");
897 string frcol = lcolor.getLaTeXName(Color_regexpframe);
898 string bgcol = "white";
899 features.addPreambleSnippet(
900 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
901 + frcol + string("}{")
902 + bgcol + string("}{\\ensuremath{\\mathtt{#1}}}}"));
903 features.addPreambleSnippet(
904 string("\\newcommand{\\endregexp}{}"));
907 // Validation is necessary only if not using AMS math.
908 // To be safe, we will always run mathedvalidate.
909 //if (features.amsstyle)
912 //features.binom = true;
913 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
914 // it would be better to do this elsewhere, but we can't validate in
915 // InsetMathMatrix and we have no way, outside MathExtern, to know if
916 // we even have any matrices.
917 features.addCSSSnippet(
918 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
919 "table.matrix td{padding: 0.25px;}\n"
920 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
921 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
923 InsetMathGrid::validate(features);
927 void InsetMathHull::header_write(WriteStream & os) const
929 bool n = numberedType();
946 os << "\\begin{equation" << star(n) << "}\n";
958 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
965 os << "\\begin{" << hullName(type_) << star(n) << '}'
966 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
972 os << "\\begin{" << hullName(type_) << '}'
973 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
983 os << "\\begin{unknown" << star(n) << "}\n";
989 void InsetMathHull::footer_write(WriteStream & os) const
991 bool n = numberedType();
1006 os << "\\end{equation" << star(n) << "}\n";
1020 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1026 os << "\\end{" << hullName(type_) << "}\n";
1030 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1031 os << "\\endregexp{}}";
1037 os << "\\end{unknown" << star(n) << "}\n";
1043 bool InsetMathHull::rowChangeOK() const
1046 type_ == hullEqnArray || type_ == hullAlign ||
1047 type_ == hullFlAlign || type_ == hullAlignAt ||
1048 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1049 type_ == hullGather || type_ == hullMultline;
1053 bool InsetMathHull::colChangeOK() const
1056 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1057 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1061 void InsetMathHull::addRow(row_type row)
1066 bool numbered = numberedType();
1067 // Move the number and raw pointer, do not call label() (bug 7511)
1068 InsetLabel * label = dummy_pointer;
1069 docstring number = empty_docstring();
1070 if (type_ == hullMultline) {
1071 if (row + 1 == nrows()) {
1072 numbered_[row] = NONUMBER;
1073 swap(label, label_[row]);
1074 swap(number, numbers_[row]);
1079 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1080 numbers_.insert(numbers_.begin() + row + 1, number);
1081 label_.insert(label_.begin() + row + 1, label);
1082 InsetMathGrid::addRow(row);
1086 void InsetMathHull::swapRow(row_type row)
1090 if (row + 1 == nrows())
1092 swap(numbered_[row], numbered_[row + 1]);
1093 swap(numbers_[row], numbers_[row + 1]);
1094 swap(label_[row], label_[row + 1]);
1095 InsetMathGrid::swapRow(row);
1099 void InsetMathHull::delRow(row_type row)
1101 if (nrows() <= 1 || !rowChangeOK())
1103 if (row + 1 == nrows() && type_ == hullMultline) {
1104 swap(numbered_[row - 1], numbered_[row]);
1105 swap(numbers_[row - 1], numbers_[row]);
1106 swap(label_[row - 1], label_[row]);
1107 InsetMathGrid::delRow(row);
1110 InsetMathGrid::delRow(row);
1111 // The last dummy row has no number info nor a label.
1112 // Test nrows() + 1 because we have already erased the row.
1113 if (row == nrows() + 1)
1115 numbered_.erase(numbered_.begin() + row);
1116 numbers_.erase(numbers_.begin() + row);
1118 label_.erase(label_.begin() + row);
1122 void InsetMathHull::addCol(col_type col)
1126 InsetMathGrid::addCol(col);
1130 void InsetMathHull::delCol(col_type col)
1132 if (ncols() <= 1 || !colChangeOK())
1134 InsetMathGrid::delCol(col);
1138 docstring InsetMathHull::nicelabel(row_type row) const
1142 docstring const & val = numbers_[row];
1144 return '(' + val + ')';
1145 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1149 void InsetMathHull::glueall(HullType type)
1152 for (idx_type i = 0; i < nargs(); ++i)
1154 InsetLabel * label = 0;
1155 if (type == hullEquation) {
1156 // preserve first non-empty label
1157 for (row_type row = 0; row < nrows(); ++row) {
1159 label = label_[row];
1165 *this = InsetMathHull(buffer_, hullSimple);
1172 void InsetMathHull::splitTo2Cols()
1174 LASSERT(ncols() == 1, return);
1175 InsetMathGrid::addCol(1);
1176 for (row_type row = 0; row < nrows(); ++row) {
1177 idx_type const i = 2 * row;
1178 pos_type pos = firstRelOp(cell(i));
1179 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1180 cell(i).erase(pos, cell(i).size());
1185 void InsetMathHull::splitTo3Cols()
1187 LASSERT(ncols() < 3, return);
1190 InsetMathGrid::addCol(2);
1191 for (row_type row = 0; row < nrows(); ++row) {
1192 idx_type const i = 3 * row + 1;
1193 if (!cell(i).empty()) {
1194 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1195 cell(i).erase(1, cell(i).size());
1201 void InsetMathHull::changeCols(col_type cols)
1203 if (ncols() == cols)
1205 else if (ncols() < cols) {
1211 while (ncols() < cols)
1212 InsetMathGrid::addCol(ncols());
1218 for (row_type row = 0; row < nrows(); ++row) {
1219 idx_type const i = row * ncols();
1220 for (col_type col = cols; col < ncols(); ++col) {
1221 cell(i + cols - 1).append(cell(i + col));
1225 while (ncols() > cols) {
1226 InsetMathGrid::delCol(ncols() - 1);
1231 HullType InsetMathHull::getType() const
1237 void InsetMathHull::setType(HullType type)
1244 void InsetMathHull::mutate(HullType newtype)
1246 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1248 // we try to move along the chain
1249 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1251 // +-------------------------------------+
1252 // we use eqnarray as intermediate type for mutations that are not
1253 // directly supported because it handles labels and numbering for
1256 if (newtype == type_) {
1260 else if (newtype < hullNone) {
1265 else if (type_ == hullNone) {
1266 setType(hullSimple);
1271 else if (type_ == hullSimple) {
1272 if (newtype == hullNone) {
1276 setType(hullEquation);
1277 numbered(0, label_[0] ? true : false);
1282 else if (type_ == hullEquation) {
1283 if (newtype < type_) {
1284 setType(hullSimple);
1287 } else if (newtype == hullEqnArray) {
1288 // split it "nicely" on the first relop
1290 setType(hullEqnArray);
1291 } else if (newtype == hullMultline || newtype == hullGather) {
1294 // split it "nicely"
1301 else if (type_ == hullEqnArray) {
1302 if (newtype < type_) {
1305 } else { // align & Co.
1312 else if (type_ == hullAlign || type_ == hullAlignAt ||
1313 type_ == hullXAlignAt || type_ == hullFlAlign) {
1314 if (newtype < hullAlign) {
1316 setType(hullEqnArray);
1318 } else if (newtype == hullGather || newtype == hullMultline) {
1321 } else if (newtype == hullXXAlignAt) {
1322 for (row_type row = 0; row < nrows(); ++row)
1323 numbered(row, false);
1330 else if (type_ == hullXXAlignAt) {
1331 for (row_type row = 0; row < nrows(); ++row)
1332 numbered(row, false);
1333 if (newtype < hullAlign) {
1335 setType(hullEqnArray);
1337 } else if (newtype == hullGather || newtype == hullMultline) {
1345 else if (type_ == hullMultline || type_ == hullGather) {
1346 if (newtype == hullGather || newtype == hullMultline)
1348 else if (newtype == hullAlign || newtype == hullFlAlign ||
1349 newtype == hullAlignAt || newtype == hullXAlignAt) {
1352 } else if (newtype == hullXXAlignAt) {
1354 for (row_type row = 0; row < nrows(); ++row)
1355 numbered(row, false);
1359 setType(hullEqnArray);
1365 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1366 << "' to '" << to_utf8(hullName(newtype))
1367 << "' not implemented" << endl;
1372 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1373 bool last_eoln) const
1376 if (numberedType()) {
1377 if (label_[row] && numbered(row)) {
1378 docstring const name =
1379 latex ? escape(label_[row]->getParam("name"))
1380 : label_[row]->getParam("name");
1381 res += "\\label{" + name + '}';
1383 if (type_ != hullMultline) {
1384 if (numbered_[row] == NONUMBER)
1385 res += "\\nonumber ";
1386 else if (numbered_[row] == NOTAG)
1390 // Never add \\ on the last empty line of eqnarray and friends
1392 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1395 void InsetMathHull::write(WriteStream & os) const
1397 ModeSpecifier specifier(os, MATH_MODE);
1399 InsetMathGrid::write(os);
1404 void InsetMathHull::normalize(NormalStream & os) const
1406 os << "[formula " << hullName(type_) << ' ';
1407 InsetMathGrid::normalize(os);
1412 void InsetMathHull::infoize(odocstream & os) const
1414 os << bformat(_("Type: %1$s"), hullName(type_));
1418 void InsetMathHull::check() const
1420 LATTEST(numbered_.size() == nrows());
1421 LATTEST(numbers_.size() == nrows());
1422 LATTEST(label_.size() == nrows());
1426 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1430 idocstringstream iss(func.argument());
1431 iss >> dlang >> extra;
1433 extra = from_ascii("noextra");
1434 string const lang = to_ascii(dlang);
1436 // replace selection with result of computation
1437 if (reduceSelectionToOneCell(cur)) {
1439 asArray(grabAndEraseSelection(cur), ar);
1440 lyxerr << "use selection: " << ar << endl;
1441 cur.insert(pipeThroughExtern(lang, extra, ar));
1445 // only inline, display or eqnarray math is allowed
1446 if (getType() > hullEqnArray) {
1447 frontend::Alert::warning(_("Bad math environment"),
1448 _("Computation cannot be performed for AMS "
1449 "math environments.\nChange the math "
1450 "formula type and try again."));
1455 eq.push_back(MathAtom(new InsetMathChar('=')));
1457 // go to first item in line
1458 cur.idx() -= cur.idx() % ncols();
1461 if (getType() == hullSimple) {
1462 size_type pos = cur.cell().find_last(eq);
1464 if (pos == cur.cell().size()) {
1466 lyxerr << "use whole cell: " << ar << endl;
1468 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1469 lyxerr << "use partial cell form pos: " << pos << endl;
1471 cur.cell().append(eq);
1472 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1473 cur.pos() = cur.lastpos();
1477 if (getType() == hullEquation) {
1478 lyxerr << "use equation inset" << endl;
1479 mutate(hullEqnArray);
1480 MathData & ar = cur.cell();
1481 lyxerr << "use cell: " << ar << endl;
1485 cur.cell() = pipeThroughExtern(lang, extra, ar);
1486 // move to end of line
1487 cur.pos() = cur.lastpos();
1492 lyxerr << "use eqnarray" << endl;
1493 cur.idx() += 2 - cur.idx() % ncols();
1495 MathData ar = cur.cell();
1496 lyxerr << "use cell: " << ar << endl;
1497 // FIXME: temporarily disabled
1503 cur.cell() = pipeThroughExtern(lang, extra, ar);
1504 cur.pos() = cur.lastpos();
1509 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1511 //lyxerr << "action: " << cmd.action() << endl;
1512 switch (cmd.action()) {
1514 case LFUN_FINISHED_BACKWARD:
1515 case LFUN_FINISHED_FORWARD:
1516 case LFUN_FINISHED_RIGHT:
1517 case LFUN_FINISHED_LEFT:
1518 //lyxerr << "action: " << cmd.action() << endl;
1519 InsetMathGrid::doDispatch(cur, cmd);
1522 case LFUN_PARAGRAPH_BREAK:
1523 // just swallow this
1526 case LFUN_NEWLINE_INSERT:
1527 // some magic for the common case
1528 if (type_ == hullSimple || type_ == hullEquation) {
1529 cur.recordUndoInset();
1531 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1532 mutate(align ? hullAlign : hullEqnArray);
1533 // mutate() may change labels and such.
1534 cur.forceBufferUpdate();
1535 cur.idx() = nrows() * ncols() - 1;
1536 cur.pos() = cur.lastpos();
1538 InsetMathGrid::doDispatch(cur, cmd);
1541 case LFUN_MATH_NUMBER_TOGGLE: {
1542 //lyxerr << "toggling all numbers" << endl;
1543 cur.recordUndoInset();
1544 bool old = numberedType();
1545 if (type_ == hullMultline)
1546 numbered(nrows() - 1, !old);
1548 for (row_type row = 0; row < nrows(); ++row)
1549 numbered(row, !old);
1551 cur.message(old ? _("No number") : _("Number"));
1552 cur.forceBufferUpdate();
1556 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1557 cur.recordUndoInset();
1558 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1559 bool old = numbered(r);
1560 cur.message(old ? _("No number") : _("Number"));
1562 cur.forceBufferUpdate();
1566 case LFUN_LABEL_INSERT: {
1567 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1568 docstring old_label = label(r);
1569 docstring const default_label = from_ascii("eq:");
1570 if (old_label.empty())
1571 old_label = default_label;
1573 InsetCommandParams p(LABEL_CODE);
1574 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1575 string const data = InsetCommand::params2string(p);
1577 if (cmd.argument().empty())
1578 cur.bv().showDialog("label", data);
1580 FuncRequest fr(LFUN_INSET_INSERT, data);
1586 case LFUN_LABEL_COPY_AS_REFERENCE: {
1588 if (cmd.argument().empty() && &cur.inset() == this)
1589 // if there is no argument and we're inside math, we retrieve
1590 // the row number from the cursor position.
1591 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1593 // if there is an argument, find the corresponding label, else
1594 // check whether there is at least one label.
1595 for (row = 0; row != nrows(); ++row)
1596 if (numbered(row) && label_[row]
1597 && (cmd.argument().empty() || label(row) == cmd.argument()))
1604 InsetCommandParams p(REF_CODE, "ref");
1605 p["reference"] = label(row);
1606 cap::clearSelection();
1607 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1611 case LFUN_WORD_DELETE_FORWARD:
1612 case LFUN_CHAR_DELETE_FORWARD:
1613 if (col(cur.idx()) + 1 == ncols()
1614 && cur.pos() == cur.lastpos()
1615 && !cur.selection()) {
1616 if (!label(row(cur.idx())).empty()) {
1617 cur.recordUndoInset();
1618 label(row(cur.idx()), docstring());
1619 } else if (numbered(row(cur.idx()))) {
1620 cur.recordUndoInset();
1621 numbered(row(cur.idx()), false);
1622 cur.forceBufferUpdate();
1624 InsetMathGrid::doDispatch(cur, cmd);
1628 InsetMathGrid::doDispatch(cur, cmd);
1633 case LFUN_INSET_INSERT: {
1634 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1635 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1636 string const name = cmd.getArg(0);
1637 if (name == "label") {
1638 InsetCommandParams p(LABEL_CODE);
1639 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1640 docstring str = p["name"];
1641 cur.recordUndoInset();
1642 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1646 docstring old = label(r);
1649 // The label will take care of the reference update.
1653 // Newly created inset so initialize it.
1654 label_[r]->initView();
1657 cur.forceBufferUpdate();
1660 InsetMathGrid::doDispatch(cur, cmd);
1664 case LFUN_MATH_EXTERN:
1665 cur.recordUndoInset();
1669 case LFUN_MATH_MUTATE: {
1670 cur.recordUndoInset();
1671 row_type row = cur.row();
1672 col_type col = cur.col();
1673 mutate(hullType(cmd.argument()));
1674 cur.idx() = row * ncols() + col;
1675 if (cur.idx() > cur.lastidx()) {
1676 cur.idx() = cur.lastidx();
1677 cur.pos() = cur.lastpos();
1679 if (cur.pos() > cur.lastpos())
1680 cur.pos() = cur.lastpos();
1682 cur.forceBufferUpdate();
1683 // FIXME: find some more clever handling of the selection,
1684 // i.e. preserve it.
1685 cur.clearSelection();
1686 //cur.dispatched(FINISHED);
1690 case LFUN_MATH_DISPLAY: {
1691 cur.recordUndoInset();
1692 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1693 // if the cursor is in a cell that got merged, move it to
1694 // start of the hull inset.
1695 if (cur.idx() > 0) {
1699 if (cur.pos() > cur.lastpos())
1700 cur.pos() = cur.lastpos();
1706 InsetMathGrid::doDispatch(cur, cmd);
1712 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1713 FuncStatus & status) const
1715 switch (cmd.action()) {
1716 case LFUN_FINISHED_BACKWARD:
1717 case LFUN_FINISHED_FORWARD:
1718 case LFUN_FINISHED_RIGHT:
1719 case LFUN_FINISHED_LEFT:
1722 case LFUN_NEWLINE_INSERT:
1723 case LFUN_MATH_EXTERN:
1725 status.setEnabled(true);
1728 // we never allow this in math, and we want to bind enter
1729 // to another actions in command-alternatives
1730 case LFUN_PARAGRAPH_BREAK:
1731 status.setEnabled(false);
1733 case LFUN_MATH_MUTATE: {
1734 HullType const ht = hullType(cmd.argument());
1735 status.setOnOff(type_ == ht);
1736 status.setEnabled(true);
1738 if (ht != hullSimple) {
1739 Cursor tmpcur = cur;
1740 while (!tmpcur.empty()) {
1741 InsetCode code = tmpcur.inset().lyxCode();
1742 if (code == BOX_CODE) {
1744 } else if (code == TABULAR_CODE) {
1745 FuncRequest tmpcmd(LFUN_MATH_DISPLAY);
1746 if (tmpcur.getStatus(tmpcmd, status) && !status.enabled())
1754 case LFUN_MATH_DISPLAY: {
1756 if (cur.depth() > 1) {
1757 Inset const & in = cur[cur.depth()-2].inset();
1758 if (in.lyxCode() == SCRIPT_CODE)
1759 enable = display() != Inline;
1761 status.setEnabled(enable);
1762 status.setOnOff(display() != Inline);
1766 case LFUN_MATH_NUMBER_TOGGLE:
1767 // FIXME: what is the right test, this or the one of
1769 status.setEnabled(display() != Inline);
1770 status.setOnOff(numberedType());
1773 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1774 // FIXME: what is the right test, this or the one of
1776 bool const enable = (type_ == hullMultline)
1777 ? (nrows() - 1 == cur.row())
1778 : display() != Inline;
1779 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1780 status.setEnabled(enable);
1781 status.setOnOff(enable && numbered(r));
1785 case LFUN_LABEL_INSERT:
1786 status.setEnabled(type_ != hullSimple);
1789 case LFUN_LABEL_COPY_AS_REFERENCE: {
1790 bool enabled = false;
1792 if (cmd.argument().empty() && &cur.inset() == this) {
1793 // if there is no argument and we're inside math, we retrieve
1794 // the row number from the cursor position.
1795 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1796 enabled = numberedType() && label_[row] && numbered(row);
1798 // if there is an argument, find the corresponding label, else
1799 // check whether there is at least one label.
1800 for (row_type row = 0; row != nrows(); ++row) {
1801 if (numbered(row) && label_[row] &&
1802 (cmd.argument().empty() || label(row) == cmd.argument())) {
1808 status.setEnabled(enabled);
1812 case LFUN_INSET_INSERT:
1813 if (cmd.getArg(0) == "label") {
1814 status.setEnabled(type_ != hullSimple);
1817 return InsetMathGrid::getStatus(cur, cmd, status);
1819 case LFUN_INSET_MODIFY: {
1820 istringstream is(to_utf8(cmd.argument()));
1824 return InsetMathGrid::getStatus(cur, cmd, status);
1827 && (s == "append-row"
1828 || s == "delete-row"
1829 || s == "copy-row")) {
1830 status.message(bformat(
1831 from_utf8(N_("Can't change number of rows in '%1$s'")),
1833 status.setEnabled(false);
1837 && (s == "append-column"
1838 || s == "delete-column"
1839 || s == "copy-column")) {
1840 status.message(bformat(
1841 from_utf8(N_("Can't change number of columns in '%1$s'")),
1843 status.setEnabled(false);
1846 if ((type_ == hullSimple
1847 || type_ == hullEquation
1848 || type_ == hullNone) &&
1849 (s == "add-hline-above" || s == "add-hline-below")) {
1850 status.message(bformat(
1851 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1853 status.setEnabled(false);
1856 if (s == "add-vline-left" || s == "add-vline-right") {
1857 status.message(bformat(
1858 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1860 status.setEnabled(false);
1863 if (s == "valign-top" || s == "valign-middle"
1864 || s == "valign-bottom" || s == "align-left"
1865 || s == "align-center" || s == "align-right") {
1866 status.setEnabled(false);
1869 return InsetMathGrid::getStatus(cur, cmd, status);
1873 return InsetMathGrid::getStatus(cur, cmd, status);
1876 // This cannot really happen, but inserted to shut-up gcc
1877 return InsetMathGrid::getStatus(cur, cmd, status);
1881 /////////////////////////////////////////////////////////////////////
1885 // simply scrap this function if you want
1886 void InsetMathHull::mutateToText()
1889 // translate to latex
1891 latex(os, false, false);
1892 string str = os.str();
1895 Text * lt = view_->cursor().innerText();
1896 string::const_iterator cit = str.begin();
1897 string::const_iterator end = str.end();
1898 for (; cit != end; ++cit)
1899 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1902 //dispatch(LFUN_ESCAPE);
1907 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1908 docstring const & font)
1910 // this whole function is a hack and won't work for incremental font
1913 if (cur.inset().asInsetMath()->name() == font)
1914 cur.handleFont(to_utf8(font));
1916 cur.handleNest(createInsetMath(font, cur.buffer()));
1922 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1927 font.fromString(to_utf8(arg), b);
1928 if (font.fontInfo().color() != Color_inherit) {
1929 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1930 cur.handleNest(at, 0);
1935 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1938 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1939 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1940 enter_front ? idxFirst(cur) : idxLast(cur);
1941 // The inset formula dimension is not necessarily the same as the
1942 // one of the instant preview image, so we have to indicate to the
1943 // BufferView that a metrics update is needed.
1944 cur.screenUpdateFlags(Update::Force);
1948 void InsetMathHull::revealCodes(Cursor & cur) const
1950 if (!cur.inMathed())
1952 odocstringstream os;
1954 cur.message(os.str());
1956 // write something to the minibuffer
1957 // translate to latex
1961 string str = os.str();
1963 string::size_type pos = 0;
1965 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1968 else if (*it == '\0') {
1970 pos = it - str.begin();
1976 res = res.substr(pos - 30);
1977 if (res.size() > 60)
1978 res = res.substr(0, 60);
1984 /////////////////////////////////////////////////////////////////////
1988 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1991 // FIXME: completely broken
1992 static InsetMathHull * lastformula = 0;
1993 static CursorBase current = DocIterator(ibegin(nucleus()));
1995 static string laststr;
1997 if (lastformula != this || laststr != str) {
1998 //lyxerr << "reset lastformula to " << this << endl;
2001 current = ibegin(nucleus());
2003 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2007 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2009 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2010 CursorSlice & top = it.back();
2011 MathData const & a = top.asInsetMath()->cell(top.idx_);
2012 if (a.matchpart(ar, top.pos_)) {
2013 bv->cursor().setSelection(it, ar.size());
2015 top.pos_ += ar.size();
2021 //lyxerr << "not found!" << endl;
2028 void InsetMathHull::write(ostream & os) const
2030 odocstringstream oss;
2031 TexRow texrow(false);
2032 otexrowstream ots(oss,texrow);
2033 WriteStream wi(ots, false, false, WriteStream::wsDefault);
2036 os << to_utf8(oss.str());
2040 void InsetMathHull::read(Lexer & lex)
2043 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2044 operator=(*at->asHullInset());
2048 bool InsetMathHull::readQuiet(Lexer & lex)
2051 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2053 operator=(*at->asHullInset());
2058 int InsetMathHull::plaintext(odocstringstream & os,
2059 OutputParams const & op, size_t max_length) const
2061 // disables ASCII-art for export of equations. See #2275.
2062 if (0 && display()) {
2066 TextPainter tpain(dim.width(), dim.height());
2067 drawT(tpain, 0, dim.ascent());
2069 // reset metrics cache to "real" values
2071 return tpain.textheight();
2074 odocstringstream oss;
2075 TexRow texrow(false);
2076 otexrowstream ots(oss,texrow);
2077 Encoding const * const enc = encodings.fromLyXName("utf8");
2078 WriteStream wi(ots, false, true, WriteStream::wsDefault, enc);
2081 if (type_ == hullRegexp)
2084 for (row_type r = 0; r < nrows(); ++r) {
2085 for (col_type c = 0; c < ncols(); ++c)
2086 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2087 // if it's for the TOC, we write just the first line
2088 // and do not include the newline.
2089 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2091 if (r < nrows() - 1)
2095 docstring const str = oss.str();
2101 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
2106 if (getType() == hullSimple)
2107 name = from_ascii("inlineequation");
2109 name = from_ascii("informalequation");
2111 docstring bname = name;
2112 if (!label(0).empty())
2113 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
2115 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
2117 odocstringstream ls;
2119 otexstream ols(ls, texrow);
2120 if (runparams.flavor == OutputParams::XML) {
2121 ms << MTag("alt role='tex' ");
2122 // Workaround for db2latex: db2latex always includes equations with
2123 // \ensuremath{} or \begin{display}\end{display}
2124 // so we strip LyX' math environment
2125 WriteStream wi(ols, false, false, WriteStream::wsDefault, runparams.encoding);
2126 InsetMathGrid::write(wi);
2127 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2132 InsetMathGrid::mathmlize(ms);
2135 ms << MTag("alt role='tex'");
2136 latex(ols, runparams);
2137 res = texrow.rows();
2138 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2142 ms << from_ascii("<graphic fileref=\"eqn/");
2143 if (!label(0).empty())
2144 ms << sgml::cleanID(buffer(), runparams, label(0));
2146 ms << sgml::uniqueID(from_ascii("anon"));
2148 if (runparams.flavor == OutputParams::XML)
2149 ms << from_ascii("\"/>");
2151 ms << from_ascii("\">");
2153 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2155 return ms.line() + res;
2159 bool InsetMathHull::haveNumbers() const
2161 bool havenumbers = false;
2162 // inline formulas are never numbered (bug 7351 part 3)
2163 if (getType() == hullSimple)
2165 for (size_t i = 0; i != numbered_.size(); ++i) {
2176 // We need to do something about alignment here.
2178 // This duplicates code from InsetMathGrid, but
2179 // we need access here to number information,
2180 // and we simply do not have that in InsetMathGrid.
2181 void InsetMathHull::htmlize(HtmlStream & os) const
2183 bool const havenumbers = haveNumbers();
2184 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2187 os << cell(index(0, 0));
2191 os << MTag("table", "class='mathtable'");
2192 for (row_type row = 0; row < nrows(); ++row) {
2194 for (col_type col = 0; col < ncols(); ++col) {
2196 os << cell(index(row, col));
2201 docstring const & num = numbers_[row];
2203 os << '(' << num << ')';
2208 os << ETag("table");
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::mathmlize(MathStream & os) const
2217 bool const havenumbers = haveNumbers();
2218 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2221 os << MTag("mtable");
2222 char const * const celltag = havetable ? "mtd" : "mrow";
2223 // FIXME There does not seem to be wide support at the moment
2224 // for mlabeledtr, so we have to use just mtr for now.
2225 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2226 char const * const rowtag = "mtr";
2227 for (row_type row = 0; row < nrows(); ++row) {
2230 for (col_type col = 0; col < ncols(); ++col) {
2232 << cell(index(row, col))
2238 docstring const & num = numbers_[row];
2240 os << '(' << num << ')';
2247 os << ETag("mtable");
2251 void InsetMathHull::mathAsLatex(WriteStream & os) const
2253 MathEnsurer ensurer(os, false);
2254 bool havenumbers = haveNumbers();
2255 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2258 os << cell(index(0, 0));
2262 os << "<table class='mathtable'>";
2263 for (row_type row = 0; row < nrows(); ++row) {
2265 for (col_type col = 0; col < ncols(); ++col) {
2266 os << "<td class='math'>";
2267 os << cell(index(row, col));
2272 docstring const & num = numbers_[row];
2274 os << '(' << num << ')';
2283 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2285 BufferParams::MathOutput const mathtype =
2286 buffer().masterBuffer()->params().html_math_output;
2288 bool success = false;
2290 // we output all the labels just at the beginning of the equation.
2291 // this should be fine.
2292 for (size_t i = 0; i != label_.size(); ++i) {
2293 InsetLabel const * const il = label_[i];
2299 // FIXME Eventually we would like to do this inset by inset.
2300 if (mathtype == BufferParams::MathML) {
2301 odocstringstream os;
2306 } catch (MathExportException const &) {}
2308 if (getType() == hullSimple)
2309 xs << html::StartTag("math",
2310 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2312 xs << html::StartTag("math",
2313 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2314 xs << XHTMLStream::ESCAPE_NONE
2316 << html::EndTag("math");
2318 } else if (mathtype == BufferParams::HTML) {
2319 odocstringstream os;
2324 } catch (MathExportException const &) {}
2326 string const tag = (getType() == hullSimple) ? "span" : "div";
2327 xs << html::StartTag(tag, "class='formula'", true)
2328 << XHTMLStream::ESCAPE_NONE
2330 << html::EndTag(tag);
2334 // what we actually want is this:
2336 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2338 // || mathtype == BufferParams::Images
2340 // but what follows is equivalent, since we'll enter only if either (a) we
2341 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2342 // aren't doing LaTeX, in which case we are doing Images.
2343 if (!success && mathtype != BufferParams::LaTeX) {
2344 graphics::PreviewImage const * pimage = 0;
2346 loadPreview(docit_);
2347 pimage = preview_->getPreviewImage(buffer());
2348 // FIXME Do we always have png?
2351 if (pimage || op.dryrun) {
2352 string const filename = pimage ? pimage->filename().onlyFileName()
2353 : "previewimage.png";
2355 // if we are not in the master buffer, then we need to see that the
2356 // generated image is copied there; otherwise, preview fails.
2357 Buffer const * mbuf = buffer().masterBuffer();
2358 if (mbuf != &buffer()) {
2359 string mbtmp = mbuf->temppath();
2360 FileName const mbufimg(support::addName(mbtmp, filename));
2361 pimage->filename().copyTo(mbufimg);
2363 // add the file to the list of files to be exported
2364 op.exportdata->addExternalFile("xhtml", pimage->filename());
2367 string const tag = (getType() == hullSimple) ? "span" : "div";
2369 << html::StartTag(tag)
2370 << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2371 << html::EndTag(tag)
2377 // so we'll pass this test if we've failed everything else, or
2378 // if mathtype was LaTeX, since we won't have entered any of the
2380 if (!success /* || mathtype != BufferParams::LaTeX */) {
2381 // Unfortunately, we cannot use latexString() because we do not want
2382 // $...$ or whatever.
2383 odocstringstream ls;
2384 TexRow texrow(false);
2385 otexrowstream ots(ls,texrow);
2386 WriteStream wi(ots, false, true, WriteStream::wsPreview);
2387 ModeSpecifier specifier(wi, MATH_MODE);
2389 docstring const latex = ls.str();
2391 // class='math' allows for use of jsMath
2392 // http://www.math.union.edu/~dpvc/jsMath/
2394 // probably should allow for some kind of customization here
2395 string const tag = (getType() == hullSimple) ? "span" : "div";
2396 xs << html::StartTag(tag, "class='math'")
2398 << html::EndTag(tag)
2405 void InsetMathHull::toString(odocstream & os) const
2407 odocstringstream ods;
2408 plaintext(ods, OutputParams(0));
2413 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2415 odocstringstream ods;
2418 // FIXME: this results in spilling TeX into the LyXHTML output since the
2419 // outliner is used to generate the LyXHTML list of figures/etc.
2425 string InsetMathHull::contextMenuName() const
2427 return "context-math";
2431 void InsetMathHull::recordLocation(DocIterator const & di)