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/PreviewImage.h"
48 #include "graphics/PreviewLoader.h"
50 #include "frontends/alert.h"
51 #include "frontends/Painter.h"
53 #include "support/convert.h"
54 #include "support/lassert.h"
55 #include "support/debug.h"
56 #include "support/filetools.h"
57 #include "support/gettext.h"
58 #include "support/lstrings.h"
63 using namespace lyx::support;
67 using cap::grabAndEraseSelection;
71 int getCols(HullType type)
88 // returns position of first relation operator in the array
89 // used for "intelligent splitting"
90 size_t firstRelOp(MathData const & ar)
92 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
94 return it - ar.begin();
99 char const * star(bool numbered)
101 return numbered ? "" : "*";
105 } // end anon namespace
108 HullType hullType(docstring const & s)
110 if (s == "none") return hullNone;
111 if (s == "simple") return hullSimple;
112 if (s == "equation") return hullEquation;
113 if (s == "eqnarray") return hullEqnArray;
114 if (s == "align") return hullAlign;
115 if (s == "alignat") return hullAlignAt;
116 if (s == "xalignat") return hullXAlignAt;
117 if (s == "xxalignat") return hullXXAlignAt;
118 if (s == "multline") return hullMultline;
119 if (s == "gather") return hullGather;
120 if (s == "flalign") return hullFlAlign;
121 if (s == "regexp") return hullRegexp;
122 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
127 docstring hullName(HullType type)
130 case hullNone: return from_ascii("none");
131 case hullSimple: return from_ascii("simple");
132 case hullEquation: return from_ascii("equation");
133 case hullEqnArray: return from_ascii("eqnarray");
134 case hullAlign: return from_ascii("align");
135 case hullAlignAt: return from_ascii("alignat");
136 case hullXAlignAt: return from_ascii("xalignat");
137 case hullXXAlignAt: return from_ascii("xxalignat");
138 case hullMultline: return from_ascii("multline");
139 case hullGather: return from_ascii("gather");
140 case hullFlAlign: return from_ascii("flalign");
141 case hullRegexp: return from_ascii("regexp");
143 lyxerr << "unknown hull type '" << type << "'" << endl;
144 return from_ascii("none");
148 static InsetLabel * dummy_pointer = 0;
150 InsetMathHull::InsetMathHull(Buffer * buf)
151 : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, true),
152 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
153 preview_(new RenderPreview(this))
155 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
156 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
157 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
158 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
165 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
166 : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, true),
167 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
168 preview_(new RenderPreview(this))
176 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
182 InsetMathHull::~InsetMathHull()
184 for (size_t i = 0; i < label_.size(); ++i)
189 Inset * InsetMathHull::clone() const
191 return new InsetMathHull(*this);
195 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
199 InsetMathGrid::operator=(other);
201 numbered_ = other.numbered_;
202 numbers_ = other.numbers_;
203 buffer_ = other.buffer_;
204 for (size_t i = 0; i < label_.size(); ++i)
206 label_ = other.label_;
207 for (size_t i = 0; i != label_.size(); ++i) {
209 label_[i] = new InsetLabel(*label_[i]);
211 preview_.reset(new RenderPreview(*other.preview_, this));
217 void InsetMathHull::setBuffer(Buffer & buffer)
219 InsetMathGrid::setBuffer(buffer);
221 for (size_t i = 0; i != label_.size(); ++i) {
223 label_[i]->setBuffer(buffer);
229 const char * counters_to_save[] = {"section", "chapter"};
230 unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
234 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
237 //FIXME: buffer_ should be set at creation for this inset! Problem is
238 // This inset is created at too many places (see Parser::parse1() in
243 // if any of the equations are numbered, then we want to save the values
244 // of some of the counters.
246 BufferParams const & bp = buffer_->params();
247 string const & lang = it->getParLanguage(bp)->code();
248 Counters & cnts = bp.documentClass().counters();
250 // right now, we only need to do this at export time
251 if (utype == OutputUpdate) {
252 for (size_t i = 0; i < numcnts; ++i) {
253 docstring const cnt = from_ascii(counters_to_save[i]);
254 if (cnts.hasCounter(cnt))
255 counter_map[cnt] = cnts.value(cnt);
259 // this has to be done separately
260 docstring const eqstr = from_ascii("equation");
261 if (cnts.hasCounter(eqstr)) {
262 if (utype == OutputUpdate)
263 counter_map[eqstr] = cnts.value(eqstr);
264 for (size_t i = 0; i != label_.size(); ++i) {
266 cnts.step(eqstr, utype);
267 numbers_[i] = cnts.theCounter(eqstr, lang);
269 numbers_[i] = empty_docstring();
275 for (size_t i = 0; i != label_.size(); ++i) {
277 label_[i]->updateBuffer(it, utype);
280 InsetMathGrid::updateBuffer(it, utype);
284 void InsetMathHull::addToToc(DocIterator const & pit) const
287 //FIXME: buffer_ should be set at creation for this inset! Problem is
288 // This inset is created at too many places (see Parser::parse1() in
293 Toc & toc = buffer().tocBackend().toc("equation");
295 for (row_type row = 0; row != nrows(); ++row) {
299 label_[row]->addToToc(pit);
300 toc.push_back(TocItem(pit, 0, nicelabel(row)));
305 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
311 return InsetMathNest::editXY(cur, x, y);
315 InsetMath::mode_type InsetMathHull::currentMode() const
317 if (type_ == hullNone)
318 return UNDECIDED_MODE;
319 // definitely math mode ...
324 bool InsetMathHull::idxFirst(Cursor & cur) const
332 bool InsetMathHull::idxLast(Cursor & cur) const
334 cur.idx() = nargs() - 1;
335 cur.pos() = cur.lastpos();
340 char InsetMathHull::defaultColAlign(col_type col)
342 if (type_ == hullEqnArray)
344 if (type_ == hullGather)
346 if (type_ >= hullAlign)
347 return "rl"[col & 1];
352 int InsetMathHull::defaultColSpace(col_type col)
354 if (type_ == hullAlign || type_ == hullAlignAt)
356 if (type_ == hullXAlignAt)
357 return (col & 1) ? 20 : 0;
358 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
359 return (col & 1) ? 40 : 0;
364 docstring InsetMathHull::standardFont() const
369 font_name = from_ascii("texttt");
372 font_name = from_ascii("lyxnochange");
375 font_name = from_ascii("mathnormal");
381 ColorCode InsetMathHull::standardColor() const
387 color = Color_foreground;
396 bool InsetMathHull::previewState(BufferView * bv) const
398 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
399 graphics::PreviewImage const * pimage =
400 preview_->getPreviewImage(bv->buffer());
401 return pimage && pimage->image();
407 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
409 if (previewState(mi.base.bv)) {
410 preview_->metrics(mi, dim);
411 // insert a one pixel gap in front of the formula
414 dim.des += displayMargin();
415 // Cache the inset dimension.
416 setDimCache(mi, dim);
420 FontSetChanger dummy1(mi.base, standardFont());
421 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
423 // let the cells adjust themselves
424 InsetMathGrid::metrics(mi, dim);
427 dim.asc += displayMargin();
428 dim.des += displayMargin();
431 if (numberedType()) {
432 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
434 for (row_type row = 0; row < nrows(); ++row)
435 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
441 // make it at least as high as the current font
444 math_font_max_dim(mi.base.font, asc, des);
445 dim.asc = max(dim.asc, asc);
446 dim.des = max(dim.des, des);
447 // Cache the inset dimension.
448 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
449 setDimCache(mi, dim);
453 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
455 if (previewState(pi.base.bv))
456 return graphics::PreviewLoader::backgroundColor();
461 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
463 Dimension const dim = dimension(*pi.base.bv);
464 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
465 dim.asc + dim.des - 1, pi.backgroundColor(this));
469 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
471 use_preview_ = previewState(pi.base.bv);
473 if (type_ == hullRegexp) {
474 Dimension const dim = dimension(*pi.base.bv);
475 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
476 dim.width() - 2, dim.height() - 2, Color_regexpframe);
479 // one pixel gap in front
480 preview_->draw(pi, x + 1, y);
481 setPosCache(pi, x, y);
485 ColorCode color = pi.selected && lyxrc.use_system_colors
486 ? Color_selectiontext : standardColor();
487 bool const really_change_color = pi.base.font.color() == Color_none;
488 ColorChanger dummy0(pi.base.font, color, really_change_color);
489 FontSetChanger dummy1(pi.base, standardFont());
490 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
492 InsetMathGrid::draw(pi, x + 1, y);
494 if (numberedType()) {
495 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
496 for (row_type row = 0; row < nrows(); ++row) {
497 int const yy = y + rowinfo_[row].offset_;
498 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
499 docstring const nl = nicelabel(row);
503 setPosCache(pi, x, y);
507 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
510 InsetMathGrid::metricsT(mi, dim);
513 WriteStream wi(os, false, true, WriteStream::wsDefault);
515 dim.wid = os.str().size();
522 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
525 InsetMathGrid::drawT(pain, x, y);
528 WriteStream wi(os, false, true, WriteStream::wsDefault);
530 pain.draw(x, y, os.str().c_str());
535 static docstring latexString(InsetMathHull const & inset)
538 // This has to be static, because a preview snippet or a math
539 // macro containing math in text mode (such as $\text{$\phi$}$ or
540 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
541 // first time as a whole, and the second time only the inner math.
542 // In this last case inset.buffer() would be invalid.
543 static Encoding const * encoding = 0;
544 if (inset.isBufferValid())
545 encoding = &(inset.buffer().params().encoding());
546 WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
552 void InsetMathHull::initUnicodeMath() const
554 // Trigger classification of the unicode symbols in this inset
555 docstring const dummy = latexString(*this);
559 void InsetMathHull::addPreview(DocIterator const & inset_pos,
560 graphics::PreviewLoader & /*ploader*/) const
562 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
563 preparePreview(inset_pos);
568 void InsetMathHull::preparePreview(DocIterator const & pos,
569 bool forexport) const
571 // there is no need to do all the macro stuff if we're not
572 // actually going to generate the preview.
573 if (RenderPreview::status() != LyXRC::PREVIEW_ON && !forexport)
576 Buffer const * buffer = pos.buffer();
578 // collect macros at this position
580 buffer->listMacroNames(macros);
581 MacroNameSet::iterator it = macros.begin();
582 MacroNameSet::iterator end = macros.end();
583 odocstringstream macro_preamble;
584 for (; it != end; ++it) {
585 MacroData const * data = buffer->getMacro(*it, pos, true);
587 data->write(macro_preamble, true);
588 macro_preamble << endl;
593 if (forexport && haveNumbers()) {
594 docstring eqstr = from_ascii("equation");
595 CounterMap::const_iterator it = counter_map.find(eqstr);
596 if (it != counter_map.end()) {
597 int num = it->second;
599 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
600 '{' + convert<docstring>(num) + '}' + '\n';
602 for (size_t i = 0; i != numcnts; ++i) {
603 docstring cnt = from_ascii(counters_to_save[i]);
604 it = counter_map.find(cnt);
605 if (it == counter_map.end())
607 int num = it->second;
609 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
610 '{' + convert<docstring>(num) + '}';
613 docstring const snippet = macro_preamble.str() +
614 setcnt + latexString(*this);
615 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
616 preview_->addPreview(snippet, *buffer, forexport);
620 void InsetMathHull::reloadPreview(DocIterator const & pos) const
623 preview_->startLoading(*pos.buffer());
627 void InsetMathHull::loadPreview(DocIterator const & pos) const
629 bool const forexport = true;
630 preparePreview(pos, forexport);
631 preview_->startLoading(*pos.buffer(), forexport);
635 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
637 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
639 cur.screenUpdateFlags(Update::Force);
645 docstring InsetMathHull::label(row_type row) const
647 LASSERT(row < nrows(), /**/);
648 if (InsetLabel * il = label_[row])
649 return il->screenLabel();
654 void InsetMathHull::label(row_type row, docstring const & label)
656 //lyxerr << "setting label '" << label << "' for row " << row << endl;
660 label_[row] = dummy_pointer;
663 label_[row]->updateCommand(label);
665 label_[row]->setParam("name", label);
669 InsetCommandParams p(LABEL_CODE);
671 label_[row] = new InsetLabel(buffer_, p);
673 label_[row]->setBuffer(buffer());
677 void InsetMathHull::numbered(row_type row, bool num)
679 numbered_[row] = num;
680 if (!numbered_[row] && label_[row]) {
687 bool InsetMathHull::numbered(row_type row) const
689 return numbered_[row];
693 bool InsetMathHull::ams() const
695 return type_ == hullAlign
696 || type_ == hullFlAlign
697 || type_ == hullMultline
698 || type_ == hullGather
699 || type_ == hullAlignAt
700 || type_ == hullXAlignAt
701 || type_ == hullXXAlignAt;
705 Inset::DisplayType InsetMathHull::display() const
707 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
712 bool InsetMathHull::numberedType() const
714 if (type_ == hullNone)
716 if (type_ == hullSimple)
718 if (type_ == hullXXAlignAt)
720 if (type_ == hullRegexp)
722 for (row_type row = 0; row < nrows(); ++row)
729 void InsetMathHull::validate(LaTeXFeatures & features) const
731 if (features.runparams().isLaTeX()) {
733 features.require("amsmath");
735 if (type_ == hullRegexp) {
736 features.require("color");
737 string frcol = lcolor.getLaTeXName(Color_regexpframe);
738 string bgcol = "white";
739 features.addPreambleSnippet(
740 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
741 + frcol + string("}{")
742 + bgcol + string("}{\\texttt{#1}}}"));
745 // Validation is necessary only if not using AMS math.
746 // To be safe, we will always run mathedvalidate.
747 //if (features.amsstyle)
750 //features.binom = true;
751 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
752 // it would be better to do this elsewhere, but we can't validate in
753 // InsetMathMatrix and we have no way, outside MathExtern, to know if
754 // we even have any matrices.
755 features.addPreambleSnippet("<style type=\"text/css\">\n"
756 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
757 "table.matrix td{padding: 0.25px;}\n"
758 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
759 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}\n"
762 InsetMathGrid::validate(features);
766 void InsetMathHull::header_write(WriteStream & os) const
768 bool n = numberedType();
782 os << "\n\\begin{equation" << star(n) << "}\n";
792 os << "\n\\begin{" << hullName(type_) << star(n) << "}\n";
797 os << "\n\\begin{" << hullName(type_) << star(n) << '}'
798 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
802 os << "\n\\begin{" << hullName(type_) << '}'
803 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
811 os << "\n\\begin{unknown" << star(n) << "}\n";
817 void InsetMathHull::footer_write(WriteStream & os) const
819 bool n = numberedType();
832 os << "\n\\end{equation" << star(n) << "}\n";
844 os << "\n\\end{" << hullName(type_) << star(n) << "}\n";
848 os << "\n\\end{" << hullName(type_) << "}\n";
856 os << "\n\\end{unknown" << star(n) << "}\n";
862 bool InsetMathHull::rowChangeOK() const
865 type_ == hullEqnArray || type_ == hullAlign ||
866 type_ == hullFlAlign || type_ == hullAlignAt ||
867 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
868 type_ == hullGather || type_ == hullMultline;
872 bool InsetMathHull::colChangeOK() const
875 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
876 type_ == hullXAlignAt || type_ == hullXXAlignAt;
880 void InsetMathHull::addRow(row_type row)
885 bool numbered = numberedType();
887 if (type_ == hullMultline) {
888 if (row + 1 == nrows()) {
889 numbered_[row] = false;
895 numbered_.insert(numbered_.begin() + row + 1, numbered);
896 numbers_.insert(numbers_.begin() + row + 1, empty_docstring());
897 label_.insert(label_.begin() + row + 1, dummy_pointer);
900 InsetMathGrid::addRow(row);
904 void InsetMathHull::swapRow(row_type row)
908 if (row + 1 == nrows())
910 // gcc implements the standard std::vector<bool> which is *not* a container:
911 // http://www.gotw.ca/publications/N1185.pdf
912 // As a results, it doesn't like this:
913 // swap(numbered_[row], numbered_[row + 1]);
914 // so we do it manually:
915 bool const b = numbered_[row];
916 numbered_[row] = numbered_[row + 1];
917 numbered_[row + 1] = b;
918 swap(numbers_[row], numbers_[row + 1]);
919 swap(label_[row], label_[row + 1]);
920 InsetMathGrid::swapRow(row);
924 void InsetMathHull::delRow(row_type row)
926 if (nrows() <= 1 || !rowChangeOK())
928 if (row + 1 == nrows() && type_ == hullMultline) {
929 bool const b = numbered_[row - 1];
930 numbered_[row - 1] = numbered_[row];
932 swap(numbers_[row - 1], numbers_[row]);
933 swap(label_[row - 1], label_[row]);
934 InsetMathGrid::delRow(row);
937 InsetMathGrid::delRow(row);
938 // The last dummy row has no number info nor a label.
939 // Test nrows() + 1 because we have already erased the row.
940 if (row == nrows() + 1)
942 numbered_.erase(numbered_.begin() + row);
943 numbers_.erase(numbers_.begin() + row);
945 label_.erase(label_.begin() + row);
949 void InsetMathHull::addCol(col_type col)
953 InsetMathGrid::addCol(col);
957 void InsetMathHull::delCol(col_type col)
959 if (ncols() <= 1 || !colChangeOK())
961 InsetMathGrid::delCol(col);
965 docstring InsetMathHull::nicelabel(row_type row) const
969 docstring const & val = numbers_[row];
971 return '(' + val + ')';
972 return '(' + val + ',' + label_[row]->screenLabel() + ')';
976 void InsetMathHull::glueall(HullType type)
979 for (idx_type i = 0; i < nargs(); ++i)
981 InsetLabel * label = 0;
982 if (type == hullEquation) {
983 // preserve first non-empty label
984 for (row_type row = 0; row < nrows(); ++row) {
992 *this = InsetMathHull(buffer_, hullSimple);
999 void InsetMathHull::splitTo2Cols()
1001 LASSERT(ncols() == 1, /**/);
1002 InsetMathGrid::addCol(1);
1003 for (row_type row = 0; row < nrows(); ++row) {
1004 idx_type const i = 2 * row;
1005 pos_type pos = firstRelOp(cell(i));
1006 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1007 cell(i).erase(pos, cell(i).size());
1012 void InsetMathHull::splitTo3Cols()
1014 LASSERT(ncols() < 3, /**/);
1017 InsetMathGrid::addCol(2);
1018 for (row_type row = 0; row < nrows(); ++row) {
1019 idx_type const i = 3 * row + 1;
1020 if (cell(i).size()) {
1021 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1022 cell(i).erase(1, cell(i).size());
1028 void InsetMathHull::changeCols(col_type cols)
1030 if (ncols() == cols)
1032 else if (ncols() < cols) {
1038 while (ncols() < cols)
1039 InsetMathGrid::addCol(ncols());
1045 for (row_type row = 0; row < nrows(); ++row) {
1046 idx_type const i = row * ncols();
1047 for (col_type col = cols; col < ncols(); ++col) {
1048 cell(i + cols - 1).append(cell(i + col));
1052 while (ncols() > cols) {
1053 InsetMathGrid::delCol(ncols() - 1);
1058 HullType InsetMathHull::getType() const
1064 void InsetMathHull::setType(HullType type)
1071 void InsetMathHull::mutate(HullType newtype)
1073 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1075 // we try to move along the chain
1076 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1078 // +-------------------------------------+
1079 // we use eqnarray as intermediate type for mutations that are not
1080 // directly supported because it handles labels and numbering for
1083 if (newtype == type_) {
1087 else if (newtype < hullNone) {
1092 else if (type_ == hullNone) {
1093 setType(hullSimple);
1098 else if (type_ == hullSimple) {
1099 if (newtype == hullNone) {
1103 setType(hullEquation);
1104 numbered(0, label_[0] ? true : false);
1109 else if (type_ == hullEquation) {
1110 if (newtype < type_) {
1111 setType(hullSimple);
1114 } else if (newtype == hullEqnArray) {
1115 // split it "nicely" on the first relop
1117 setType(hullEqnArray);
1118 } else if (newtype == hullMultline || newtype == hullGather) {
1121 // split it "nicely"
1128 else if (type_ == hullEqnArray) {
1129 if (newtype < type_) {
1132 } else { // align & Co.
1139 else if (type_ == hullAlign || type_ == hullAlignAt ||
1140 type_ == hullXAlignAt || type_ == hullFlAlign) {
1141 if (newtype < hullAlign) {
1143 setType(hullEqnArray);
1145 } else if (newtype == hullGather || newtype == hullMultline) {
1148 } else if (newtype == hullXXAlignAt) {
1149 for (row_type row = 0; row < nrows(); ++row)
1150 numbered(row, false);
1157 else if (type_ == hullXXAlignAt) {
1158 for (row_type row = 0; row < nrows(); ++row)
1159 numbered(row, false);
1160 if (newtype < hullAlign) {
1162 setType(hullEqnArray);
1164 } else if (newtype == hullGather || newtype == hullMultline) {
1172 else if (type_ == hullMultline || type_ == hullGather) {
1173 if (newtype == hullGather || newtype == hullMultline)
1175 else if (newtype == hullAlign || newtype == hullFlAlign ||
1176 newtype == hullAlignAt || newtype == hullXAlignAt) {
1179 } else if (newtype == hullXXAlignAt) {
1181 for (row_type row = 0; row < nrows(); ++row)
1182 numbered(row, false);
1186 setType(hullEqnArray);
1192 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1193 << "' to '" << to_utf8(hullName(newtype))
1194 << "' not implemented" << endl;
1199 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1200 bool last_eoln) const
1203 if (numberedType()) {
1204 if (label_[row] && numbered_[row]) {
1205 docstring const name =
1206 latex ? escape(label_[row]->getParam("name"))
1207 : label_[row]->getParam("name");
1208 res += "\\label{" + name + '}';
1210 if (!numbered_[row] && (type_ != hullMultline))
1211 res += "\\nonumber ";
1213 // Never add \\ on the last empty line of eqnarray and friends
1215 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1219 void InsetMathHull::write(WriteStream & os) const
1221 ModeSpecifier specifier(os, MATH_MODE);
1223 InsetMathGrid::write(os);
1228 void InsetMathHull::normalize(NormalStream & os) const
1230 os << "[formula " << hullName(type_) << ' ';
1231 InsetMathGrid::normalize(os);
1236 void InsetMathHull::infoize(odocstream & os) const
1238 os << "Type: " << hullName(type_);
1242 void InsetMathHull::check() const
1244 LASSERT(numbered_.size() == nrows(), /**/);
1245 LASSERT(numbers_.size() == nrows(), /**/);
1246 LASSERT(label_.size() == nrows(), /**/);
1250 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1254 idocstringstream iss(func.argument());
1255 iss >> dlang >> extra;
1257 extra = from_ascii("noextra");
1258 string const lang = to_ascii(dlang);
1260 // FIXME: temporarily disabled
1261 //if (cur.selection()) {
1264 // lyxerr << "use selection: " << ar << endl;
1265 // insert(pipeThroughExtern(lang, extra, ar));
1269 // only inline, display or eqnarray math is allowed
1270 if (getType() > hullEqnArray) {
1271 frontend::Alert::warning(_("Bad math environment"),
1272 _("Computation cannot be performed for AMS "
1273 "math environments.\nChange the math "
1274 "formula type and try again."));
1279 eq.push_back(MathAtom(new InsetMathChar('=')));
1281 // go to first item in line
1282 cur.idx() -= cur.idx() % ncols();
1285 if (getType() == hullSimple) {
1286 size_type pos = cur.cell().find_last(eq);
1288 if (cur.inMathed() && cur.selection()) {
1289 asArray(grabAndEraseSelection(cur), ar);
1290 } else if (pos == cur.cell().size()) {
1292 lyxerr << "use whole cell: " << ar << endl;
1294 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1295 lyxerr << "use partial cell form pos: " << pos << endl;
1297 cur.cell().append(eq);
1298 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1299 cur.pos() = cur.lastpos();
1303 if (getType() == hullEquation) {
1304 lyxerr << "use equation inset" << endl;
1305 mutate(hullEqnArray);
1306 MathData & ar = cur.cell();
1307 lyxerr << "use cell: " << ar << endl;
1311 cur.cell() = pipeThroughExtern(lang, extra, ar);
1312 // move to end of line
1313 cur.pos() = cur.lastpos();
1318 lyxerr << "use eqnarray" << endl;
1319 cur.idx() += 2 - cur.idx() % ncols();
1321 MathData ar = cur.cell();
1322 lyxerr << "use cell: " << ar << endl;
1323 // FIXME: temporarily disabled
1329 cur.cell() = pipeThroughExtern(lang, extra, ar);
1330 cur.pos() = cur.lastpos();
1335 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1337 //lyxerr << "action: " << cmd.action() << endl;
1338 switch (cmd.action()) {
1340 case LFUN_FINISHED_BACKWARD:
1341 case LFUN_FINISHED_FORWARD:
1342 case LFUN_FINISHED_RIGHT:
1343 case LFUN_FINISHED_LEFT:
1344 //lyxerr << "action: " << cmd.action() << endl;
1345 InsetMathGrid::doDispatch(cur, cmd);
1349 case LFUN_BREAK_PARAGRAPH:
1350 // just swallow this
1353 case LFUN_NEWLINE_INSERT:
1354 // some magic for the common case
1355 if (type_ == hullSimple || type_ == hullEquation) {
1356 cur.recordUndoInset();
1358 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1359 mutate(align ? hullAlign : hullEqnArray);
1360 // mutate() may change labels and such.
1361 cur.forceBufferUpdate();
1362 cur.idx() = nrows() * ncols() - 1;
1363 cur.pos() = cur.lastpos();
1365 InsetMathGrid::doDispatch(cur, cmd);
1368 case LFUN_MATH_NUMBER_TOGGLE: {
1369 //lyxerr << "toggling all numbers" << endl;
1370 cur.recordUndoInset();
1371 bool old = numberedType();
1372 if (type_ == hullMultline)
1373 numbered(nrows() - 1, !old);
1375 for (row_type row = 0; row < nrows(); ++row)
1376 numbered(row, !old);
1378 cur.message(old ? _("No number") : _("Number"));
1379 cur.forceBufferUpdate();
1383 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1384 cur.recordUndoInset();
1385 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1386 bool old = numbered(r);
1387 cur.message(old ? _("No number") : _("Number"));
1389 cur.forceBufferUpdate();
1393 case LFUN_LABEL_INSERT: {
1394 cur.recordUndoInset();
1395 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1396 docstring old_label = label(r);
1397 docstring const default_label = from_ascii("eq:");
1398 if (old_label.empty())
1399 old_label = default_label;
1401 InsetCommandParams p(LABEL_CODE);
1402 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1403 string const data = InsetCommand::params2string(p);
1405 if (cmd.argument().empty())
1406 cur.bv().showDialog("label", data);
1408 FuncRequest fr(LFUN_INSET_INSERT, data);
1414 case LFUN_LABEL_COPY_AS_REF: {
1416 if (cmd.argument().empty() && &cur.inset() == this)
1417 // if there is no argument and we're inside math, we retrieve
1418 // the row number from the cursor position.
1419 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1421 // if there is an argument, find the corresponding label, else
1422 // check whether there is at least one label.
1423 for (row = 0; row != nrows(); ++row)
1424 if (numbered_[row] && label_[row]
1425 && (cmd.argument().empty() || label(row) == cmd.argument()))
1432 InsetCommandParams p(REF_CODE, "ref");
1433 p["reference"] = label(row);
1434 cap::clearSelection();
1435 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1439 case LFUN_WORD_DELETE_FORWARD:
1440 case LFUN_CHAR_DELETE_FORWARD:
1441 if (col(cur.idx()) + 1 == ncols()
1442 && cur.pos() == cur.lastpos()
1443 && !cur.selection()) {
1444 if (!label(row(cur.idx())).empty()) {
1445 cur.recordUndoInset();
1446 label(row(cur.idx()), docstring());
1447 } else if (numbered(row(cur.idx()))) {
1448 cur.recordUndoInset();
1449 numbered(row(cur.idx()), false);
1450 cur.forceBufferUpdate();
1452 InsetMathGrid::doDispatch(cur, cmd);
1456 InsetMathGrid::doDispatch(cur, cmd);
1461 case LFUN_INSET_INSERT: {
1462 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1463 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1464 string const name = cmd.getArg(0);
1465 if (name == "label") {
1466 InsetCommandParams p(LABEL_CODE);
1467 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1468 docstring str = p["name"];
1469 cur.recordUndoInset();
1470 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1474 docstring old = label(r);
1477 // The label will take care of the reference update.
1481 // Newly created inset so initialize it.
1482 label_[r]->initView();
1485 cur.forceBufferUpdate();
1488 InsetMathGrid::doDispatch(cur, cmd);
1492 case LFUN_MATH_EXTERN:
1493 cur.recordUndoInset();
1497 case LFUN_MATH_MUTATE: {
1498 cur.recordUndoInset();
1499 row_type row = cur.row();
1500 col_type col = cur.col();
1501 mutate(hullType(cmd.argument()));
1502 cur.idx() = row * ncols() + col;
1503 if (cur.idx() > cur.lastidx()) {
1504 cur.idx() = cur.lastidx();
1505 cur.pos() = cur.lastpos();
1507 if (cur.pos() > cur.lastpos())
1508 cur.pos() = cur.lastpos();
1510 cur.forceBufferUpdate();
1511 // FIXME: find some more clever handling of the selection,
1512 // i.e. preserve it.
1513 cur.clearSelection();
1514 //cur.dispatched(FINISHED);
1518 case LFUN_MATH_DISPLAY: {
1519 cur.recordUndoInset();
1520 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1522 cur.pos() = cur.lastpos();
1523 //cur.dispatched(FINISHED);
1528 InsetMathGrid::doDispatch(cur, cmd);
1534 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1535 FuncStatus & status) const
1537 switch (cmd.action()) {
1538 case LFUN_FINISHED_BACKWARD:
1539 case LFUN_FINISHED_FORWARD:
1540 case LFUN_FINISHED_RIGHT:
1541 case LFUN_FINISHED_LEFT:
1544 case LFUN_NEWLINE_INSERT:
1545 case LFUN_MATH_EXTERN:
1547 status.setEnabled(true);
1550 // we never allow this in math, and we want to bind enter
1551 // to another actions in command-alternatives
1552 case LFUN_BREAK_PARAGRAPH:
1553 status.setEnabled(false);
1555 case LFUN_MATH_MUTATE: {
1556 HullType const ht = hullType(cmd.argument());
1557 status.setOnOff(type_ == ht);
1558 status.setEnabled(true);
1560 if (ht != hullSimple) {
1561 Cursor tmpcur = cur;
1562 while (!tmpcur.empty()) {
1563 InsetCode code = tmpcur.inset().lyxCode();
1564 if (code == BOX_CODE) {
1566 } else if (code == TABULAR_CODE) {
1567 FuncRequest tmpcmd(LFUN_MATH_DISPLAY);
1568 if (tmpcur.getStatus(tmpcmd, status) && !status.enabled())
1576 case LFUN_MATH_DISPLAY: {
1578 if (cur.depth() > 1) {
1579 Inset const & in = cur[cur.depth()-2].inset();
1580 if (in.lyxCode() == SCRIPT_CODE)
1581 enable = display() != Inline;
1583 status.setEnabled(enable);
1587 case LFUN_MATH_NUMBER_TOGGLE:
1588 // FIXME: what is the right test, this or the one of
1590 status.setEnabled(display() != Inline);
1591 status.setOnOff(numberedType());
1594 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1595 // FIXME: what is the right test, this or the one of
1597 bool const enable = (type_ == hullMultline)
1598 ? (nrows() - 1 == cur.row())
1599 : display() != Inline;
1600 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1601 status.setEnabled(enable);
1602 status.setOnOff(enable && numbered(r));
1606 case LFUN_LABEL_INSERT:
1607 status.setEnabled(type_ != hullSimple);
1610 case LFUN_LABEL_COPY_AS_REF: {
1611 bool enabled = false;
1613 if (cmd.argument().empty() && &cur.inset() == this) {
1614 // if there is no argument and we're inside math, we retrieve
1615 // the row number from the cursor position.
1616 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1617 enabled = numberedType() && label_[row] && numbered_[row];
1619 // if there is an argument, find the corresponding label, else
1620 // check whether there is at least one label.
1621 for (row_type row = 0; row != nrows(); ++row) {
1622 if (numbered_[row] && label_[row] &&
1623 (cmd.argument().empty() || label(row) == cmd.argument())) {
1629 status.setEnabled(enabled);
1633 case LFUN_INSET_INSERT:
1634 if (cmd.getArg(0) == "label") {
1635 status.setEnabled(type_ != hullSimple);
1638 return InsetMathGrid::getStatus(cur, cmd, status);
1640 case LFUN_INSET_MODIFY: {
1641 istringstream is(to_utf8(cmd.argument()));
1645 return InsetMathGrid::getStatus(cur, cmd, status);
1648 && (s == "append-row"
1649 || s == "delete-row"
1650 || s == "copy-row")) {
1651 status.message(bformat(
1652 from_utf8(N_("Can't change number of rows in '%1$s'")),
1654 status.setEnabled(false);
1658 && (s == "append-column"
1659 || s == "delete-column"
1660 || s == "copy-column")) {
1661 status.message(bformat(
1662 from_utf8(N_("Can't change number of columns in '%1$s'")),
1664 status.setEnabled(false);
1667 if ((type_ == hullSimple
1668 || type_ == hullEquation
1669 || type_ == hullNone) &&
1670 (s == "add-hline-above" || s == "add-hline-below")) {
1671 status.message(bformat(
1672 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1674 status.setEnabled(false);
1677 if (s == "add-vline-left" || s == "add-vline-right") {
1678 status.message(bformat(
1679 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1681 status.setEnabled(false);
1684 if (s == "valign-top" || s == "valign-middle"
1685 || s == "valign-bottom" || s == "align-left"
1686 || s == "align-center" || s == "align-right") {
1687 status.setEnabled(false);
1690 return InsetMathGrid::getStatus(cur, cmd, status);
1694 return InsetMathGrid::getStatus(cur, cmd, status);
1697 // This cannot really happen, but inserted to shut-up gcc
1698 return InsetMathGrid::getStatus(cur, cmd, status);
1702 /////////////////////////////////////////////////////////////////////
1706 // simply scrap this function if you want
1707 void InsetMathHull::mutateToText()
1710 // translate to latex
1712 latex(os, false, false);
1713 string str = os.str();
1716 Text * lt = view_->cursor().innerText();
1717 string::const_iterator cit = str.begin();
1718 string::const_iterator end = str.end();
1719 for (; cit != end; ++cit)
1720 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1723 //dispatch(LFUN_ESCAPE);
1728 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1729 docstring const & font)
1731 // this whole function is a hack and won't work for incremental font
1734 if (cur.inset().asInsetMath()->name() == font)
1735 cur.handleFont(to_utf8(font));
1737 cur.handleNest(createInsetMath(font, cur.buffer()));
1743 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1748 font.fromString(to_utf8(arg), b);
1749 if (font.fontInfo().color() != Color_inherit) {
1750 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1751 cur.handleNest(at, 0);
1756 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1759 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1760 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1761 enter_front ? idxFirst(cur) : idxLast(cur);
1762 // The inset formula dimension is not necessarily the same as the
1763 // one of the instant preview image, so we have to indicate to the
1764 // BufferView that a metrics update is needed.
1765 cur.screenUpdateFlags(Update::Force);
1769 void InsetMathHull::revealCodes(Cursor & cur) const
1771 if (!cur.inMathed())
1773 odocstringstream os;
1775 cur.message(os.str());
1777 // write something to the minibuffer
1778 // translate to latex
1782 string str = os.str();
1784 string::size_type pos = 0;
1786 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1789 else if (*it == '\0') {
1791 pos = it - str.begin();
1797 res = res.substr(pos - 30);
1798 if (res.size() > 60)
1799 res = res.substr(0, 60);
1805 /////////////////////////////////////////////////////////////////////
1809 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1812 // FIXME: completely broken
1813 static InsetMathHull * lastformula = 0;
1814 static CursorBase current = DocIterator(ibegin(nucleus()));
1816 static string laststr;
1818 if (lastformula != this || laststr != str) {
1819 //lyxerr << "reset lastformula to " << this << endl;
1822 current = ibegin(nucleus());
1824 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1828 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1830 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1831 CursorSlice & top = it.back();
1832 MathData const & a = top.asInsetMath()->cell(top.idx_);
1833 if (a.matchpart(ar, top.pos_)) {
1834 bv->cursor().setSelection(it, ar.size());
1836 top.pos_ += ar.size();
1842 //lyxerr << "not found!" << endl;
1849 void InsetMathHull::write(ostream & os) const
1851 odocstringstream oss;
1852 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1855 os << to_utf8(oss.str());
1859 void InsetMathHull::read(Lexer & lex)
1862 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1863 operator=(*at->asHullInset());
1867 bool InsetMathHull::readQuiet(Lexer & lex)
1870 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1872 operator=(*at->asHullInset());
1877 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1879 // disables ASCII-art for export of equations. See #2275.
1880 if (0 && display()) {
1884 TextPainter tpain(dim.width(), dim.height());
1885 drawT(tpain, 0, dim.ascent());
1887 // reset metrics cache to "real" values
1889 return tpain.textheight();
1891 odocstringstream oss;
1892 Encoding const * const enc = encodings.fromLyXName("utf8");
1893 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1895 if (type_ == hullRegexp)
1899 docstring const str = oss.str();
1906 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1911 if (getType() == hullSimple)
1912 name = from_ascii("inlineequation");
1914 name = from_ascii("informalequation");
1916 docstring bname = name;
1917 if (!label(0).empty())
1918 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1920 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1922 odocstringstream ls;
1923 if (runparams.flavor == OutputParams::XML) {
1924 ms << MTag("alt role='tex' ");
1925 // Workaround for db2latex: db2latex always includes equations with
1926 // \ensuremath{} or \begin{display}\end{display}
1927 // so we strip LyX' math environment
1928 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1929 InsetMathGrid::write(wi);
1930 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1935 InsetMathGrid::mathmlize(ms);
1940 otexstream ols(ls, texrow);
1941 ms << MTag("alt role='tex'");
1942 latex(ols, runparams);
1943 res = texrow.rows();
1944 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1948 ms << from_ascii("<graphic fileref=\"eqn/");
1949 if (!label(0).empty())
1950 ms << sgml::cleanID(buffer(), runparams, label(0));
1952 ms << sgml::uniqueID(from_ascii("anon"));
1954 if (runparams.flavor == OutputParams::XML)
1955 ms << from_ascii("\"/>");
1957 ms << from_ascii("\">");
1959 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1961 return ms.line() + res;
1965 bool InsetMathHull::haveNumbers() const
1967 bool havenumbers = false;
1968 // inline formulas are never numbered (bug 7351 part 3)
1969 if (getType() == hullSimple)
1971 for (size_t i = 0; i != numbered_.size(); ++i) {
1982 // We need to do something about alignment here.
1984 // This duplicates code from InsetMathGrid, but
1985 // we need access here to number information,
1986 // and we simply do not have that in InsetMathGrid.
1987 void InsetMathHull::htmlize(HtmlStream & os) const
1989 bool const havenumbers = haveNumbers();
1990 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
1993 os << cell(index(0, 0));
1997 os << MTag("table", "class='mathtable'");
1998 for (row_type row = 0; row < nrows(); ++row) {
2000 for (col_type col = 0; col < ncols(); ++col) {
2002 os << cell(index(row, col));
2007 docstring const & num = numbers_[row];
2009 os << '(' << num << ')';
2014 os << ETag("table");
2018 // this duplicates code from InsetMathGrid, but
2019 // we need access here to number information,
2020 // and we simply do not have that in InsetMathGrid.
2021 void InsetMathHull::mathmlize(MathStream & os) const
2023 bool const havenumbers = haveNumbers();
2024 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2027 os << MTag("mtable");
2028 char const * const celltag = havetable ? "mtd" : "mrow";
2029 // FIXME There does not seem to be wide support at the moment
2030 // for mlabeledtr, so we have to use just mtr for now.
2031 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2032 char const * const rowtag = "mtr";
2033 for (row_type row = 0; row < nrows(); ++row) {
2036 for (col_type col = 0; col < ncols(); ++col) {
2038 << cell(index(row, col))
2044 docstring const & num = numbers_[row];
2046 os << '(' << num << ')';
2053 os << ETag("mtable");
2057 void InsetMathHull::mathAsLatex(WriteStream & os) const
2059 MathEnsurer ensurer(os, false);
2060 bool havenumbers = haveNumbers();
2061 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2064 os << cell(index(0, 0));
2068 os << "<table class='mathtable'>";
2069 for (row_type row = 0; row < nrows(); ++row) {
2071 for (col_type col = 0; col < ncols(); ++col) {
2072 os << "<td class='math'>";
2073 os << cell(index(row, col));
2078 docstring const & num = numbers_[row];
2080 os << '(' << num << ')';
2089 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2091 BufferParams::MathOutput const mathtype =
2092 buffer().params().html_math_output;
2094 bool success = false;
2096 // we output all the labels just at the beginning of the equation.
2097 // this should be fine.
2098 for (size_t i = 0; i != label_.size(); ++i) {
2099 InsetLabel const * const il = label_[i];
2105 // FIXME Eventually we would like to do this inset by inset.
2106 if (mathtype == BufferParams::MathML) {
2107 odocstringstream os;
2112 } catch (MathExportException const &) {}
2114 if (getType() == hullSimple)
2115 xs << html::StartTag("math",
2116 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2118 xs << html::StartTag("math",
2119 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2120 xs << XHTMLStream::ESCAPE_NONE
2122 << html::EndTag("math");
2124 } else if (mathtype == BufferParams::HTML) {
2125 odocstringstream os;
2130 } catch (MathExportException const &) {}
2132 string const tag = (getType() == hullSimple) ? "span" : "div";
2133 xs << html::StartTag(tag, "class='formula'", true)
2134 << XHTMLStream::ESCAPE_NONE
2136 << html::EndTag(tag);
2140 // what we actually want is this:
2142 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2144 // || mathtype == BufferParams::Images
2146 // but what follows is equivalent, since we'll enter only if either (a) we
2147 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2148 // aren't doing LaTeX, in which case we are doing Images.
2149 if (!success && mathtype != BufferParams::LaTeX) {
2150 graphics::PreviewImage const * pimage = 0;
2152 loadPreview(docit_);
2153 pimage = preview_->getPreviewImage(buffer());
2154 // FIXME Do we always have png?
2157 if (pimage || op.dryrun) {
2158 string const filename = pimage ? pimage->filename().onlyFileName()
2159 : "previewimage.png";
2161 // if we are not in the master buffer, then we need to see that the
2162 // generated image is copied there; otherwise, preview fails.
2163 Buffer const * mbuf = buffer().masterBuffer();
2164 if (mbuf != &buffer()) {
2165 string mbtmp = mbuf->temppath();
2166 FileName const mbufimg(support::addName(mbtmp, filename));
2167 pimage->filename().copyTo(mbufimg);
2169 // add the file to the list of files to be exported
2170 op.exportdata->addExternalFile("xhtml", pimage->filename());
2173 string const tag = (getType() == hullSimple) ? "span" : "div";
2175 << html::StartTag(tag)
2176 << html::CompTag("img", "src=\"" + filename + "\"")
2177 << html::EndTag(tag)
2183 // so we'll pass this test if we've failed everything else, or
2184 // if mathtype was LaTeX, since we won't have entered any of the
2186 if (!success /* || mathtype != BufferParams::LaTeX */) {
2187 // Unfortunately, we cannot use latexString() because we do not want
2188 // $...$ or whatever.
2189 odocstringstream ls;
2190 WriteStream wi(ls, false, true, WriteStream::wsPreview);
2191 ModeSpecifier specifier(wi, MATH_MODE);
2193 docstring const latex = ls.str();
2195 // class='math' allows for use of jsMath
2196 // http://www.math.union.edu/~dpvc/jsMath/
2198 // probably should allow for some kind of customization here
2199 string const tag = (getType() == hullSimple) ? "span" : "div";
2200 xs << html::StartTag(tag, "class='math'")
2202 << html::EndTag(tag)
2209 void InsetMathHull::toString(odocstream & os) const
2211 plaintext(os, OutputParams(0));
2215 void InsetMathHull::forToc(docstring & os, size_t) const
2217 odocstringstream ods;
2218 plaintext(ods, OutputParams(0));
2223 docstring InsetMathHull::contextMenuName() const
2225 return from_ascii("context-math");
2229 void InsetMathHull::recordLocation(DocIterator const & di)