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 "output_xhtml.h"
41 #include "Paragraph.h"
42 #include "ParIterator.h"
44 #include "TextClass.h"
45 #include "TextPainter.h"
46 #include "TocBackend.h"
48 #include "insets/InsetLabel.h"
49 #include "insets/InsetRef.h"
50 #include "insets/RenderPreview.h"
52 #include "graphics/GraphicsImage.h"
53 #include "graphics/PreviewImage.h"
54 #include "graphics/PreviewLoader.h"
56 #include "frontends/alert.h"
57 #include "frontends/Painter.h"
59 #include "support/convert.h"
60 #include "support/lassert.h"
61 #include "support/debug.h"
62 #include "support/filetools.h"
63 #include "support/gettext.h"
64 #include "support/lstrings.h"
69 using namespace lyx::support;
73 using cap::grabAndEraseSelection;
74 using cap::reduceSelectionToOneCell;
78 int getCols(HullType type)
95 // returns position of first relation operator in the array
96 // used for "intelligent splitting"
97 size_t firstRelOp(MathData const & ar)
99 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
100 if ((*it)->isRelOp())
101 return it - ar.begin();
106 char const * star(bool numbered)
108 return numbered ? "" : "*";
112 } // end anon namespace
115 HullType hullType(docstring const & s)
117 if (s == "none") return hullNone;
118 if (s == "simple") return hullSimple;
119 if (s == "equation") return hullEquation;
120 if (s == "eqnarray") return hullEqnArray;
121 if (s == "align") return hullAlign;
122 if (s == "alignat") return hullAlignAt;
123 if (s == "xalignat") return hullXAlignAt;
124 if (s == "xxalignat") return hullXXAlignAt;
125 if (s == "multline") return hullMultline;
126 if (s == "gather") return hullGather;
127 if (s == "flalign") return hullFlAlign;
128 if (s == "regexp") return hullRegexp;
129 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
134 docstring hullName(HullType type)
137 case hullNone: return from_ascii("none");
138 case hullSimple: return from_ascii("simple");
139 case hullEquation: return from_ascii("equation");
140 case hullEqnArray: return from_ascii("eqnarray");
141 case hullAlign: return from_ascii("align");
142 case hullAlignAt: return from_ascii("alignat");
143 case hullXAlignAt: return from_ascii("xalignat");
144 case hullXXAlignAt: return from_ascii("xxalignat");
145 case hullMultline: return from_ascii("multline");
146 case hullGather: return from_ascii("gather");
147 case hullFlAlign: return from_ascii("flalign");
148 case hullRegexp: return from_ascii("regexp");
150 lyxerr << "unknown hull type '" << type << "'" << endl;
151 return from_ascii("none");
155 static InsetLabel * dummy_pointer = 0;
157 InsetMathHull::InsetMathHull(Buffer * buf)
158 : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, NUMBER),
159 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
160 preview_(new RenderPreview(this)), use_preview_(false)
162 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
163 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
164 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
165 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
172 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
173 : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, NUMBER),
174 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
175 preview_(new RenderPreview(this)), use_preview_(false)
183 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
189 InsetMathHull::~InsetMathHull()
191 for (size_t i = 0; i < label_.size(); ++i)
196 Inset * InsetMathHull::clone() const
198 return new InsetMathHull(*this);
202 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
206 InsetMathGrid::operator=(other);
208 numbered_ = other.numbered_;
209 numbers_ = other.numbers_;
210 buffer_ = other.buffer_;
211 for (size_t i = 0; i < label_.size(); ++i)
213 label_ = other.label_;
214 for (size_t i = 0; i != label_.size(); ++i) {
216 label_[i] = new InsetLabel(*label_[i]);
218 preview_.reset(new RenderPreview(*other.preview_, this));
224 void InsetMathHull::setBuffer(Buffer & buffer)
226 InsetMathGrid::setBuffer(buffer);
228 for (size_t i = 0; i != label_.size(); ++i) {
230 label_[i]->setBuffer(buffer);
235 // FIXME This should really be controlled by the TOC level, or
236 // something of the sort.
238 const char * counters_to_save[] = {"section", "chapter"};
239 unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
243 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
246 //FIXME: buffer_ should be set at creation for this inset! Problem is
247 // This inset is created at too many places (see Parser::parse1() in
252 // if any of the equations are numbered, then we want to save the values
253 // of some of the counters.
255 BufferParams const & bp = buffer_->params();
256 string const & lang = it->getParLanguage(bp)->code();
258 buffer_->masterBuffer()->params().documentClass().counters();
260 // right now, we only need to do this at export time
261 if (utype == OutputUpdate) {
262 for (size_t i = 0; i < numcnts; ++i) {
263 docstring const cnt = from_ascii(counters_to_save[i]);
264 if (cnts.hasCounter(cnt))
265 counter_map[cnt] = cnts.value(cnt);
269 // this has to be done separately
270 docstring const eqstr = from_ascii("equation");
271 if (cnts.hasCounter(eqstr)) {
272 if (utype == OutputUpdate)
273 counter_map[eqstr] = cnts.value(eqstr);
274 for (size_t i = 0; i != label_.size(); ++i) {
276 cnts.step(eqstr, utype);
277 numbers_[i] = cnts.theCounter(eqstr, lang);
279 numbers_[i] = empty_docstring();
285 for (size_t i = 0; i != label_.size(); ++i) {
287 label_[i]->updateBuffer(it, utype);
290 InsetMathGrid::updateBuffer(it, utype);
294 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active) const
297 //FIXME: buffer_ should be set at creation for this inset! Problem is
298 // This inset is created at too many places (see Parser::parse1() in
303 Toc & toc = buffer().tocBackend().toc("equation");
305 for (row_type row = 0; row != nrows(); ++row) {
309 label_[row]->addToToc(pit, output_active);
310 toc.push_back(TocItem(pit, 0, nicelabel(row), output_active));
315 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
321 return InsetMathNest::editXY(cur, x, y);
325 InsetMath::mode_type InsetMathHull::currentMode() const
327 if (type_ == hullNone)
328 return UNDECIDED_MODE;
329 // definitely math mode ...
334 bool InsetMathHull::idxFirst(Cursor & cur) const
342 bool InsetMathHull::idxLast(Cursor & cur) const
344 cur.idx() = nargs() - 1;
345 cur.pos() = cur.lastpos();
350 char InsetMathHull::defaultColAlign(col_type col)
352 if (type_ == hullEqnArray)
354 if (type_ == hullMultline)
356 if (type_ == hullGather)
358 if (type_ >= hullAlign)
359 return "rl"[col & 1];
364 char InsetMathHull::displayColAlign(idx_type idx) const
366 if (type_ == hullMultline) {
367 row_type const r = row(idx);
370 if (r == nrows() - 1)
373 return InsetMathGrid::displayColAlign(idx);
377 int InsetMathHull::defaultColSpace(col_type col)
379 if (type_ == hullAlign || type_ == hullAlignAt)
381 if (type_ == hullXAlignAt)
382 return (col & 1) ? 20 : 0;
383 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
384 return (col & 1) ? 40 : 0;
389 docstring InsetMathHull::standardFont() const
394 font_name = from_ascii("texttt");
397 font_name = from_ascii("lyxnochange");
400 font_name = from_ascii("mathnormal");
406 ColorCode InsetMathHull::standardColor() const
412 color = Color_foreground;
421 bool InsetMathHull::previewState(const BufferView *const bv) const
423 if (!editing(bv) && RenderPreview::previewMath()
424 && type_ != hullRegexp)
426 graphics::PreviewImage const * pimage =
427 preview_->getPreviewImage(bv->buffer());
428 return pimage && pimage->image();
435 static const int ERROR_FRAME_WIDTH = 2;
438 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
440 if (previewState(mi.base.bv)) {
441 preview_->metrics(mi, dim);
442 if (previewTooSmall(dim)) {
443 // preview image is too small
444 dim.wid += 2 * ERROR_FRAME_WIDTH;
445 dim.asc += 2 * ERROR_FRAME_WIDTH;
447 // insert a one pixel gap in front of the formula
450 dim.des += displayMargin();
452 // Cache the inset dimension.
453 setDimCache(mi, dim);
457 FontSetChanger dummy1(mi.base, standardFont());
458 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
460 // let the cells adjust themselves
461 InsetMathGrid::metrics(mi, dim);
464 dim.asc += displayMargin();
465 dim.des += displayMargin();
468 if (numberedType()) {
469 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
471 for (row_type row = 0; row < nrows(); ++row)
472 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
478 if (type_ == hullRegexp)
480 // make it at least as high as the current font
483 math_font_max_dim(mi.base.font, asc, des);
484 dim.asc = max(dim.asc, asc);
485 dim.des = max(dim.des, des);
486 // Cache the inset dimension.
487 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
488 setDimCache(mi, dim);
492 bool InsetMathHull::previewTooSmall(Dimension const & dim) const
494 return dim.width() <= 10 && dim.height() <= 10;
498 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
500 BufferView const * const bv = pi.base.bv;
501 if (previewState(bv)) {
502 Dimension const dim = dimension(*pi.base.bv);
503 if (previewTooSmall(dim))
505 return graphics::PreviewLoader::backgroundColor();
511 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
513 Dimension const dim = dimension(*pi.base.bv);
514 if (previewTooSmall(dim)) {
515 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
516 dim.wid, dim.asc + dim.des, backgroundColor(pi));
519 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
520 dim.asc + dim.des - 1, pi.backgroundColor(this));
524 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
526 BufferView const * const bv = pi.base.bv;
527 use_preview_ = previewState(bv);
529 if (type_ == hullRegexp) {
530 Dimension const dim = dimension(*bv);
531 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
532 dim.width() - 2, dim.height() - 2, Color_regexpframe);
536 Dimension const dim = dimension(*bv);
537 if (previewTooSmall(dim)) {
538 // we have an extra frame
539 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
541 // one pixel gap in front
542 preview_->draw(pi, x + 1, y);
544 setPosCache(pi, x, y);
548 ColorCode color = pi.selected && lyxrc.use_system_colors
549 ? Color_selectiontext : standardColor();
550 bool const really_change_color = pi.base.font.color() == Color_none;
551 ColorChanger dummy0(pi.base.font, color, really_change_color);
552 FontSetChanger dummy1(pi.base, standardFont());
553 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
555 InsetMathGrid::draw(pi, x + 1, y);
557 if (numberedType()) {
558 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
559 for (row_type row = 0; row < nrows(); ++row) {
560 int const yy = y + rowinfo_[row].offset_;
561 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
562 docstring const nl = nicelabel(row);
566 setPosCache(pi, x, y);
570 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
573 InsetMathGrid::metricsT(mi, dim);
576 WriteStream wi(os, false, true, WriteStream::wsDefault);
578 dim.wid = os.str().size();
585 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
588 InsetMathGrid::drawT(pain, x, y);
591 WriteStream wi(os, false, true, WriteStream::wsDefault);
593 pain.draw(x, y, os.str().c_str());
598 static docstring latexString(InsetMathHull const & inset)
601 // This has to be static, because a preview snippet or a math
602 // macro containing math in text mode (such as $\text{$\phi$}$ or
603 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
604 // first time as a whole, and the second time only the inner math.
605 // In this last case inset.buffer() would be invalid.
606 static Encoding const * encoding = 0;
607 if (inset.isBufferValid())
608 encoding = &(inset.buffer().params().encoding());
609 WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
615 void InsetMathHull::initUnicodeMath() const
617 // Trigger classification of the unicode symbols in this inset
618 docstring const dummy = latexString(*this);
622 void InsetMathHull::addPreview(DocIterator const & inset_pos,
623 graphics::PreviewLoader & /*ploader*/) const
625 if (RenderPreview::previewMath()) {
626 preparePreview(inset_pos);
631 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
632 MacroNameSet & macros, MacroNameSet & defs) const
634 MacroNameSet::iterator const end = macros.end();
636 for (size_t i = 0; i < md.size(); ++i) {
637 MathMacro const * mi = md[i].nucleus()->asMacro();
638 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
639 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
640 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
641 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
643 // Make sure this is a macro defined in the document
644 // (as we also spot the macros in the symbols file)
645 // or that we have not already accounted for it.
646 docstring const name = mi->name();
647 if (macros.find(name) == end)
650 // Look for macros in the arguments of this macro.
651 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
652 usedMacros(mi->cell(idx), pos, macros, defs);
653 // Look for macros in the definition of this macro.
654 MathData ar(pos.buffer());
655 MacroData const * data =
656 pos.buffer()->getMacro(name, pos, true);
658 odocstringstream macro_def;
659 data->write(macro_def, true);
661 defs.insert(macro_def.str());
662 asArray(data->definition(), ar);
664 usedMacros(ar, pos, macros, defs);
666 if (!si->nuc().empty())
667 usedMacros(si->nuc(), pos, macros, defs);
669 usedMacros(si->down(), pos, macros, defs);
671 usedMacros(si->up(), pos, macros, defs);
672 } else if (fi || gi) {
673 idx_type nidx = fi ? fi->nargs() : gi->nargs();
674 for (idx_type idx = 0; idx < nidx; ++idx)
675 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
678 usedMacros(ni->cell(0), pos, macros, defs);
684 void InsetMathHull::preparePreview(DocIterator const & pos,
685 bool forexport) const
687 // there is no need to do all the macro stuff if we're not
688 // actually going to generate the preview.
689 if (!RenderPreview::previewMath() && !forexport)
692 Buffer const * buffer = pos.buffer();
694 // collect macros at this position
696 buffer->listMacroNames(macros);
698 // collect definitions only for the macros used in this inset
700 for (idx_type idx = 0; idx < nargs(); ++idx)
701 usedMacros(cell(idx), pos, macros, defs);
703 MacroNameSet::iterator it = defs.begin();
704 MacroNameSet::iterator end = defs.end();
705 docstring macro_preamble;
706 for (; it != end; ++it)
707 macro_preamble.append(*it);
710 if (forexport && haveNumbers()) {
711 docstring eqstr = from_ascii("equation");
712 CounterMap::const_iterator it = counter_map.find(eqstr);
713 if (it != counter_map.end()) {
714 int num = it->second;
716 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
717 '{' + convert<docstring>(num) + '}' + '\n';
719 for (size_t i = 0; i != numcnts; ++i) {
720 docstring cnt = from_ascii(counters_to_save[i]);
721 it = counter_map.find(cnt);
722 if (it == counter_map.end())
724 int num = it->second;
726 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
727 '{' + convert<docstring>(num) + '}';
730 docstring const snippet = macro_preamble + setcnt + latexString(*this);
731 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
732 preview_->addPreview(snippet, *buffer, forexport);
736 void InsetMathHull::reloadPreview(DocIterator const & pos) const
739 preview_->startLoading(*pos.buffer());
743 void InsetMathHull::loadPreview(DocIterator const & pos) const
745 bool const forexport = true;
746 preparePreview(pos, forexport);
747 preview_->startLoading(*pos.buffer(), forexport);
751 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
753 if (RenderPreview::previewMath()) {
755 cur.screenUpdateFlags(Update::Force);
761 docstring InsetMathHull::label(row_type row) const
763 LASSERT(row < nrows(), return docstring());
764 if (InsetLabel * il = label_[row])
765 return il->screenLabel();
770 void InsetMathHull::label(row_type row, docstring const & label)
772 //lyxerr << "setting label '" << label << "' for row " << row << endl;
776 label_[row] = dummy_pointer;
779 label_[row]->updateLabelAndRefs(label);
781 label_[row]->setParam("name", label);
785 InsetCommandParams p(LABEL_CODE);
787 label_[row] = new InsetLabel(buffer_, p);
789 label_[row]->setBuffer(buffer());
793 void InsetMathHull::numbered(row_type row, Numbered num)
795 numbered_[row] = num;
796 if (!numbered(row) && label_[row]) {
803 bool InsetMathHull::numbered(row_type row) const
805 return numbered_[row] == NUMBER;
809 bool InsetMathHull::ams() const
827 for (size_t row = 0; row < numbered_.size(); ++row)
828 if (numbered_[row] == NOTAG)
834 Inset::DisplayType InsetMathHull::display() const
836 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
841 bool InsetMathHull::numberedType() const
843 if (type_ == hullNone)
845 if (type_ == hullSimple)
847 if (type_ == hullXXAlignAt)
849 if (type_ == hullRegexp)
851 for (row_type row = 0; row < nrows(); ++row)
858 void InsetMathHull::validate(LaTeXFeatures & features) const
860 if (features.runparams().isLaTeX()) {
862 features.require("amsmath");
864 if (type_ == hullRegexp) {
865 features.require("color");
866 string frcol = lcolor.getLaTeXName(Color_regexpframe);
867 string bgcol = "white";
868 features.addPreambleSnippet(
869 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
870 + frcol + string("}{")
871 + bgcol + string("}{\\ensuremath{\\mathtt{#1}}}}"));
872 features.addPreambleSnippet(
873 string("\\newcommand{\\endregexp}{}"));
876 // Validation is necessary only if not using AMS math.
877 // To be safe, we will always run mathedvalidate.
878 //if (features.amsstyle)
881 //features.binom = true;
882 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
883 // it would be better to do this elsewhere, but we can't validate in
884 // InsetMathMatrix and we have no way, outside MathExtern, to know if
885 // we even have any matrices.
886 features.addCSSSnippet(
887 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
888 "table.matrix td{padding: 0.25px;}\n"
889 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
890 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
892 InsetMathGrid::validate(features);
896 void InsetMathHull::header_write(WriteStream & os) const
898 bool n = numberedType();
912 os << "\n\\begin{equation" << star(n) << "}\n";
922 os << "\n\\begin{" << hullName(type_) << star(n) << "}\n";
927 os << "\n\\begin{" << hullName(type_) << star(n) << '}'
928 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
932 os << "\n\\begin{" << hullName(type_) << '}'
933 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
941 os << "\n\\begin{unknown" << star(n) << "}\n";
947 void InsetMathHull::footer_write(WriteStream & os) const
949 bool n = numberedType();
962 os << "\n\\end{equation" << star(n) << "}\n";
974 os << "\n\\end{" << hullName(type_) << star(n) << "}\n";
978 os << "\n\\end{" << hullName(type_) << "}\n";
982 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
983 os << "\\endregexp{}}";
987 os << "\n\\end{unknown" << star(n) << "}\n";
993 bool InsetMathHull::rowChangeOK() const
996 type_ == hullEqnArray || type_ == hullAlign ||
997 type_ == hullFlAlign || type_ == hullAlignAt ||
998 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
999 type_ == hullGather || type_ == hullMultline;
1003 bool InsetMathHull::colChangeOK() const
1006 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1007 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1011 void InsetMathHull::addRow(row_type row)
1016 bool numbered = numberedType();
1017 // Move the number and raw pointer, do not call label() (bug 7511)
1018 InsetLabel * label = dummy_pointer;
1019 docstring number = empty_docstring();
1020 if (type_ == hullMultline) {
1021 if (row + 1 == nrows()) {
1022 numbered_[row] = NONUMBER;
1023 swap(label, label_[row]);
1024 swap(number, numbers_[row]);
1029 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1030 numbers_.insert(numbers_.begin() + row + 1, number);
1031 label_.insert(label_.begin() + row + 1, label);
1032 InsetMathGrid::addRow(row);
1036 void InsetMathHull::swapRow(row_type row)
1040 if (row + 1 == nrows())
1042 swap(numbered_[row], numbered_[row + 1]);
1043 swap(numbers_[row], numbers_[row + 1]);
1044 swap(label_[row], label_[row + 1]);
1045 InsetMathGrid::swapRow(row);
1049 void InsetMathHull::delRow(row_type row)
1051 if (nrows() <= 1 || !rowChangeOK())
1053 if (row + 1 == nrows() && type_ == hullMultline) {
1054 swap(numbered_[row - 1], numbered_[row]);
1055 swap(numbers_[row - 1], numbers_[row]);
1056 swap(label_[row - 1], label_[row]);
1057 InsetMathGrid::delRow(row);
1060 InsetMathGrid::delRow(row);
1061 // The last dummy row has no number info nor a label.
1062 // Test nrows() + 1 because we have already erased the row.
1063 if (row == nrows() + 1)
1065 numbered_.erase(numbered_.begin() + row);
1066 numbers_.erase(numbers_.begin() + row);
1068 label_.erase(label_.begin() + row);
1072 void InsetMathHull::addCol(col_type col)
1076 InsetMathGrid::addCol(col);
1080 void InsetMathHull::delCol(col_type col)
1082 if (ncols() <= 1 || !colChangeOK())
1084 InsetMathGrid::delCol(col);
1088 docstring InsetMathHull::nicelabel(row_type row) const
1092 docstring const & val = numbers_[row];
1094 return '(' + val + ')';
1095 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1099 void InsetMathHull::glueall(HullType type)
1102 for (idx_type i = 0; i < nargs(); ++i)
1104 InsetLabel * label = 0;
1105 if (type == hullEquation) {
1106 // preserve first non-empty label
1107 for (row_type row = 0; row < nrows(); ++row) {
1109 label = label_[row];
1115 *this = InsetMathHull(buffer_, hullSimple);
1122 void InsetMathHull::splitTo2Cols()
1124 LASSERT(ncols() == 1, return);
1125 InsetMathGrid::addCol(1);
1126 for (row_type row = 0; row < nrows(); ++row) {
1127 idx_type const i = 2 * row;
1128 pos_type pos = firstRelOp(cell(i));
1129 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1130 cell(i).erase(pos, cell(i).size());
1135 void InsetMathHull::splitTo3Cols()
1137 LASSERT(ncols() < 3, return);
1140 InsetMathGrid::addCol(2);
1141 for (row_type row = 0; row < nrows(); ++row) {
1142 idx_type const i = 3 * row + 1;
1143 if (!cell(i).empty()) {
1144 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1145 cell(i).erase(1, cell(i).size());
1151 void InsetMathHull::changeCols(col_type cols)
1153 if (ncols() == cols)
1155 else if (ncols() < cols) {
1161 while (ncols() < cols)
1162 InsetMathGrid::addCol(ncols());
1168 for (row_type row = 0; row < nrows(); ++row) {
1169 idx_type const i = row * ncols();
1170 for (col_type col = cols; col < ncols(); ++col) {
1171 cell(i + cols - 1).append(cell(i + col));
1175 while (ncols() > cols) {
1176 InsetMathGrid::delCol(ncols() - 1);
1181 HullType InsetMathHull::getType() const
1187 void InsetMathHull::setType(HullType type)
1194 void InsetMathHull::mutate(HullType newtype)
1196 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1198 // we try to move along the chain
1199 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1201 // +-------------------------------------+
1202 // we use eqnarray as intermediate type for mutations that are not
1203 // directly supported because it handles labels and numbering for
1206 if (newtype == type_) {
1210 else if (newtype < hullNone) {
1215 else if (type_ == hullNone) {
1216 setType(hullSimple);
1221 else if (type_ == hullSimple) {
1222 if (newtype == hullNone) {
1226 setType(hullEquation);
1227 numbered(0, label_[0] ? true : false);
1232 else if (type_ == hullEquation) {
1233 if (newtype < type_) {
1234 setType(hullSimple);
1237 } else if (newtype == hullEqnArray) {
1238 // split it "nicely" on the first relop
1240 setType(hullEqnArray);
1241 } else if (newtype == hullMultline || newtype == hullGather) {
1244 // split it "nicely"
1251 else if (type_ == hullEqnArray) {
1252 if (newtype < type_) {
1255 } else { // align & Co.
1262 else if (type_ == hullAlign || type_ == hullAlignAt ||
1263 type_ == hullXAlignAt || type_ == hullFlAlign) {
1264 if (newtype < hullAlign) {
1266 setType(hullEqnArray);
1268 } else if (newtype == hullGather || newtype == hullMultline) {
1271 } else if (newtype == hullXXAlignAt) {
1272 for (row_type row = 0; row < nrows(); ++row)
1273 numbered(row, false);
1280 else if (type_ == hullXXAlignAt) {
1281 for (row_type row = 0; row < nrows(); ++row)
1282 numbered(row, false);
1283 if (newtype < hullAlign) {
1285 setType(hullEqnArray);
1287 } else if (newtype == hullGather || newtype == hullMultline) {
1295 else if (type_ == hullMultline || type_ == hullGather) {
1296 if (newtype == hullGather || newtype == hullMultline)
1298 else if (newtype == hullAlign || newtype == hullFlAlign ||
1299 newtype == hullAlignAt || newtype == hullXAlignAt) {
1302 } else if (newtype == hullXXAlignAt) {
1304 for (row_type row = 0; row < nrows(); ++row)
1305 numbered(row, false);
1309 setType(hullEqnArray);
1315 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1316 << "' to '" << to_utf8(hullName(newtype))
1317 << "' not implemented" << endl;
1322 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1323 bool last_eoln) const
1326 if (numberedType()) {
1327 if (label_[row] && numbered(row)) {
1328 docstring const name =
1329 latex ? escape(label_[row]->getParam("name"))
1330 : label_[row]->getParam("name");
1331 res += "\\label{" + name + '}';
1333 if (type_ != hullMultline) {
1334 if (numbered_[row] == NONUMBER)
1335 res += "\\nonumber ";
1336 else if (numbered_[row] == NOTAG)
1340 // Never add \\ on the last empty line of eqnarray and friends
1342 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1346 void InsetMathHull::write(WriteStream & os) const
1348 ModeSpecifier specifier(os, MATH_MODE);
1350 InsetMathGrid::write(os);
1355 void InsetMathHull::normalize(NormalStream & os) const
1357 os << "[formula " << hullName(type_) << ' ';
1358 InsetMathGrid::normalize(os);
1363 void InsetMathHull::infoize(odocstream & os) const
1365 os << bformat(_("Type: %1$s"), hullName(type_));
1369 void InsetMathHull::check() const
1371 LATTEST(numbered_.size() == nrows());
1372 LATTEST(numbers_.size() == nrows());
1373 LATTEST(label_.size() == nrows());
1377 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1381 idocstringstream iss(func.argument());
1382 iss >> dlang >> extra;
1384 extra = from_ascii("noextra");
1385 string const lang = to_ascii(dlang);
1387 // replace selection with result of computation
1388 if (reduceSelectionToOneCell(cur)) {
1390 asArray(grabAndEraseSelection(cur), ar);
1391 lyxerr << "use selection: " << ar << endl;
1392 cur.insert(pipeThroughExtern(lang, extra, ar));
1396 // only inline, display or eqnarray math is allowed
1397 if (getType() > hullEqnArray) {
1398 frontend::Alert::warning(_("Bad math environment"),
1399 _("Computation cannot be performed for AMS "
1400 "math environments.\nChange the math "
1401 "formula type and try again."));
1406 eq.push_back(MathAtom(new InsetMathChar('=')));
1408 // go to first item in line
1409 cur.idx() -= cur.idx() % ncols();
1412 if (getType() == hullSimple) {
1413 size_type pos = cur.cell().find_last(eq);
1415 if (pos == cur.cell().size()) {
1417 lyxerr << "use whole cell: " << ar << endl;
1419 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1420 lyxerr << "use partial cell form pos: " << pos << endl;
1422 cur.cell().append(eq);
1423 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1424 cur.pos() = cur.lastpos();
1428 if (getType() == hullEquation) {
1429 lyxerr << "use equation inset" << endl;
1430 mutate(hullEqnArray);
1431 MathData & ar = cur.cell();
1432 lyxerr << "use cell: " << ar << endl;
1436 cur.cell() = pipeThroughExtern(lang, extra, ar);
1437 // move to end of line
1438 cur.pos() = cur.lastpos();
1443 lyxerr << "use eqnarray" << endl;
1444 cur.idx() += 2 - cur.idx() % ncols();
1446 MathData ar = cur.cell();
1447 lyxerr << "use cell: " << ar << endl;
1448 // FIXME: temporarily disabled
1454 cur.cell() = pipeThroughExtern(lang, extra, ar);
1455 cur.pos() = cur.lastpos();
1460 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1462 //lyxerr << "action: " << cmd.action() << endl;
1463 switch (cmd.action()) {
1465 case LFUN_FINISHED_BACKWARD:
1466 case LFUN_FINISHED_FORWARD:
1467 case LFUN_FINISHED_RIGHT:
1468 case LFUN_FINISHED_LEFT:
1469 //lyxerr << "action: " << cmd.action() << endl;
1470 InsetMathGrid::doDispatch(cur, cmd);
1473 case LFUN_PARAGRAPH_BREAK:
1474 // just swallow this
1477 case LFUN_NEWLINE_INSERT:
1478 // some magic for the common case
1479 if (type_ == hullSimple || type_ == hullEquation) {
1480 cur.recordUndoInset();
1482 cur.bv().buffer().params().use_package("amsmath") == BufferParams::package_on;
1483 mutate(align ? hullAlign : hullEqnArray);
1484 // mutate() may change labels and such.
1485 cur.forceBufferUpdate();
1486 cur.idx() = nrows() * ncols() - 1;
1487 cur.pos() = cur.lastpos();
1489 InsetMathGrid::doDispatch(cur, cmd);
1492 case LFUN_MATH_NUMBER_TOGGLE: {
1493 //lyxerr << "toggling all numbers" << endl;
1494 cur.recordUndoInset();
1495 bool old = numberedType();
1496 if (type_ == hullMultline)
1497 numbered(nrows() - 1, !old);
1499 for (row_type row = 0; row < nrows(); ++row)
1500 numbered(row, !old);
1502 cur.message(old ? _("No number") : _("Number"));
1503 cur.forceBufferUpdate();
1507 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1508 cur.recordUndoInset();
1509 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1510 bool old = numbered(r);
1511 cur.message(old ? _("No number") : _("Number"));
1513 cur.forceBufferUpdate();
1517 case LFUN_LABEL_INSERT: {
1518 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1519 docstring old_label = label(r);
1520 docstring const default_label = from_ascii("eq:");
1521 if (old_label.empty())
1522 old_label = default_label;
1524 InsetCommandParams p(LABEL_CODE);
1525 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1526 string const data = InsetCommand::params2string(p);
1528 if (cmd.argument().empty())
1529 cur.bv().showDialog("label", data);
1531 FuncRequest fr(LFUN_INSET_INSERT, data);
1537 case LFUN_LABEL_COPY_AS_REFERENCE: {
1539 if (cmd.argument().empty() && &cur.inset() == this)
1540 // if there is no argument and we're inside math, we retrieve
1541 // the row number from the cursor position.
1542 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1544 // if there is an argument, find the corresponding label, else
1545 // check whether there is at least one label.
1546 for (row = 0; row != nrows(); ++row)
1547 if (numbered(row) && label_[row]
1548 && (cmd.argument().empty() || label(row) == cmd.argument()))
1555 InsetCommandParams p(REF_CODE, "ref");
1556 p["reference"] = label(row);
1557 cap::clearSelection();
1558 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1562 case LFUN_WORD_DELETE_FORWARD:
1563 case LFUN_CHAR_DELETE_FORWARD:
1564 if (col(cur.idx()) + 1 == ncols()
1565 && cur.pos() == cur.lastpos()
1566 && !cur.selection()) {
1567 if (!label(row(cur.idx())).empty()) {
1568 cur.recordUndoInset();
1569 label(row(cur.idx()), docstring());
1570 } else if (numbered(row(cur.idx()))) {
1571 cur.recordUndoInset();
1572 numbered(row(cur.idx()), false);
1573 cur.forceBufferUpdate();
1575 InsetMathGrid::doDispatch(cur, cmd);
1579 InsetMathGrid::doDispatch(cur, cmd);
1584 case LFUN_INSET_INSERT: {
1585 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1586 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1587 string const name = cmd.getArg(0);
1588 if (name == "label") {
1589 InsetCommandParams p(LABEL_CODE);
1590 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1591 docstring str = p["name"];
1592 cur.recordUndoInset();
1593 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1597 docstring old = label(r);
1600 // The label will take care of the reference update.
1604 // Newly created inset so initialize it.
1605 label_[r]->initView();
1608 cur.forceBufferUpdate();
1611 InsetMathGrid::doDispatch(cur, cmd);
1615 case LFUN_MATH_EXTERN:
1616 cur.recordUndoInset();
1620 case LFUN_MATH_MUTATE: {
1621 cur.recordUndoInset();
1622 row_type row = cur.row();
1623 col_type col = cur.col();
1624 mutate(hullType(cmd.argument()));
1625 cur.idx() = row * ncols() + col;
1626 if (cur.idx() > cur.lastidx()) {
1627 cur.idx() = cur.lastidx();
1628 cur.pos() = cur.lastpos();
1630 if (cur.pos() > cur.lastpos())
1631 cur.pos() = cur.lastpos();
1633 cur.forceBufferUpdate();
1634 // FIXME: find some more clever handling of the selection,
1635 // i.e. preserve it.
1636 cur.clearSelection();
1637 //cur.dispatched(FINISHED);
1641 case LFUN_MATH_DISPLAY: {
1642 cur.recordUndoInset();
1643 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1645 cur.pos() = cur.lastpos();
1646 //cur.dispatched(FINISHED);
1651 InsetMathGrid::doDispatch(cur, cmd);
1657 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1658 FuncStatus & status) const
1660 switch (cmd.action()) {
1661 case LFUN_FINISHED_BACKWARD:
1662 case LFUN_FINISHED_FORWARD:
1663 case LFUN_FINISHED_RIGHT:
1664 case LFUN_FINISHED_LEFT:
1667 case LFUN_NEWLINE_INSERT:
1668 case LFUN_MATH_EXTERN:
1670 status.setEnabled(true);
1673 // we never allow this in math, and we want to bind enter
1674 // to another actions in command-alternatives
1675 case LFUN_PARAGRAPH_BREAK:
1676 status.setEnabled(false);
1678 case LFUN_MATH_MUTATE: {
1679 HullType const ht = hullType(cmd.argument());
1680 status.setOnOff(type_ == ht);
1681 status.setEnabled(true);
1683 if (ht != hullSimple) {
1684 Cursor tmpcur = cur;
1685 while (!tmpcur.empty()) {
1686 InsetCode code = tmpcur.inset().lyxCode();
1687 if (code == BOX_CODE) {
1689 } else if (code == TABULAR_CODE) {
1690 FuncRequest tmpcmd(LFUN_MATH_DISPLAY);
1691 if (tmpcur.getStatus(tmpcmd, status) && !status.enabled())
1699 case LFUN_MATH_DISPLAY: {
1701 if (cur.depth() > 1) {
1702 Inset const & in = cur[cur.depth()-2].inset();
1703 if (in.lyxCode() == SCRIPT_CODE)
1704 enable = display() != Inline;
1706 status.setEnabled(enable);
1707 status.setOnOff(display() != Inline);
1711 case LFUN_MATH_NUMBER_TOGGLE:
1712 // FIXME: what is the right test, this or the one of
1714 status.setEnabled(display() != Inline);
1715 status.setOnOff(numberedType());
1718 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1719 // FIXME: what is the right test, this or the one of
1721 bool const enable = (type_ == hullMultline)
1722 ? (nrows() - 1 == cur.row())
1723 : display() != Inline;
1724 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1725 status.setEnabled(enable);
1726 status.setOnOff(enable && numbered(r));
1730 case LFUN_LABEL_INSERT:
1731 status.setEnabled(type_ != hullSimple);
1734 case LFUN_LABEL_COPY_AS_REFERENCE: {
1735 bool enabled = false;
1737 if (cmd.argument().empty() && &cur.inset() == this) {
1738 // if there is no argument and we're inside math, we retrieve
1739 // the row number from the cursor position.
1740 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1741 enabled = numberedType() && label_[row] && numbered(row);
1743 // if there is an argument, find the corresponding label, else
1744 // check whether there is at least one label.
1745 for (row_type row = 0; row != nrows(); ++row) {
1746 if (numbered(row) && label_[row] &&
1747 (cmd.argument().empty() || label(row) == cmd.argument())) {
1753 status.setEnabled(enabled);
1757 case LFUN_INSET_INSERT:
1758 if (cmd.getArg(0) == "label") {
1759 status.setEnabled(type_ != hullSimple);
1762 return InsetMathGrid::getStatus(cur, cmd, status);
1764 case LFUN_INSET_MODIFY: {
1765 istringstream is(to_utf8(cmd.argument()));
1769 return InsetMathGrid::getStatus(cur, cmd, status);
1772 && (s == "append-row"
1773 || s == "delete-row"
1774 || s == "copy-row")) {
1775 status.message(bformat(
1776 from_utf8(N_("Can't change number of rows in '%1$s'")),
1778 status.setEnabled(false);
1782 && (s == "append-column"
1783 || s == "delete-column"
1784 || s == "copy-column")) {
1785 status.message(bformat(
1786 from_utf8(N_("Can't change number of columns in '%1$s'")),
1788 status.setEnabled(false);
1791 if ((type_ == hullSimple
1792 || type_ == hullEquation
1793 || type_ == hullNone) &&
1794 (s == "add-hline-above" || s == "add-hline-below")) {
1795 status.message(bformat(
1796 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1798 status.setEnabled(false);
1801 if (s == "add-vline-left" || s == "add-vline-right") {
1802 status.message(bformat(
1803 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1805 status.setEnabled(false);
1808 if (s == "valign-top" || s == "valign-middle"
1809 || s == "valign-bottom" || s == "align-left"
1810 || s == "align-center" || s == "align-right") {
1811 status.setEnabled(false);
1814 return InsetMathGrid::getStatus(cur, cmd, status);
1818 return InsetMathGrid::getStatus(cur, cmd, status);
1821 // This cannot really happen, but inserted to shut-up gcc
1822 return InsetMathGrid::getStatus(cur, cmd, status);
1826 /////////////////////////////////////////////////////////////////////
1830 // simply scrap this function if you want
1831 void InsetMathHull::mutateToText()
1834 // translate to latex
1836 latex(os, false, false);
1837 string str = os.str();
1840 Text * lt = view_->cursor().innerText();
1841 string::const_iterator cit = str.begin();
1842 string::const_iterator end = str.end();
1843 for (; cit != end; ++cit)
1844 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1847 //dispatch(LFUN_ESCAPE);
1852 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1853 docstring const & font)
1855 // this whole function is a hack and won't work for incremental font
1858 if (cur.inset().asInsetMath()->name() == font)
1859 cur.handleFont(to_utf8(font));
1861 cur.handleNest(createInsetMath(font, cur.buffer()));
1867 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1872 font.fromString(to_utf8(arg), b);
1873 if (font.fontInfo().color() != Color_inherit) {
1874 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1875 cur.handleNest(at, 0);
1880 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1883 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1884 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1885 enter_front ? idxFirst(cur) : idxLast(cur);
1886 // The inset formula dimension is not necessarily the same as the
1887 // one of the instant preview image, so we have to indicate to the
1888 // BufferView that a metrics update is needed.
1889 cur.screenUpdateFlags(Update::Force);
1893 void InsetMathHull::revealCodes(Cursor & cur) const
1895 if (!cur.inMathed())
1897 odocstringstream os;
1899 cur.message(os.str());
1901 // write something to the minibuffer
1902 // translate to latex
1906 string str = os.str();
1908 string::size_type pos = 0;
1910 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1913 else if (*it == '\0') {
1915 pos = it - str.begin();
1921 res = res.substr(pos - 30);
1922 if (res.size() > 60)
1923 res = res.substr(0, 60);
1929 /////////////////////////////////////////////////////////////////////
1933 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1936 // FIXME: completely broken
1937 static InsetMathHull * lastformula = 0;
1938 static CursorBase current = DocIterator(ibegin(nucleus()));
1940 static string laststr;
1942 if (lastformula != this || laststr != str) {
1943 //lyxerr << "reset lastformula to " << this << endl;
1946 current = ibegin(nucleus());
1948 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1952 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1954 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1955 CursorSlice & top = it.back();
1956 MathData const & a = top.asInsetMath()->cell(top.idx_);
1957 if (a.matchpart(ar, top.pos_)) {
1958 bv->cursor().setSelection(it, ar.size());
1960 top.pos_ += ar.size();
1966 //lyxerr << "not found!" << endl;
1973 void InsetMathHull::write(ostream & os) const
1975 odocstringstream oss;
1976 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1979 os << to_utf8(oss.str());
1983 void InsetMathHull::read(Lexer & lex)
1986 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1987 operator=(*at->asHullInset());
1991 bool InsetMathHull::readQuiet(Lexer & lex)
1994 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1996 operator=(*at->asHullInset());
2001 int InsetMathHull::plaintext(odocstringstream & os,
2002 OutputParams const & op, size_t max_length) const
2004 // disables ASCII-art for export of equations. See #2275.
2005 if (0 && display()) {
2009 TextPainter tpain(dim.width(), dim.height());
2010 drawT(tpain, 0, dim.ascent());
2012 // reset metrics cache to "real" values
2014 return tpain.textheight();
2017 odocstringstream oss;
2018 Encoding const * const enc = encodings.fromLyXName("utf8");
2019 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
2022 if (type_ == hullRegexp)
2025 for (row_type r = 0; r < nrows(); ++r) {
2026 for (col_type c = 0; c < ncols(); ++c)
2027 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2028 // if it's for the TOC, we write just the first line
2029 // and do not include the newline.
2030 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2032 if (r < nrows() - 1)
2036 docstring const str = oss.str();
2042 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
2047 if (getType() == hullSimple)
2048 name = from_ascii("inlineequation");
2050 name = from_ascii("informalequation");
2052 docstring bname = name;
2053 if (!label(0).empty())
2054 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
2056 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
2058 odocstringstream ls;
2059 if (runparams.flavor == OutputParams::XML) {
2060 ms << MTag("alt role='tex' ");
2061 // Workaround for db2latex: db2latex always includes equations with
2062 // \ensuremath{} or \begin{display}\end{display}
2063 // so we strip LyX' math environment
2064 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
2065 InsetMathGrid::write(wi);
2066 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2071 InsetMathGrid::mathmlize(ms);
2076 otexstream ols(ls, texrow);
2077 ms << MTag("alt role='tex'");
2078 latex(ols, runparams);
2079 res = texrow.rows();
2080 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2084 ms << from_ascii("<graphic fileref=\"eqn/");
2085 if (!label(0).empty())
2086 ms << sgml::cleanID(buffer(), runparams, label(0));
2088 ms << sgml::uniqueID(from_ascii("anon"));
2090 if (runparams.flavor == OutputParams::XML)
2091 ms << from_ascii("\"/>");
2093 ms << from_ascii("\">");
2095 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2097 return ms.line() + res;
2101 bool InsetMathHull::haveNumbers() const
2103 bool havenumbers = false;
2104 // inline formulas are never numbered (bug 7351 part 3)
2105 if (getType() == hullSimple)
2107 for (size_t i = 0; i != numbered_.size(); ++i) {
2118 // We need to do something about alignment here.
2120 // This duplicates code from InsetMathGrid, but
2121 // we need access here to number information,
2122 // and we simply do not have that in InsetMathGrid.
2123 void InsetMathHull::htmlize(HtmlStream & os) const
2125 bool const havenumbers = haveNumbers();
2126 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2129 os << cell(index(0, 0));
2133 os << MTag("table", "class='mathtable'");
2134 for (row_type row = 0; row < nrows(); ++row) {
2136 for (col_type col = 0; col < ncols(); ++col) {
2138 os << cell(index(row, col));
2143 docstring const & num = numbers_[row];
2145 os << '(' << num << ')';
2150 os << ETag("table");
2154 // this duplicates code from InsetMathGrid, but
2155 // we need access here to number information,
2156 // and we simply do not have that in InsetMathGrid.
2157 void InsetMathHull::mathmlize(MathStream & os) const
2159 bool const havenumbers = haveNumbers();
2160 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2163 os << MTag("mtable");
2164 char const * const celltag = havetable ? "mtd" : "mrow";
2165 // FIXME There does not seem to be wide support at the moment
2166 // for mlabeledtr, so we have to use just mtr for now.
2167 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2168 char const * const rowtag = "mtr";
2169 for (row_type row = 0; row < nrows(); ++row) {
2172 for (col_type col = 0; col < ncols(); ++col) {
2174 << cell(index(row, col))
2180 docstring const & num = numbers_[row];
2182 os << '(' << num << ')';
2189 os << ETag("mtable");
2193 void InsetMathHull::mathAsLatex(WriteStream & os) const
2195 MathEnsurer ensurer(os, false);
2196 bool havenumbers = haveNumbers();
2197 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2200 os << cell(index(0, 0));
2204 os << "<table class='mathtable'>";
2205 for (row_type row = 0; row < nrows(); ++row) {
2207 for (col_type col = 0; col < ncols(); ++col) {
2208 os << "<td class='math'>";
2209 os << cell(index(row, col));
2214 docstring const & num = numbers_[row];
2216 os << '(' << num << ')';
2225 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2227 BufferParams::MathOutput const mathtype =
2228 buffer().masterBuffer()->params().html_math_output;
2230 bool success = false;
2232 // we output all the labels just at the beginning of the equation.
2233 // this should be fine.
2234 for (size_t i = 0; i != label_.size(); ++i) {
2235 InsetLabel const * const il = label_[i];
2241 // FIXME Eventually we would like to do this inset by inset.
2242 if (mathtype == BufferParams::MathML) {
2243 odocstringstream os;
2248 } catch (MathExportException const &) {}
2250 if (getType() == hullSimple)
2251 xs << html::StartTag("math",
2252 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2254 xs << html::StartTag("math",
2255 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2256 xs << XHTMLStream::ESCAPE_NONE
2258 << html::EndTag("math");
2260 } else if (mathtype == BufferParams::HTML) {
2261 odocstringstream os;
2266 } catch (MathExportException const &) {}
2268 string const tag = (getType() == hullSimple) ? "span" : "div";
2269 xs << html::StartTag(tag, "class='formula'", true)
2270 << XHTMLStream::ESCAPE_NONE
2272 << html::EndTag(tag);
2276 // what we actually want is this:
2278 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2280 // || mathtype == BufferParams::Images
2282 // but what follows is equivalent, since we'll enter only if either (a) we
2283 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2284 // aren't doing LaTeX, in which case we are doing Images.
2285 if (!success && mathtype != BufferParams::LaTeX) {
2286 graphics::PreviewImage const * pimage = 0;
2288 loadPreview(docit_);
2289 pimage = preview_->getPreviewImage(buffer());
2290 // FIXME Do we always have png?
2293 if (pimage || op.dryrun) {
2294 string const filename = pimage ? pimage->filename().onlyFileName()
2295 : "previewimage.png";
2297 // if we are not in the master buffer, then we need to see that the
2298 // generated image is copied there; otherwise, preview fails.
2299 Buffer const * mbuf = buffer().masterBuffer();
2300 if (mbuf != &buffer()) {
2301 string mbtmp = mbuf->temppath();
2302 FileName const mbufimg(support::addName(mbtmp, filename));
2303 pimage->filename().copyTo(mbufimg);
2305 // add the file to the list of files to be exported
2306 op.exportdata->addExternalFile("xhtml", pimage->filename());
2309 string const tag = (getType() == hullSimple) ? "span" : "div";
2311 << html::StartTag(tag)
2312 << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2313 << html::EndTag(tag)
2319 // so we'll pass this test if we've failed everything else, or
2320 // if mathtype was LaTeX, since we won't have entered any of the
2322 if (!success /* || mathtype != BufferParams::LaTeX */) {
2323 // Unfortunately, we cannot use latexString() because we do not want
2324 // $...$ or whatever.
2325 odocstringstream ls;
2326 WriteStream wi(ls, false, true, WriteStream::wsPreview);
2327 ModeSpecifier specifier(wi, MATH_MODE);
2329 docstring const latex = ls.str();
2331 // class='math' allows for use of jsMath
2332 // http://www.math.union.edu/~dpvc/jsMath/
2334 // probably should allow for some kind of customization here
2335 string const tag = (getType() == hullSimple) ? "span" : "div";
2336 xs << html::StartTag(tag, "class='math'")
2338 << html::EndTag(tag)
2345 void InsetMathHull::toString(odocstream & os) const
2347 odocstringstream ods;
2348 plaintext(ods, OutputParams(0));
2353 void InsetMathHull::forOutliner(docstring & os, size_t) const
2355 odocstringstream ods;
2363 string InsetMathHull::contextMenuName() const
2365 return "context-math";
2369 void InsetMathHull::recordLocation(DocIterator const & di)