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 "MathExtern.h"
18 #include "MathFactory.h"
19 #include "MathStream.h"
20 #include "MathSupport.h"
23 #include "BufferParams.h"
24 #include "BufferView.h"
26 #include "CutAndPaste.h"
29 #include "FuncRequest.h"
30 #include "FuncStatus.h"
32 #include "LaTeXFeatures.h"
34 #include "MacroTable.h"
35 #include "output_xhtml.h"
36 #include "Paragraph.h"
37 #include "ParIterator.h"
39 #include "TextClass.h"
40 #include "TextPainter.h"
41 #include "TocBackend.h"
43 #include "insets/InsetLabel.h"
44 #include "insets/InsetRef.h"
45 #include "insets/RenderPreview.h"
47 #include "graphics/GraphicsImage.h"
48 #include "graphics/PreviewImage.h"
49 #include "graphics/PreviewLoader.h"
51 #include "frontends/alert.h"
52 #include "frontends/Painter.h"
54 #include "support/convert.h"
55 #include "support/lassert.h"
56 #include "support/debug.h"
57 #include "support/filetools.h"
58 #include "support/gettext.h"
59 #include "support/lstrings.h"
64 using namespace lyx::support;
68 using cap::grabAndEraseSelection;
69 using cap::reduceSelectionToOneCell;
73 int getCols(HullType type)
90 // returns position of first relation operator in the array
91 // used for "intelligent splitting"
92 size_t firstRelOp(MathData const & ar)
94 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
96 return it - ar.begin();
101 char const * star(bool numbered)
103 return numbered ? "" : "*";
107 } // end anon namespace
110 HullType hullType(docstring const & s)
112 if (s == "none") return hullNone;
113 if (s == "simple") return hullSimple;
114 if (s == "equation") return hullEquation;
115 if (s == "eqnarray") return hullEqnArray;
116 if (s == "align") return hullAlign;
117 if (s == "alignat") return hullAlignAt;
118 if (s == "xalignat") return hullXAlignAt;
119 if (s == "xxalignat") return hullXXAlignAt;
120 if (s == "multline") return hullMultline;
121 if (s == "gather") return hullGather;
122 if (s == "flalign") return hullFlAlign;
123 if (s == "regexp") return hullRegexp;
124 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
129 docstring hullName(HullType type)
132 case hullNone: return from_ascii("none");
133 case hullSimple: return from_ascii("simple");
134 case hullEquation: return from_ascii("equation");
135 case hullEqnArray: return from_ascii("eqnarray");
136 case hullAlign: return from_ascii("align");
137 case hullAlignAt: return from_ascii("alignat");
138 case hullXAlignAt: return from_ascii("xalignat");
139 case hullXXAlignAt: return from_ascii("xxalignat");
140 case hullMultline: return from_ascii("multline");
141 case hullGather: return from_ascii("gather");
142 case hullFlAlign: return from_ascii("flalign");
143 case hullRegexp: return from_ascii("regexp");
145 lyxerr << "unknown hull type '" << type << "'" << endl;
146 return from_ascii("none");
150 static InsetLabel * dummy_pointer = 0;
152 InsetMathHull::InsetMathHull(Buffer * buf)
153 : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, NUMBER),
154 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
155 preview_(new RenderPreview(this)), use_preview_(false)
157 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
158 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
159 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
160 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
167 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
168 : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, NUMBER),
169 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
170 preview_(new RenderPreview(this)), use_preview_(false)
178 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
184 InsetMathHull::~InsetMathHull()
186 for (size_t i = 0; i < label_.size(); ++i)
191 Inset * InsetMathHull::clone() const
193 return new InsetMathHull(*this);
197 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
201 InsetMathGrid::operator=(other);
203 numbered_ = other.numbered_;
204 numbers_ = other.numbers_;
205 buffer_ = other.buffer_;
206 for (size_t i = 0; i < label_.size(); ++i)
208 label_ = other.label_;
209 for (size_t i = 0; i != label_.size(); ++i) {
211 label_[i] = new InsetLabel(*label_[i]);
213 preview_.reset(new RenderPreview(*other.preview_, this));
219 void InsetMathHull::setBuffer(Buffer & buffer)
221 InsetMathGrid::setBuffer(buffer);
223 for (size_t i = 0; i != label_.size(); ++i) {
225 label_[i]->setBuffer(buffer);
230 // FIXME This should really be controlled by the TOC level, or
231 // something of the sort.
233 const char * counters_to_save[] = {"section", "chapter"};
234 unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
238 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
241 //FIXME: buffer_ should be set at creation for this inset! Problem is
242 // This inset is created at too many places (see Parser::parse1() in
247 // if any of the equations are numbered, then we want to save the values
248 // of some of the counters.
250 BufferParams const & bp = buffer_->params();
251 string const & lang = it->getParLanguage(bp)->code();
253 buffer_->masterBuffer()->params().documentClass().counters();
255 // right now, we only need to do this at export time
256 if (utype == OutputUpdate) {
257 for (size_t i = 0; i < numcnts; ++i) {
258 docstring const cnt = from_ascii(counters_to_save[i]);
259 if (cnts.hasCounter(cnt))
260 counter_map[cnt] = cnts.value(cnt);
264 // this has to be done separately
265 docstring const eqstr = from_ascii("equation");
266 if (cnts.hasCounter(eqstr)) {
267 if (utype == OutputUpdate)
268 counter_map[eqstr] = cnts.value(eqstr);
269 for (size_t i = 0; i != label_.size(); ++i) {
271 cnts.step(eqstr, utype);
272 numbers_[i] = cnts.theCounter(eqstr, lang);
274 numbers_[i] = empty_docstring();
280 for (size_t i = 0; i != label_.size(); ++i) {
282 label_[i]->updateBuffer(it, utype);
285 InsetMathGrid::updateBuffer(it, utype);
289 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active) const
292 //FIXME: buffer_ should be set at creation for this inset! Problem is
293 // This inset is created at too many places (see Parser::parse1() in
298 Toc & toc = buffer().tocBackend().toc("equation");
300 for (row_type row = 0; row != nrows(); ++row) {
304 label_[row]->addToToc(pit, output_active);
305 toc.push_back(TocItem(pit, 0, nicelabel(row), output_active));
310 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
316 return InsetMathNest::editXY(cur, x, y);
320 InsetMath::mode_type InsetMathHull::currentMode() const
322 if (type_ == hullNone)
323 return UNDECIDED_MODE;
324 // definitely math mode ...
329 bool InsetMathHull::idxFirst(Cursor & cur) const
337 bool InsetMathHull::idxLast(Cursor & cur) const
339 cur.idx() = nargs() - 1;
340 cur.pos() = cur.lastpos();
345 char InsetMathHull::defaultColAlign(col_type col)
347 if (type_ == hullEqnArray)
349 if (type_ == hullMultline)
351 if (type_ == hullGather)
353 if (type_ >= hullAlign)
354 return "rl"[col & 1];
359 char InsetMathHull::displayColAlign(idx_type idx) const
361 if (type_ == hullMultline) {
362 row_type const r = row(idx);
365 if (r == nrows() - 1)
368 return InsetMathGrid::displayColAlign(idx);
372 int InsetMathHull::defaultColSpace(col_type col)
374 if (type_ == hullAlign || type_ == hullAlignAt)
376 if (type_ == hullXAlignAt)
377 return (col & 1) ? 20 : 0;
378 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
379 return (col & 1) ? 40 : 0;
384 docstring InsetMathHull::standardFont() const
389 font_name = from_ascii("texttt");
392 font_name = from_ascii("lyxnochange");
395 font_name = from_ascii("mathnormal");
401 ColorCode InsetMathHull::standardColor() const
407 color = Color_foreground;
416 bool InsetMathHull::previewState(const BufferView *const bv) const
418 if (!editing(bv) && RenderPreview::previewMath()
419 && type_ != hullRegexp)
421 graphics::PreviewImage const * pimage =
422 preview_->getPreviewImage(bv->buffer());
423 return pimage && pimage->image();
430 static const int ERROR_FRAME_WIDTH = 2;
433 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
435 if (previewState(mi.base.bv)) {
436 preview_->metrics(mi, dim);
437 if (previewTooSmall(dim)) {
438 // preview image is too small
439 dim.wid += 2 * ERROR_FRAME_WIDTH;
440 dim.asc += 2 * ERROR_FRAME_WIDTH;
442 // insert a one pixel gap in front of the formula
445 dim.des += displayMargin();
447 // Cache the inset dimension.
448 setDimCache(mi, dim);
452 FontSetChanger dummy1(mi.base, standardFont());
453 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
455 // let the cells adjust themselves
456 InsetMathGrid::metrics(mi, dim);
459 dim.asc += displayMargin();
460 dim.des += displayMargin();
463 if (numberedType()) {
464 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
466 for (row_type row = 0; row < nrows(); ++row)
467 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
473 if (type_ == hullRegexp)
475 // make it at least as high as the current font
478 math_font_max_dim(mi.base.font, asc, des);
479 dim.asc = max(dim.asc, asc);
480 dim.des = max(dim.des, des);
481 // Cache the inset dimension.
482 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
483 setDimCache(mi, dim);
487 bool InsetMathHull::previewTooSmall(Dimension const & dim) const
489 return dim.width() <= 10 && dim.height() <= 10;
493 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
495 BufferView const * const bv = pi.base.bv;
496 if (previewState(bv)) {
497 Dimension const dim = dimension(*pi.base.bv);
498 if (previewTooSmall(dim))
500 return graphics::PreviewLoader::backgroundColor();
506 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
508 Dimension const dim = dimension(*pi.base.bv);
509 if (previewTooSmall(dim)) {
510 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
511 dim.wid, dim.asc + dim.des, backgroundColor(pi));
514 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
515 dim.asc + dim.des - 1, pi.backgroundColor(this));
519 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
521 BufferView const * const bv = pi.base.bv;
522 use_preview_ = previewState(bv);
524 if (type_ == hullRegexp) {
525 Dimension const dim = dimension(*bv);
526 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
527 dim.width() - 2, dim.height() - 2, Color_regexpframe);
531 Dimension const dim = dimension(*bv);
532 if (previewTooSmall(dim)) {
533 // we have an extra frame
534 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
536 // one pixel gap in front
537 preview_->draw(pi, x + 1, y);
539 setPosCache(pi, x, y);
543 ColorCode color = pi.selected && lyxrc.use_system_colors
544 ? Color_selectiontext : standardColor();
545 bool const really_change_color = pi.base.font.color() == Color_none;
546 ColorChanger dummy0(pi.base.font, color, really_change_color);
547 FontSetChanger dummy1(pi.base, standardFont());
548 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
550 InsetMathGrid::draw(pi, x + 1, y);
552 if (numberedType()) {
553 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
554 for (row_type row = 0; row < nrows(); ++row) {
555 int const yy = y + rowinfo_[row].offset_;
556 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
557 docstring const nl = nicelabel(row);
561 setPosCache(pi, x, y);
565 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
568 InsetMathGrid::metricsT(mi, dim);
571 WriteStream wi(os, false, true, WriteStream::wsDefault);
573 dim.wid = os.str().size();
580 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
583 InsetMathGrid::drawT(pain, x, y);
586 WriteStream wi(os, false, true, WriteStream::wsDefault);
588 pain.draw(x, y, os.str().c_str());
593 static docstring latexString(InsetMathHull const & inset)
596 // This has to be static, because a preview snippet or a math
597 // macro containing math in text mode (such as $\text{$\phi$}$ or
598 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
599 // first time as a whole, and the second time only the inner math.
600 // In this last case inset.buffer() would be invalid.
601 static Encoding const * encoding = 0;
602 if (inset.isBufferValid())
603 encoding = &(inset.buffer().params().encoding());
604 WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
610 void InsetMathHull::initUnicodeMath() const
612 // Trigger classification of the unicode symbols in this inset
613 docstring const dummy = latexString(*this);
617 void InsetMathHull::addPreview(DocIterator const & inset_pos,
618 graphics::PreviewLoader & /*ploader*/) const
620 if (RenderPreview::previewMath()) {
621 preparePreview(inset_pos);
626 void InsetMathHull::preparePreview(DocIterator const & pos,
627 bool forexport) const
629 // there is no need to do all the macro stuff if we're not
630 // actually going to generate the preview.
631 if (!RenderPreview::previewMath() && !forexport)
634 Buffer const * buffer = pos.buffer();
636 // collect macros at this position
638 buffer->listMacroNames(macros);
639 MacroNameSet::iterator it = macros.begin();
640 MacroNameSet::iterator end = macros.end();
641 docstring macro_preamble;
642 for (; it != end; ++it) {
643 MacroData const * data = buffer->getMacro(*it, pos, true);
645 odocstringstream mac_preamble;
646 data->write(mac_preamble, false);
647 docstring const mps = mac_preamble.str();
648 bool const is_new_def = prefixIs(mps, from_ascii("\\newcomm"));
649 // assure that \newcommand definitions of macros are only added once
650 if (!is_new_def || !preview_->hasMacroDef(mps, *buffer)) {
652 preview_->addMacroDef(mps, *buffer);
653 if (!macro_preamble.empty())
654 macro_preamble += '\n';
655 macro_preamble += mps;
661 if (forexport && haveNumbers()) {
662 docstring eqstr = from_ascii("equation");
663 CounterMap::const_iterator it = counter_map.find(eqstr);
664 if (it != counter_map.end()) {
665 int num = it->second;
667 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
668 '{' + convert<docstring>(num) + '}' + '\n';
670 for (size_t i = 0; i != numcnts; ++i) {
671 docstring cnt = from_ascii(counters_to_save[i]);
672 it = counter_map.find(cnt);
673 if (it == counter_map.end())
675 int num = it->second;
677 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
678 '{' + convert<docstring>(num) + '}';
681 docstring const snippet = macro_preamble + setcnt + latexString(*this);
682 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
683 preview_->addPreview(snippet, *buffer, forexport);
687 void InsetMathHull::reloadPreview(DocIterator const & pos) const
690 preview_->startLoading(*pos.buffer());
694 void InsetMathHull::loadPreview(DocIterator const & pos) const
696 bool const forexport = true;
697 preparePreview(pos, forexport);
698 preview_->startLoading(*pos.buffer(), forexport);
702 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
704 if (RenderPreview::previewMath()) {
706 cur.screenUpdateFlags(Update::Force);
712 docstring InsetMathHull::label(row_type row) const
714 LASSERT(row < nrows(), return docstring());
715 if (InsetLabel * il = label_[row])
716 return il->screenLabel();
721 void InsetMathHull::label(row_type row, docstring const & label)
723 //lyxerr << "setting label '" << label << "' for row " << row << endl;
727 label_[row] = dummy_pointer;
730 label_[row]->updateLabelAndRefs(label);
732 label_[row]->setParam("name", label);
736 InsetCommandParams p(LABEL_CODE);
738 label_[row] = new InsetLabel(buffer_, p);
740 label_[row]->setBuffer(buffer());
744 void InsetMathHull::numbered(row_type row, Numbered num)
746 numbered_[row] = num;
747 if (!numbered(row) && label_[row]) {
754 bool InsetMathHull::numbered(row_type row) const
756 return numbered_[row] == NUMBER;
760 bool InsetMathHull::ams() const
778 for (size_t row = 0; row < numbered_.size(); ++row)
779 if (numbered_[row] == NOTAG)
785 Inset::DisplayType InsetMathHull::display() const
787 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
792 bool InsetMathHull::numberedType() const
794 if (type_ == hullNone)
796 if (type_ == hullSimple)
798 if (type_ == hullXXAlignAt)
800 if (type_ == hullRegexp)
802 for (row_type row = 0; row < nrows(); ++row)
809 void InsetMathHull::validate(LaTeXFeatures & features) const
811 if (features.runparams().isLaTeX()) {
813 features.require("amsmath");
815 if (type_ == hullRegexp) {
816 features.require("color");
817 string frcol = lcolor.getLaTeXName(Color_regexpframe);
818 string bgcol = "white";
819 features.addPreambleSnippet(
820 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
821 + frcol + string("}{")
822 + bgcol + string("}{\\ensuremath{\\mathtt{#1}}}}"));
823 features.addPreambleSnippet(
824 string("\\newcommand{\\endregexp}{}"));
827 // Validation is necessary only if not using AMS math.
828 // To be safe, we will always run mathedvalidate.
829 //if (features.amsstyle)
832 //features.binom = true;
833 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
834 // it would be better to do this elsewhere, but we can't validate in
835 // InsetMathMatrix and we have no way, outside MathExtern, to know if
836 // we even have any matrices.
837 features.addCSSSnippet(
838 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
839 "table.matrix td{padding: 0.25px;}\n"
840 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
841 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
843 InsetMathGrid::validate(features);
847 void InsetMathHull::header_write(WriteStream & os) const
849 bool n = numberedType();
863 os << "\n\\begin{equation" << star(n) << "}\n";
873 os << "\n\\begin{" << hullName(type_) << star(n) << "}\n";
878 os << "\n\\begin{" << hullName(type_) << star(n) << '}'
879 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
883 os << "\n\\begin{" << hullName(type_) << '}'
884 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
892 os << "\n\\begin{unknown" << star(n) << "}\n";
898 void InsetMathHull::footer_write(WriteStream & os) const
900 bool n = numberedType();
913 os << "\n\\end{equation" << star(n) << "}\n";
925 os << "\n\\end{" << hullName(type_) << star(n) << "}\n";
929 os << "\n\\end{" << hullName(type_) << "}\n";
933 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
934 os << "\\endregexp{}}";
938 os << "\n\\end{unknown" << star(n) << "}\n";
944 bool InsetMathHull::rowChangeOK() const
947 type_ == hullEqnArray || type_ == hullAlign ||
948 type_ == hullFlAlign || type_ == hullAlignAt ||
949 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
950 type_ == hullGather || type_ == hullMultline;
954 bool InsetMathHull::colChangeOK() const
957 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
958 type_ == hullXAlignAt || type_ == hullXXAlignAt;
962 void InsetMathHull::addRow(row_type row)
967 bool numbered = numberedType();
968 // Move the number and raw pointer, do not call label() (bug 7511)
969 InsetLabel * label = dummy_pointer;
970 docstring number = empty_docstring();
971 if (type_ == hullMultline) {
972 if (row + 1 == nrows()) {
973 numbered_[row] = NONUMBER;
974 swap(label, label_[row]);
975 swap(number, numbers_[row]);
980 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
981 numbers_.insert(numbers_.begin() + row + 1, number);
982 label_.insert(label_.begin() + row + 1, label);
983 InsetMathGrid::addRow(row);
987 void InsetMathHull::swapRow(row_type row)
991 if (row + 1 == nrows())
993 swap(numbered_[row], numbered_[row + 1]);
994 swap(numbers_[row], numbers_[row + 1]);
995 swap(label_[row], label_[row + 1]);
996 InsetMathGrid::swapRow(row);
1000 void InsetMathHull::delRow(row_type row)
1002 if (nrows() <= 1 || !rowChangeOK())
1004 if (row + 1 == nrows() && type_ == hullMultline) {
1005 swap(numbered_[row - 1], numbered_[row]);
1006 swap(numbers_[row - 1], numbers_[row]);
1007 swap(label_[row - 1], label_[row]);
1008 InsetMathGrid::delRow(row);
1011 InsetMathGrid::delRow(row);
1012 // The last dummy row has no number info nor a label.
1013 // Test nrows() + 1 because we have already erased the row.
1014 if (row == nrows() + 1)
1016 numbered_.erase(numbered_.begin() + row);
1017 numbers_.erase(numbers_.begin() + row);
1019 label_.erase(label_.begin() + row);
1023 void InsetMathHull::addCol(col_type col)
1027 InsetMathGrid::addCol(col);
1031 void InsetMathHull::delCol(col_type col)
1033 if (ncols() <= 1 || !colChangeOK())
1035 InsetMathGrid::delCol(col);
1039 docstring InsetMathHull::nicelabel(row_type row) const
1043 docstring const & val = numbers_[row];
1045 return '(' + val + ')';
1046 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1050 void InsetMathHull::glueall(HullType type)
1053 for (idx_type i = 0; i < nargs(); ++i)
1055 InsetLabel * label = 0;
1056 if (type == hullEquation) {
1057 // preserve first non-empty label
1058 for (row_type row = 0; row < nrows(); ++row) {
1060 label = label_[row];
1066 *this = InsetMathHull(buffer_, hullSimple);
1073 void InsetMathHull::splitTo2Cols()
1075 LASSERT(ncols() == 1, return);
1076 InsetMathGrid::addCol(1);
1077 for (row_type row = 0; row < nrows(); ++row) {
1078 idx_type const i = 2 * row;
1079 pos_type pos = firstRelOp(cell(i));
1080 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1081 cell(i).erase(pos, cell(i).size());
1086 void InsetMathHull::splitTo3Cols()
1088 LASSERT(ncols() < 3, return);
1091 InsetMathGrid::addCol(2);
1092 for (row_type row = 0; row < nrows(); ++row) {
1093 idx_type const i = 3 * row + 1;
1094 if (!cell(i).empty()) {
1095 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1096 cell(i).erase(1, cell(i).size());
1102 void InsetMathHull::changeCols(col_type cols)
1104 if (ncols() == cols)
1106 else if (ncols() < cols) {
1112 while (ncols() < cols)
1113 InsetMathGrid::addCol(ncols());
1119 for (row_type row = 0; row < nrows(); ++row) {
1120 idx_type const i = row * ncols();
1121 for (col_type col = cols; col < ncols(); ++col) {
1122 cell(i + cols - 1).append(cell(i + col));
1126 while (ncols() > cols) {
1127 InsetMathGrid::delCol(ncols() - 1);
1132 HullType InsetMathHull::getType() const
1138 void InsetMathHull::setType(HullType type)
1145 void InsetMathHull::mutate(HullType newtype)
1147 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1149 // we try to move along the chain
1150 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1152 // +-------------------------------------+
1153 // we use eqnarray as intermediate type for mutations that are not
1154 // directly supported because it handles labels and numbering for
1157 if (newtype == type_) {
1161 else if (newtype < hullNone) {
1166 else if (type_ == hullNone) {
1167 setType(hullSimple);
1172 else if (type_ == hullSimple) {
1173 if (newtype == hullNone) {
1177 setType(hullEquation);
1178 numbered(0, label_[0] ? true : false);
1183 else if (type_ == hullEquation) {
1184 if (newtype < type_) {
1185 setType(hullSimple);
1188 } else if (newtype == hullEqnArray) {
1189 // split it "nicely" on the first relop
1191 setType(hullEqnArray);
1192 } else if (newtype == hullMultline || newtype == hullGather) {
1195 // split it "nicely"
1202 else if (type_ == hullEqnArray) {
1203 if (newtype < type_) {
1206 } else { // align & Co.
1213 else if (type_ == hullAlign || type_ == hullAlignAt ||
1214 type_ == hullXAlignAt || type_ == hullFlAlign) {
1215 if (newtype < hullAlign) {
1217 setType(hullEqnArray);
1219 } else if (newtype == hullGather || newtype == hullMultline) {
1222 } else if (newtype == hullXXAlignAt) {
1223 for (row_type row = 0; row < nrows(); ++row)
1224 numbered(row, false);
1231 else if (type_ == hullXXAlignAt) {
1232 for (row_type row = 0; row < nrows(); ++row)
1233 numbered(row, false);
1234 if (newtype < hullAlign) {
1236 setType(hullEqnArray);
1238 } else if (newtype == hullGather || newtype == hullMultline) {
1246 else if (type_ == hullMultline || type_ == hullGather) {
1247 if (newtype == hullGather || newtype == hullMultline)
1249 else if (newtype == hullAlign || newtype == hullFlAlign ||
1250 newtype == hullAlignAt || newtype == hullXAlignAt) {
1253 } else if (newtype == hullXXAlignAt) {
1255 for (row_type row = 0; row < nrows(); ++row)
1256 numbered(row, false);
1260 setType(hullEqnArray);
1266 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1267 << "' to '" << to_utf8(hullName(newtype))
1268 << "' not implemented" << endl;
1273 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1274 bool last_eoln) const
1277 if (numberedType()) {
1278 if (label_[row] && numbered(row)) {
1279 docstring const name =
1280 latex ? escape(label_[row]->getParam("name"))
1281 : label_[row]->getParam("name");
1282 res += "\\label{" + name + '}';
1284 if (type_ != hullMultline) {
1285 if (numbered_[row] == NONUMBER)
1286 res += "\\nonumber ";
1287 else if (numbered_[row] == NOTAG)
1291 // Never add \\ on the last empty line of eqnarray and friends
1293 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1297 void InsetMathHull::write(WriteStream & os) const
1299 ModeSpecifier specifier(os, MATH_MODE);
1301 InsetMathGrid::write(os);
1306 void InsetMathHull::normalize(NormalStream & os) const
1308 os << "[formula " << hullName(type_) << ' ';
1309 InsetMathGrid::normalize(os);
1314 void InsetMathHull::infoize(odocstream & os) const
1316 os << bformat(_("Type: %1$s"), hullName(type_));
1320 void InsetMathHull::check() const
1322 LATTEST(numbered_.size() == nrows());
1323 LATTEST(numbers_.size() == nrows());
1324 LATTEST(label_.size() == nrows());
1328 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1332 idocstringstream iss(func.argument());
1333 iss >> dlang >> extra;
1335 extra = from_ascii("noextra");
1336 string const lang = to_ascii(dlang);
1338 // replace selection with result of computation
1339 if (reduceSelectionToOneCell(cur)) {
1341 asArray(grabAndEraseSelection(cur), ar);
1342 lyxerr << "use selection: " << ar << endl;
1343 cur.insert(pipeThroughExtern(lang, extra, ar));
1347 // only inline, display or eqnarray math is allowed
1348 if (getType() > hullEqnArray) {
1349 frontend::Alert::warning(_("Bad math environment"),
1350 _("Computation cannot be performed for AMS "
1351 "math environments.\nChange the math "
1352 "formula type and try again."));
1357 eq.push_back(MathAtom(new InsetMathChar('=')));
1359 // go to first item in line
1360 cur.idx() -= cur.idx() % ncols();
1363 if (getType() == hullSimple) {
1364 size_type pos = cur.cell().find_last(eq);
1366 if (pos == cur.cell().size()) {
1368 lyxerr << "use whole cell: " << ar << endl;
1370 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1371 lyxerr << "use partial cell form pos: " << pos << endl;
1373 cur.cell().append(eq);
1374 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1375 cur.pos() = cur.lastpos();
1379 if (getType() == hullEquation) {
1380 lyxerr << "use equation inset" << endl;
1381 mutate(hullEqnArray);
1382 MathData & ar = cur.cell();
1383 lyxerr << "use cell: " << ar << endl;
1387 cur.cell() = pipeThroughExtern(lang, extra, ar);
1388 // move to end of line
1389 cur.pos() = cur.lastpos();
1394 lyxerr << "use eqnarray" << endl;
1395 cur.idx() += 2 - cur.idx() % ncols();
1397 MathData ar = cur.cell();
1398 lyxerr << "use cell: " << ar << endl;
1399 // FIXME: temporarily disabled
1405 cur.cell() = pipeThroughExtern(lang, extra, ar);
1406 cur.pos() = cur.lastpos();
1411 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1413 //lyxerr << "action: " << cmd.action() << endl;
1414 switch (cmd.action()) {
1416 case LFUN_FINISHED_BACKWARD:
1417 case LFUN_FINISHED_FORWARD:
1418 case LFUN_FINISHED_RIGHT:
1419 case LFUN_FINISHED_LEFT:
1420 //lyxerr << "action: " << cmd.action() << endl;
1421 InsetMathGrid::doDispatch(cur, cmd);
1424 case LFUN_PARAGRAPH_BREAK:
1425 // just swallow this
1428 case LFUN_NEWLINE_INSERT:
1429 // some magic for the common case
1430 if (type_ == hullSimple || type_ == hullEquation) {
1431 cur.recordUndoInset();
1433 cur.bv().buffer().params().use_package("amsmath") == BufferParams::package_on;
1434 mutate(align ? hullAlign : hullEqnArray);
1435 // mutate() may change labels and such.
1436 cur.forceBufferUpdate();
1437 cur.idx() = nrows() * ncols() - 1;
1438 cur.pos() = cur.lastpos();
1440 InsetMathGrid::doDispatch(cur, cmd);
1443 case LFUN_MATH_NUMBER_TOGGLE: {
1444 //lyxerr << "toggling all numbers" << endl;
1445 cur.recordUndoInset();
1446 bool old = numberedType();
1447 if (type_ == hullMultline)
1448 numbered(nrows() - 1, !old);
1450 for (row_type row = 0; row < nrows(); ++row)
1451 numbered(row, !old);
1453 cur.message(old ? _("No number") : _("Number"));
1454 cur.forceBufferUpdate();
1458 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1459 cur.recordUndoInset();
1460 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1461 bool old = numbered(r);
1462 cur.message(old ? _("No number") : _("Number"));
1464 cur.forceBufferUpdate();
1468 case LFUN_LABEL_INSERT: {
1469 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1470 docstring old_label = label(r);
1471 docstring const default_label = from_ascii("eq:");
1472 if (old_label.empty())
1473 old_label = default_label;
1475 InsetCommandParams p(LABEL_CODE);
1476 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1477 string const data = InsetCommand::params2string(p);
1479 if (cmd.argument().empty())
1480 cur.bv().showDialog("label", data);
1482 FuncRequest fr(LFUN_INSET_INSERT, data);
1488 case LFUN_LABEL_COPY_AS_REFERENCE: {
1490 if (cmd.argument().empty() && &cur.inset() == this)
1491 // if there is no argument and we're inside math, we retrieve
1492 // the row number from the cursor position.
1493 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1495 // if there is an argument, find the corresponding label, else
1496 // check whether there is at least one label.
1497 for (row = 0; row != nrows(); ++row)
1498 if (numbered(row) && label_[row]
1499 && (cmd.argument().empty() || label(row) == cmd.argument()))
1506 InsetCommandParams p(REF_CODE, "ref");
1507 p["reference"] = label(row);
1508 cap::clearSelection();
1509 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1513 case LFUN_WORD_DELETE_FORWARD:
1514 case LFUN_CHAR_DELETE_FORWARD:
1515 if (col(cur.idx()) + 1 == ncols()
1516 && cur.pos() == cur.lastpos()
1517 && !cur.selection()) {
1518 if (!label(row(cur.idx())).empty()) {
1519 cur.recordUndoInset();
1520 label(row(cur.idx()), docstring());
1521 } else if (numbered(row(cur.idx()))) {
1522 cur.recordUndoInset();
1523 numbered(row(cur.idx()), false);
1524 cur.forceBufferUpdate();
1526 InsetMathGrid::doDispatch(cur, cmd);
1530 InsetMathGrid::doDispatch(cur, cmd);
1535 case LFUN_INSET_INSERT: {
1536 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1537 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1538 string const name = cmd.getArg(0);
1539 if (name == "label") {
1540 InsetCommandParams p(LABEL_CODE);
1541 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1542 docstring str = p["name"];
1543 cur.recordUndoInset();
1544 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1548 docstring old = label(r);
1551 // The label will take care of the reference update.
1555 // Newly created inset so initialize it.
1556 label_[r]->initView();
1559 cur.forceBufferUpdate();
1562 InsetMathGrid::doDispatch(cur, cmd);
1566 case LFUN_MATH_EXTERN:
1567 cur.recordUndoInset();
1571 case LFUN_MATH_MUTATE: {
1572 cur.recordUndoInset();
1573 row_type row = cur.row();
1574 col_type col = cur.col();
1575 mutate(hullType(cmd.argument()));
1576 cur.idx() = row * ncols() + col;
1577 if (cur.idx() > cur.lastidx()) {
1578 cur.idx() = cur.lastidx();
1579 cur.pos() = cur.lastpos();
1581 if (cur.pos() > cur.lastpos())
1582 cur.pos() = cur.lastpos();
1584 cur.forceBufferUpdate();
1585 // FIXME: find some more clever handling of the selection,
1586 // i.e. preserve it.
1587 cur.clearSelection();
1588 //cur.dispatched(FINISHED);
1592 case LFUN_MATH_DISPLAY: {
1593 cur.recordUndoInset();
1594 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1596 cur.pos() = cur.lastpos();
1597 //cur.dispatched(FINISHED);
1602 InsetMathGrid::doDispatch(cur, cmd);
1608 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1609 FuncStatus & status) const
1611 switch (cmd.action()) {
1612 case LFUN_FINISHED_BACKWARD:
1613 case LFUN_FINISHED_FORWARD:
1614 case LFUN_FINISHED_RIGHT:
1615 case LFUN_FINISHED_LEFT:
1618 case LFUN_NEWLINE_INSERT:
1619 case LFUN_MATH_EXTERN:
1621 status.setEnabled(true);
1624 // we never allow this in math, and we want to bind enter
1625 // to another actions in command-alternatives
1626 case LFUN_PARAGRAPH_BREAK:
1627 status.setEnabled(false);
1629 case LFUN_MATH_MUTATE: {
1630 HullType const ht = hullType(cmd.argument());
1631 status.setOnOff(type_ == ht);
1632 status.setEnabled(true);
1634 if (ht != hullSimple) {
1635 Cursor tmpcur = cur;
1636 while (!tmpcur.empty()) {
1637 InsetCode code = tmpcur.inset().lyxCode();
1638 if (code == BOX_CODE) {
1640 } else if (code == TABULAR_CODE) {
1641 FuncRequest tmpcmd(LFUN_MATH_DISPLAY);
1642 if (tmpcur.getStatus(tmpcmd, status) && !status.enabled())
1650 case LFUN_MATH_DISPLAY: {
1652 if (cur.depth() > 1) {
1653 Inset const & in = cur[cur.depth()-2].inset();
1654 if (in.lyxCode() == SCRIPT_CODE)
1655 enable = display() != Inline;
1657 status.setEnabled(enable);
1658 status.setOnOff(display() != Inline);
1662 case LFUN_MATH_NUMBER_TOGGLE:
1663 // FIXME: what is the right test, this or the one of
1665 status.setEnabled(display() != Inline);
1666 status.setOnOff(numberedType());
1669 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1670 // FIXME: what is the right test, this or the one of
1672 bool const enable = (type_ == hullMultline)
1673 ? (nrows() - 1 == cur.row())
1674 : display() != Inline;
1675 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1676 status.setEnabled(enable);
1677 status.setOnOff(enable && numbered(r));
1681 case LFUN_LABEL_INSERT:
1682 status.setEnabled(type_ != hullSimple);
1685 case LFUN_LABEL_COPY_AS_REFERENCE: {
1686 bool enabled = false;
1688 if (cmd.argument().empty() && &cur.inset() == this) {
1689 // if there is no argument and we're inside math, we retrieve
1690 // the row number from the cursor position.
1691 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1692 enabled = numberedType() && label_[row] && numbered(row);
1694 // if there is an argument, find the corresponding label, else
1695 // check whether there is at least one label.
1696 for (row_type row = 0; row != nrows(); ++row) {
1697 if (numbered(row) && label_[row] &&
1698 (cmd.argument().empty() || label(row) == cmd.argument())) {
1704 status.setEnabled(enabled);
1708 case LFUN_INSET_INSERT:
1709 if (cmd.getArg(0) == "label") {
1710 status.setEnabled(type_ != hullSimple);
1713 return InsetMathGrid::getStatus(cur, cmd, status);
1715 case LFUN_INSET_MODIFY: {
1716 istringstream is(to_utf8(cmd.argument()));
1720 return InsetMathGrid::getStatus(cur, cmd, status);
1723 && (s == "append-row"
1724 || s == "delete-row"
1725 || s == "copy-row")) {
1726 status.message(bformat(
1727 from_utf8(N_("Can't change number of rows in '%1$s'")),
1729 status.setEnabled(false);
1733 && (s == "append-column"
1734 || s == "delete-column"
1735 || s == "copy-column")) {
1736 status.message(bformat(
1737 from_utf8(N_("Can't change number of columns in '%1$s'")),
1739 status.setEnabled(false);
1742 if ((type_ == hullSimple
1743 || type_ == hullEquation
1744 || type_ == hullNone) &&
1745 (s == "add-hline-above" || s == "add-hline-below")) {
1746 status.message(bformat(
1747 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1749 status.setEnabled(false);
1752 if (s == "add-vline-left" || s == "add-vline-right") {
1753 status.message(bformat(
1754 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1756 status.setEnabled(false);
1759 if (s == "valign-top" || s == "valign-middle"
1760 || s == "valign-bottom" || s == "align-left"
1761 || s == "align-center" || s == "align-right") {
1762 status.setEnabled(false);
1765 return InsetMathGrid::getStatus(cur, cmd, status);
1769 return InsetMathGrid::getStatus(cur, cmd, status);
1772 // This cannot really happen, but inserted to shut-up gcc
1773 return InsetMathGrid::getStatus(cur, cmd, status);
1777 /////////////////////////////////////////////////////////////////////
1781 // simply scrap this function if you want
1782 void InsetMathHull::mutateToText()
1785 // translate to latex
1787 latex(os, false, false);
1788 string str = os.str();
1791 Text * lt = view_->cursor().innerText();
1792 string::const_iterator cit = str.begin();
1793 string::const_iterator end = str.end();
1794 for (; cit != end; ++cit)
1795 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1798 //dispatch(LFUN_ESCAPE);
1803 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1804 docstring const & font)
1806 // this whole function is a hack and won't work for incremental font
1809 if (cur.inset().asInsetMath()->name() == font)
1810 cur.handleFont(to_utf8(font));
1812 cur.handleNest(createInsetMath(font, cur.buffer()));
1818 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1823 font.fromString(to_utf8(arg), b);
1824 if (font.fontInfo().color() != Color_inherit) {
1825 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1826 cur.handleNest(at, 0);
1831 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1834 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1835 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1836 enter_front ? idxFirst(cur) : idxLast(cur);
1837 // The inset formula dimension is not necessarily the same as the
1838 // one of the instant preview image, so we have to indicate to the
1839 // BufferView that a metrics update is needed.
1840 cur.screenUpdateFlags(Update::Force);
1844 void InsetMathHull::revealCodes(Cursor & cur) const
1846 if (!cur.inMathed())
1848 odocstringstream os;
1850 cur.message(os.str());
1852 // write something to the minibuffer
1853 // translate to latex
1857 string str = os.str();
1859 string::size_type pos = 0;
1861 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1864 else if (*it == '\0') {
1866 pos = it - str.begin();
1872 res = res.substr(pos - 30);
1873 if (res.size() > 60)
1874 res = res.substr(0, 60);
1880 /////////////////////////////////////////////////////////////////////
1884 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1887 // FIXME: completely broken
1888 static InsetMathHull * lastformula = 0;
1889 static CursorBase current = DocIterator(ibegin(nucleus()));
1891 static string laststr;
1893 if (lastformula != this || laststr != str) {
1894 //lyxerr << "reset lastformula to " << this << endl;
1897 current = ibegin(nucleus());
1899 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1903 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1905 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1906 CursorSlice & top = it.back();
1907 MathData const & a = top.asInsetMath()->cell(top.idx_);
1908 if (a.matchpart(ar, top.pos_)) {
1909 bv->cursor().setSelection(it, ar.size());
1911 top.pos_ += ar.size();
1917 //lyxerr << "not found!" << endl;
1924 void InsetMathHull::write(ostream & os) const
1926 odocstringstream oss;
1927 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1930 os << to_utf8(oss.str());
1934 void InsetMathHull::read(Lexer & lex)
1937 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1938 operator=(*at->asHullInset());
1942 bool InsetMathHull::readQuiet(Lexer & lex)
1945 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1947 operator=(*at->asHullInset());
1952 int InsetMathHull::plaintext(odocstringstream & os,
1953 OutputParams const & op, size_t max_length) const
1955 // disables ASCII-art for export of equations. See #2275.
1956 if (0 && display()) {
1960 TextPainter tpain(dim.width(), dim.height());
1961 drawT(tpain, 0, dim.ascent());
1963 // reset metrics cache to "real" values
1965 return tpain.textheight();
1968 odocstringstream oss;
1969 Encoding const * const enc = encodings.fromLyXName("utf8");
1970 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1973 if (type_ == hullRegexp)
1976 for (row_type r = 0; r < nrows(); ++r) {
1977 for (col_type c = 0; c < ncols(); ++c)
1978 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
1979 // if it's for the TOC, we write just the first line
1980 // and do not include the newline.
1981 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
1983 if (r < nrows() - 1)
1987 docstring const str = oss.str();
1993 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1998 if (getType() == hullSimple)
1999 name = from_ascii("inlineequation");
2001 name = from_ascii("informalequation");
2003 docstring bname = name;
2004 if (!label(0).empty())
2005 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
2007 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
2009 odocstringstream ls;
2010 if (runparams.flavor == OutputParams::XML) {
2011 ms << MTag("alt role='tex' ");
2012 // Workaround for db2latex: db2latex always includes equations with
2013 // \ensuremath{} or \begin{display}\end{display}
2014 // so we strip LyX' math environment
2015 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
2016 InsetMathGrid::write(wi);
2017 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2022 InsetMathGrid::mathmlize(ms);
2027 otexstream ols(ls, texrow);
2028 ms << MTag("alt role='tex'");
2029 latex(ols, runparams);
2030 res = texrow.rows();
2031 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2035 ms << from_ascii("<graphic fileref=\"eqn/");
2036 if (!label(0).empty())
2037 ms << sgml::cleanID(buffer(), runparams, label(0));
2039 ms << sgml::uniqueID(from_ascii("anon"));
2041 if (runparams.flavor == OutputParams::XML)
2042 ms << from_ascii("\"/>");
2044 ms << from_ascii("\">");
2046 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2048 return ms.line() + res;
2052 bool InsetMathHull::haveNumbers() const
2054 bool havenumbers = false;
2055 // inline formulas are never numbered (bug 7351 part 3)
2056 if (getType() == hullSimple)
2058 for (size_t i = 0; i != numbered_.size(); ++i) {
2069 // We need to do something about alignment here.
2071 // This duplicates code from InsetMathGrid, but
2072 // we need access here to number information,
2073 // and we simply do not have that in InsetMathGrid.
2074 void InsetMathHull::htmlize(HtmlStream & os) const
2076 bool const havenumbers = haveNumbers();
2077 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2080 os << cell(index(0, 0));
2084 os << MTag("table", "class='mathtable'");
2085 for (row_type row = 0; row < nrows(); ++row) {
2087 for (col_type col = 0; col < ncols(); ++col) {
2089 os << cell(index(row, col));
2094 docstring const & num = numbers_[row];
2096 os << '(' << num << ')';
2101 os << ETag("table");
2105 // this duplicates code from InsetMathGrid, but
2106 // we need access here to number information,
2107 // and we simply do not have that in InsetMathGrid.
2108 void InsetMathHull::mathmlize(MathStream & os) const
2110 bool const havenumbers = haveNumbers();
2111 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2114 os << MTag("mtable");
2115 char const * const celltag = havetable ? "mtd" : "mrow";
2116 // FIXME There does not seem to be wide support at the moment
2117 // for mlabeledtr, so we have to use just mtr for now.
2118 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2119 char const * const rowtag = "mtr";
2120 for (row_type row = 0; row < nrows(); ++row) {
2123 for (col_type col = 0; col < ncols(); ++col) {
2125 << cell(index(row, col))
2131 docstring const & num = numbers_[row];
2133 os << '(' << num << ')';
2140 os << ETag("mtable");
2144 void InsetMathHull::mathAsLatex(WriteStream & os) const
2146 MathEnsurer ensurer(os, false);
2147 bool havenumbers = haveNumbers();
2148 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2151 os << cell(index(0, 0));
2155 os << "<table class='mathtable'>";
2156 for (row_type row = 0; row < nrows(); ++row) {
2158 for (col_type col = 0; col < ncols(); ++col) {
2159 os << "<td class='math'>";
2160 os << cell(index(row, col));
2165 docstring const & num = numbers_[row];
2167 os << '(' << num << ')';
2176 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2178 BufferParams::MathOutput const mathtype =
2179 buffer().masterBuffer()->params().html_math_output;
2181 bool success = false;
2183 // we output all the labels just at the beginning of the equation.
2184 // this should be fine.
2185 for (size_t i = 0; i != label_.size(); ++i) {
2186 InsetLabel const * const il = label_[i];
2192 // FIXME Eventually we would like to do this inset by inset.
2193 if (mathtype == BufferParams::MathML) {
2194 odocstringstream os;
2199 } catch (MathExportException const &) {}
2201 if (getType() == hullSimple)
2202 xs << html::StartTag("math",
2203 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2205 xs << html::StartTag("math",
2206 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2207 xs << XHTMLStream::ESCAPE_NONE
2209 << html::EndTag("math");
2211 } else if (mathtype == BufferParams::HTML) {
2212 odocstringstream os;
2217 } catch (MathExportException const &) {}
2219 string const tag = (getType() == hullSimple) ? "span" : "div";
2220 xs << html::StartTag(tag, "class='formula'", true)
2221 << XHTMLStream::ESCAPE_NONE
2223 << html::EndTag(tag);
2227 // what we actually want is this:
2229 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2231 // || mathtype == BufferParams::Images
2233 // but what follows is equivalent, since we'll enter only if either (a) we
2234 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2235 // aren't doing LaTeX, in which case we are doing Images.
2236 if (!success && mathtype != BufferParams::LaTeX) {
2237 graphics::PreviewImage const * pimage = 0;
2239 loadPreview(docit_);
2240 pimage = preview_->getPreviewImage(buffer());
2241 // FIXME Do we always have png?
2244 if (pimage || op.dryrun) {
2245 string const filename = pimage ? pimage->filename().onlyFileName()
2246 : "previewimage.png";
2248 // if we are not in the master buffer, then we need to see that the
2249 // generated image is copied there; otherwise, preview fails.
2250 Buffer const * mbuf = buffer().masterBuffer();
2251 if (mbuf != &buffer()) {
2252 string mbtmp = mbuf->temppath();
2253 FileName const mbufimg(support::addName(mbtmp, filename));
2254 pimage->filename().copyTo(mbufimg);
2256 // add the file to the list of files to be exported
2257 op.exportdata->addExternalFile("xhtml", pimage->filename());
2260 string const tag = (getType() == hullSimple) ? "span" : "div";
2262 << html::StartTag(tag)
2263 << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2264 << html::EndTag(tag)
2270 // so we'll pass this test if we've failed everything else, or
2271 // if mathtype was LaTeX, since we won't have entered any of the
2273 if (!success /* || mathtype != BufferParams::LaTeX */) {
2274 // Unfortunately, we cannot use latexString() because we do not want
2275 // $...$ or whatever.
2276 odocstringstream ls;
2277 WriteStream wi(ls, false, true, WriteStream::wsPreview);
2278 ModeSpecifier specifier(wi, MATH_MODE);
2280 docstring const latex = ls.str();
2282 // class='math' allows for use of jsMath
2283 // http://www.math.union.edu/~dpvc/jsMath/
2285 // probably should allow for some kind of customization here
2286 string const tag = (getType() == hullSimple) ? "span" : "div";
2287 xs << html::StartTag(tag, "class='math'")
2289 << html::EndTag(tag)
2296 void InsetMathHull::toString(odocstream & os) const
2298 odocstringstream ods;
2299 plaintext(ods, OutputParams(0));
2304 void InsetMathHull::forOutliner(docstring & os, size_t) const
2306 odocstringstream ods;
2314 string InsetMathHull::contextMenuName() const
2316 return "context-math";
2320 void InsetMathHull::recordLocation(DocIterator const & di)