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();
249 buffer_->masterBuffer()->params().documentClass().counters();
251 // right now, we only need to do this at export time
252 if (utype == OutputUpdate) {
253 for (size_t i = 0; i < numcnts; ++i) {
254 docstring const cnt = from_ascii(counters_to_save[i]);
255 if (cnts.hasCounter(cnt))
256 counter_map[cnt] = cnts.value(cnt);
260 // this has to be done separately
261 docstring const eqstr = from_ascii("equation");
262 if (cnts.hasCounter(eqstr)) {
263 if (utype == OutputUpdate)
264 counter_map[eqstr] = cnts.value(eqstr);
265 for (size_t i = 0; i != label_.size(); ++i) {
267 cnts.step(eqstr, utype);
268 numbers_[i] = cnts.theCounter(eqstr, lang);
270 numbers_[i] = empty_docstring();
276 for (size_t i = 0; i != label_.size(); ++i) {
278 label_[i]->updateBuffer(it, utype);
281 InsetMathGrid::updateBuffer(it, utype);
285 void InsetMathHull::addToToc(DocIterator const & pit) const
288 //FIXME: buffer_ should be set at creation for this inset! Problem is
289 // This inset is created at too many places (see Parser::parse1() in
294 Toc & toc = buffer().tocBackend().toc("equation");
296 for (row_type row = 0; row != nrows(); ++row) {
300 label_[row]->addToToc(pit);
301 toc.push_back(TocItem(pit, 0, nicelabel(row)));
306 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
312 return InsetMathNest::editXY(cur, x, y);
316 InsetMath::mode_type InsetMathHull::currentMode() const
318 if (type_ == hullNone)
319 return UNDECIDED_MODE;
320 // definitely math mode ...
325 bool InsetMathHull::idxFirst(Cursor & cur) const
333 bool InsetMathHull::idxLast(Cursor & cur) const
335 cur.idx() = nargs() - 1;
336 cur.pos() = cur.lastpos();
341 char InsetMathHull::defaultColAlign(col_type col)
343 if (type_ == hullEqnArray)
345 if (type_ == hullGather)
347 if (type_ >= hullAlign)
348 return "rl"[col & 1];
353 int InsetMathHull::defaultColSpace(col_type col)
355 if (type_ == hullAlign || type_ == hullAlignAt)
357 if (type_ == hullXAlignAt)
358 return (col & 1) ? 20 : 0;
359 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
360 return (col & 1) ? 40 : 0;
365 docstring InsetMathHull::standardFont() const
370 font_name = from_ascii("texttt");
373 font_name = from_ascii("lyxnochange");
376 font_name = from_ascii("mathnormal");
382 ColorCode InsetMathHull::standardColor() const
388 color = Color_foreground;
397 bool InsetMathHull::previewState(BufferView * bv) const
399 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
400 graphics::PreviewImage const * pimage =
401 preview_->getPreviewImage(bv->buffer());
402 return pimage && pimage->image();
408 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
410 if (previewState(mi.base.bv)) {
411 preview_->metrics(mi, dim);
412 // insert a one pixel gap in front of the formula
415 dim.des += displayMargin();
416 // Cache the inset dimension.
417 setDimCache(mi, dim);
421 FontSetChanger dummy1(mi.base, standardFont());
422 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
424 // let the cells adjust themselves
425 InsetMathGrid::metrics(mi, dim);
428 dim.asc += displayMargin();
429 dim.des += displayMargin();
432 if (numberedType()) {
433 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
435 for (row_type row = 0; row < nrows(); ++row)
436 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
442 // make it at least as high as the current font
445 math_font_max_dim(mi.base.font, asc, des);
446 dim.asc = max(dim.asc, asc);
447 dim.des = max(dim.des, des);
448 // Cache the inset dimension.
449 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
450 setDimCache(mi, dim);
454 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
456 if (previewState(pi.base.bv))
457 return graphics::PreviewLoader::backgroundColor();
462 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
464 Dimension const dim = dimension(*pi.base.bv);
465 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
466 dim.asc + dim.des - 1, pi.backgroundColor(this));
470 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
472 use_preview_ = previewState(pi.base.bv);
474 if (type_ == hullRegexp) {
475 Dimension const dim = dimension(*pi.base.bv);
476 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
477 dim.width() - 2, dim.height() - 2, Color_regexpframe);
480 // one pixel gap in front
481 preview_->draw(pi, x + 1, y);
482 setPosCache(pi, x, y);
486 ColorCode color = pi.selected && lyxrc.use_system_colors
487 ? Color_selectiontext : standardColor();
488 bool const really_change_color = pi.base.font.color() == Color_none;
489 ColorChanger dummy0(pi.base.font, color, really_change_color);
490 FontSetChanger dummy1(pi.base, standardFont());
491 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
493 InsetMathGrid::draw(pi, x + 1, y);
495 if (numberedType()) {
496 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
497 for (row_type row = 0; row < nrows(); ++row) {
498 int const yy = y + rowinfo_[row].offset_;
499 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
500 docstring const nl = nicelabel(row);
504 setPosCache(pi, x, y);
508 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
511 InsetMathGrid::metricsT(mi, dim);
514 WriteStream wi(os, false, true, WriteStream::wsDefault);
516 dim.wid = os.str().size();
523 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
526 InsetMathGrid::drawT(pain, x, y);
529 WriteStream wi(os, false, true, WriteStream::wsDefault);
531 pain.draw(x, y, os.str().c_str());
536 static docstring latexString(InsetMathHull const & inset)
539 // This has to be static, because a preview snippet or a math
540 // macro containing math in text mode (such as $\text{$\phi$}$ or
541 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
542 // first time as a whole, and the second time only the inner math.
543 // In this last case inset.buffer() would be invalid.
544 static Encoding const * encoding = 0;
545 if (inset.isBufferValid())
546 encoding = &(inset.buffer().params().encoding());
547 WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
553 void InsetMathHull::initUnicodeMath() const
555 // Trigger classification of the unicode symbols in this inset
556 docstring const dummy = latexString(*this);
560 void InsetMathHull::addPreview(DocIterator const & inset_pos,
561 graphics::PreviewLoader & /*ploader*/) const
563 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
564 preparePreview(inset_pos);
569 void InsetMathHull::preparePreview(DocIterator const & pos,
570 bool forexport) const
572 // there is no need to do all the macro stuff if we're not
573 // actually going to generate the preview.
574 if (RenderPreview::status() != LyXRC::PREVIEW_ON && !forexport)
577 Buffer const * buffer = pos.buffer();
579 // collect macros at this position
581 buffer->listMacroNames(macros);
582 MacroNameSet::iterator it = macros.begin();
583 MacroNameSet::iterator end = macros.end();
584 odocstringstream macro_preamble;
585 for (; it != end; ++it) {
586 MacroData const * data = buffer->getMacro(*it, pos, true);
588 data->write(macro_preamble, true);
589 macro_preamble << endl;
594 if (forexport && haveNumbers()) {
595 docstring eqstr = from_ascii("equation");
596 CounterMap::const_iterator it = counter_map.find(eqstr);
597 if (it != counter_map.end()) {
598 int num = it->second;
600 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
601 '{' + convert<docstring>(num) + '}' + '\n';
603 for (size_t i = 0; i != numcnts; ++i) {
604 docstring cnt = from_ascii(counters_to_save[i]);
605 it = counter_map.find(cnt);
606 if (it == counter_map.end())
608 int num = it->second;
610 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
611 '{' + convert<docstring>(num) + '}';
614 docstring const snippet = macro_preamble.str() +
615 setcnt + latexString(*this);
616 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
617 preview_->addPreview(snippet, *buffer, forexport);
621 void InsetMathHull::reloadPreview(DocIterator const & pos) const
624 preview_->startLoading(*pos.buffer());
628 void InsetMathHull::loadPreview(DocIterator const & pos) const
630 bool const forexport = true;
631 preparePreview(pos, forexport);
632 preview_->startLoading(*pos.buffer(), forexport);
636 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
638 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
640 cur.screenUpdateFlags(Update::Force);
646 docstring InsetMathHull::label(row_type row) const
648 LASSERT(row < nrows(), /**/);
649 if (InsetLabel * il = label_[row])
650 return il->screenLabel();
655 void InsetMathHull::label(row_type row, docstring const & label)
657 //lyxerr << "setting label '" << label << "' for row " << row << endl;
661 label_[row] = dummy_pointer;
664 label_[row]->updateCommand(label);
666 label_[row]->setParam("name", label);
670 InsetCommandParams p(LABEL_CODE);
672 label_[row] = new InsetLabel(buffer_, p);
674 label_[row]->setBuffer(buffer());
678 void InsetMathHull::numbered(row_type row, bool num)
680 numbered_[row] = num;
681 if (!numbered_[row] && label_[row]) {
688 bool InsetMathHull::numbered(row_type row) const
690 return numbered_[row];
694 bool InsetMathHull::ams() const
696 return type_ == hullAlign
697 || type_ == hullFlAlign
698 || type_ == hullMultline
699 || type_ == hullGather
700 || type_ == hullAlignAt
701 || type_ == hullXAlignAt
702 || type_ == hullXXAlignAt;
706 Inset::DisplayType InsetMathHull::display() const
708 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
713 bool InsetMathHull::numberedType() const
715 if (type_ == hullNone)
717 if (type_ == hullSimple)
719 if (type_ == hullXXAlignAt)
721 if (type_ == hullRegexp)
723 for (row_type row = 0; row < nrows(); ++row)
730 void InsetMathHull::validate(LaTeXFeatures & features) const
732 if (features.runparams().isLaTeX()) {
734 features.require("amsmath");
736 if (type_ == hullRegexp) {
737 features.require("color");
738 string frcol = lcolor.getLaTeXName(Color_regexpframe);
739 string bgcol = "white";
740 features.addPreambleSnippet(
741 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
742 + frcol + string("}{")
743 + bgcol + string("}{\\texttt{#1}}}"));
746 // Validation is necessary only if not using AMS math.
747 // To be safe, we will always run mathedvalidate.
748 //if (features.amsstyle)
751 //features.binom = true;
752 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
753 // it would be better to do this elsewhere, but we can't validate in
754 // InsetMathMatrix and we have no way, outside MathExtern, to know if
755 // we even have any matrices.
756 features.addPreambleSnippet("<style type=\"text/css\">\n"
757 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
758 "table.matrix td{padding: 0.25px;}\n"
759 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
760 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}\n"
763 InsetMathGrid::validate(features);
767 void InsetMathHull::header_write(WriteStream & os) const
769 bool n = numberedType();
783 os << "\n\\begin{equation" << star(n) << "}\n";
793 os << "\n\\begin{" << hullName(type_) << star(n) << "}\n";
798 os << "\n\\begin{" << hullName(type_) << star(n) << '}'
799 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
803 os << "\n\\begin{" << hullName(type_) << '}'
804 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
812 os << "\n\\begin{unknown" << star(n) << "}\n";
818 void InsetMathHull::footer_write(WriteStream & os) const
820 bool n = numberedType();
833 os << "\n\\end{equation" << star(n) << "}\n";
845 os << "\n\\end{" << hullName(type_) << star(n) << "}\n";
849 os << "\n\\end{" << hullName(type_) << "}\n";
857 os << "\n\\end{unknown" << star(n) << "}\n";
863 bool InsetMathHull::rowChangeOK() const
866 type_ == hullEqnArray || type_ == hullAlign ||
867 type_ == hullFlAlign || type_ == hullAlignAt ||
868 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
869 type_ == hullGather || type_ == hullMultline;
873 bool InsetMathHull::colChangeOK() const
876 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
877 type_ == hullXAlignAt || type_ == hullXXAlignAt;
881 void InsetMathHull::addRow(row_type row)
886 bool numbered = numberedType();
888 if (type_ == hullMultline) {
889 if (row + 1 == nrows()) {
890 numbered_[row] = false;
896 numbered_.insert(numbered_.begin() + row + 1, numbered);
897 numbers_.insert(numbers_.begin() + row + 1, empty_docstring());
898 label_.insert(label_.begin() + row + 1, dummy_pointer);
901 InsetMathGrid::addRow(row);
905 void InsetMathHull::swapRow(row_type row)
909 if (row + 1 == nrows())
911 // gcc implements the standard std::vector<bool> which is *not* a container:
912 // http://www.gotw.ca/publications/N1185.pdf
913 // As a results, it doesn't like this:
914 // swap(numbered_[row], numbered_[row + 1]);
915 // so we do it manually:
916 bool const b = numbered_[row];
917 numbered_[row] = numbered_[row + 1];
918 numbered_[row + 1] = b;
919 swap(numbers_[row], numbers_[row + 1]);
920 swap(label_[row], label_[row + 1]);
921 InsetMathGrid::swapRow(row);
925 void InsetMathHull::delRow(row_type row)
927 if (nrows() <= 1 || !rowChangeOK())
929 if (row + 1 == nrows() && type_ == hullMultline) {
930 bool const b = numbered_[row - 1];
931 numbered_[row - 1] = numbered_[row];
933 swap(numbers_[row - 1], numbers_[row]);
934 swap(label_[row - 1], label_[row]);
935 InsetMathGrid::delRow(row);
938 InsetMathGrid::delRow(row);
939 // The last dummy row has no number info nor a label.
940 // Test nrows() + 1 because we have already erased the row.
941 if (row == nrows() + 1)
943 numbered_.erase(numbered_.begin() + row);
944 numbers_.erase(numbers_.begin() + row);
946 label_.erase(label_.begin() + row);
950 void InsetMathHull::addCol(col_type col)
954 InsetMathGrid::addCol(col);
958 void InsetMathHull::delCol(col_type col)
960 if (ncols() <= 1 || !colChangeOK())
962 InsetMathGrid::delCol(col);
966 docstring InsetMathHull::nicelabel(row_type row) const
970 docstring const & val = numbers_[row];
972 return '(' + val + ')';
973 return '(' + val + ',' + label_[row]->screenLabel() + ')';
977 void InsetMathHull::glueall(HullType type)
980 for (idx_type i = 0; i < nargs(); ++i)
982 InsetLabel * label = 0;
983 if (type == hullEquation) {
984 // preserve first non-empty label
985 for (row_type row = 0; row < nrows(); ++row) {
993 *this = InsetMathHull(buffer_, hullSimple);
1000 void InsetMathHull::splitTo2Cols()
1002 LASSERT(ncols() == 1, /**/);
1003 InsetMathGrid::addCol(1);
1004 for (row_type row = 0; row < nrows(); ++row) {
1005 idx_type const i = 2 * row;
1006 pos_type pos = firstRelOp(cell(i));
1007 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1008 cell(i).erase(pos, cell(i).size());
1013 void InsetMathHull::splitTo3Cols()
1015 LASSERT(ncols() < 3, /**/);
1018 InsetMathGrid::addCol(2);
1019 for (row_type row = 0; row < nrows(); ++row) {
1020 idx_type const i = 3 * row + 1;
1021 if (cell(i).size()) {
1022 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1023 cell(i).erase(1, cell(i).size());
1029 void InsetMathHull::changeCols(col_type cols)
1031 if (ncols() == cols)
1033 else if (ncols() < cols) {
1039 while (ncols() < cols)
1040 InsetMathGrid::addCol(ncols());
1046 for (row_type row = 0; row < nrows(); ++row) {
1047 idx_type const i = row * ncols();
1048 for (col_type col = cols; col < ncols(); ++col) {
1049 cell(i + cols - 1).append(cell(i + col));
1053 while (ncols() > cols) {
1054 InsetMathGrid::delCol(ncols() - 1);
1059 HullType InsetMathHull::getType() const
1065 void InsetMathHull::setType(HullType type)
1072 void InsetMathHull::mutate(HullType newtype)
1074 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1076 // we try to move along the chain
1077 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1079 // +-------------------------------------+
1080 // we use eqnarray as intermediate type for mutations that are not
1081 // directly supported because it handles labels and numbering for
1084 if (newtype == type_) {
1088 else if (newtype < hullNone) {
1093 else if (type_ == hullNone) {
1094 setType(hullSimple);
1099 else if (type_ == hullSimple) {
1100 if (newtype == hullNone) {
1104 setType(hullEquation);
1105 numbered(0, label_[0] ? true : false);
1110 else if (type_ == hullEquation) {
1111 if (newtype < type_) {
1112 setType(hullSimple);
1115 } else if (newtype == hullEqnArray) {
1116 // split it "nicely" on the first relop
1118 setType(hullEqnArray);
1119 } else if (newtype == hullMultline || newtype == hullGather) {
1122 // split it "nicely"
1129 else if (type_ == hullEqnArray) {
1130 if (newtype < type_) {
1133 } else { // align & Co.
1140 else if (type_ == hullAlign || type_ == hullAlignAt ||
1141 type_ == hullXAlignAt || type_ == hullFlAlign) {
1142 if (newtype < hullAlign) {
1144 setType(hullEqnArray);
1146 } else if (newtype == hullGather || newtype == hullMultline) {
1149 } else if (newtype == hullXXAlignAt) {
1150 for (row_type row = 0; row < nrows(); ++row)
1151 numbered(row, false);
1158 else if (type_ == hullXXAlignAt) {
1159 for (row_type row = 0; row < nrows(); ++row)
1160 numbered(row, false);
1161 if (newtype < hullAlign) {
1163 setType(hullEqnArray);
1165 } else if (newtype == hullGather || newtype == hullMultline) {
1173 else if (type_ == hullMultline || type_ == hullGather) {
1174 if (newtype == hullGather || newtype == hullMultline)
1176 else if (newtype == hullAlign || newtype == hullFlAlign ||
1177 newtype == hullAlignAt || newtype == hullXAlignAt) {
1180 } else if (newtype == hullXXAlignAt) {
1182 for (row_type row = 0; row < nrows(); ++row)
1183 numbered(row, false);
1187 setType(hullEqnArray);
1193 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1194 << "' to '" << to_utf8(hullName(newtype))
1195 << "' not implemented" << endl;
1200 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1201 bool last_eoln) const
1204 if (numberedType()) {
1205 if (label_[row] && numbered_[row]) {
1206 docstring const name =
1207 latex ? escape(label_[row]->getParam("name"))
1208 : label_[row]->getParam("name");
1209 res += "\\label{" + name + '}';
1211 if (!numbered_[row] && (type_ != hullMultline))
1212 res += "\\nonumber ";
1214 // Never add \\ on the last empty line of eqnarray and friends
1216 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1220 void InsetMathHull::write(WriteStream & os) const
1222 ModeSpecifier specifier(os, MATH_MODE);
1224 InsetMathGrid::write(os);
1229 void InsetMathHull::normalize(NormalStream & os) const
1231 os << "[formula " << hullName(type_) << ' ';
1232 InsetMathGrid::normalize(os);
1237 void InsetMathHull::infoize(odocstream & os) const
1239 os << "Type: " << hullName(type_);
1243 void InsetMathHull::check() const
1245 LASSERT(numbered_.size() == nrows(), /**/);
1246 LASSERT(numbers_.size() == nrows(), /**/);
1247 LASSERT(label_.size() == nrows(), /**/);
1251 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1255 idocstringstream iss(func.argument());
1256 iss >> dlang >> extra;
1258 extra = from_ascii("noextra");
1259 string const lang = to_ascii(dlang);
1261 // FIXME: temporarily disabled
1262 //if (cur.selection()) {
1265 // lyxerr << "use selection: " << ar << endl;
1266 // insert(pipeThroughExtern(lang, extra, ar));
1270 // only inline, display or eqnarray math is allowed
1271 if (getType() > hullEqnArray) {
1272 frontend::Alert::warning(_("Bad math environment"),
1273 _("Computation cannot be performed for AMS "
1274 "math environments.\nChange the math "
1275 "formula type and try again."));
1280 eq.push_back(MathAtom(new InsetMathChar('=')));
1282 // go to first item in line
1283 cur.idx() -= cur.idx() % ncols();
1286 if (getType() == hullSimple) {
1287 size_type pos = cur.cell().find_last(eq);
1289 if (cur.inMathed() && cur.selection()) {
1290 asArray(grabAndEraseSelection(cur), ar);
1291 } else if (pos == cur.cell().size()) {
1293 lyxerr << "use whole cell: " << ar << endl;
1295 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1296 lyxerr << "use partial cell form pos: " << pos << endl;
1298 cur.cell().append(eq);
1299 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1300 cur.pos() = cur.lastpos();
1304 if (getType() == hullEquation) {
1305 lyxerr << "use equation inset" << endl;
1306 mutate(hullEqnArray);
1307 MathData & ar = cur.cell();
1308 lyxerr << "use cell: " << ar << endl;
1312 cur.cell() = pipeThroughExtern(lang, extra, ar);
1313 // move to end of line
1314 cur.pos() = cur.lastpos();
1319 lyxerr << "use eqnarray" << endl;
1320 cur.idx() += 2 - cur.idx() % ncols();
1322 MathData ar = cur.cell();
1323 lyxerr << "use cell: " << ar << endl;
1324 // FIXME: temporarily disabled
1330 cur.cell() = pipeThroughExtern(lang, extra, ar);
1331 cur.pos() = cur.lastpos();
1336 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1338 //lyxerr << "action: " << cmd.action() << endl;
1339 switch (cmd.action()) {
1341 case LFUN_FINISHED_BACKWARD:
1342 case LFUN_FINISHED_FORWARD:
1343 case LFUN_FINISHED_RIGHT:
1344 case LFUN_FINISHED_LEFT:
1345 //lyxerr << "action: " << cmd.action() << endl;
1346 InsetMathGrid::doDispatch(cur, cmd);
1350 case LFUN_BREAK_PARAGRAPH:
1351 // just swallow this
1354 case LFUN_NEWLINE_INSERT:
1355 // some magic for the common case
1356 if (type_ == hullSimple || type_ == hullEquation) {
1357 cur.recordUndoInset();
1359 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1360 mutate(align ? hullAlign : hullEqnArray);
1361 // mutate() may change labels and such.
1362 cur.forceBufferUpdate();
1363 cur.idx() = nrows() * ncols() - 1;
1364 cur.pos() = cur.lastpos();
1366 InsetMathGrid::doDispatch(cur, cmd);
1369 case LFUN_MATH_NUMBER_TOGGLE: {
1370 //lyxerr << "toggling all numbers" << endl;
1371 cur.recordUndoInset();
1372 bool old = numberedType();
1373 if (type_ == hullMultline)
1374 numbered(nrows() - 1, !old);
1376 for (row_type row = 0; row < nrows(); ++row)
1377 numbered(row, !old);
1379 cur.message(old ? _("No number") : _("Number"));
1380 cur.forceBufferUpdate();
1384 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1385 cur.recordUndoInset();
1386 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1387 bool old = numbered(r);
1388 cur.message(old ? _("No number") : _("Number"));
1390 cur.forceBufferUpdate();
1394 case LFUN_LABEL_INSERT: {
1395 cur.recordUndoInset();
1396 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1397 docstring old_label = label(r);
1398 docstring const default_label = from_ascii("eq:");
1399 if (old_label.empty())
1400 old_label = default_label;
1402 InsetCommandParams p(LABEL_CODE);
1403 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1404 string const data = InsetCommand::params2string(p);
1406 if (cmd.argument().empty())
1407 cur.bv().showDialog("label", data);
1409 FuncRequest fr(LFUN_INSET_INSERT, data);
1415 case LFUN_LABEL_COPY_AS_REF: {
1417 if (cmd.argument().empty() && &cur.inset() == this)
1418 // if there is no argument and we're inside math, we retrieve
1419 // the row number from the cursor position.
1420 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1422 // if there is an argument, find the corresponding label, else
1423 // check whether there is at least one label.
1424 for (row = 0; row != nrows(); ++row)
1425 if (numbered_[row] && label_[row]
1426 && (cmd.argument().empty() || label(row) == cmd.argument()))
1433 InsetCommandParams p(REF_CODE, "ref");
1434 p["reference"] = label(row);
1435 cap::clearSelection();
1436 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1440 case LFUN_WORD_DELETE_FORWARD:
1441 case LFUN_CHAR_DELETE_FORWARD:
1442 if (col(cur.idx()) + 1 == ncols()
1443 && cur.pos() == cur.lastpos()
1444 && !cur.selection()) {
1445 if (!label(row(cur.idx())).empty()) {
1446 cur.recordUndoInset();
1447 label(row(cur.idx()), docstring());
1448 } else if (numbered(row(cur.idx()))) {
1449 cur.recordUndoInset();
1450 numbered(row(cur.idx()), false);
1451 cur.forceBufferUpdate();
1453 InsetMathGrid::doDispatch(cur, cmd);
1457 InsetMathGrid::doDispatch(cur, cmd);
1462 case LFUN_INSET_INSERT: {
1463 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1464 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1465 string const name = cmd.getArg(0);
1466 if (name == "label") {
1467 InsetCommandParams p(LABEL_CODE);
1468 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1469 docstring str = p["name"];
1470 cur.recordUndoInset();
1471 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1475 docstring old = label(r);
1478 // The label will take care of the reference update.
1482 // Newly created inset so initialize it.
1483 label_[r]->initView();
1486 cur.forceBufferUpdate();
1489 InsetMathGrid::doDispatch(cur, cmd);
1493 case LFUN_MATH_EXTERN:
1494 cur.recordUndoInset();
1498 case LFUN_MATH_MUTATE: {
1499 cur.recordUndoInset();
1500 row_type row = cur.row();
1501 col_type col = cur.col();
1502 mutate(hullType(cmd.argument()));
1503 cur.idx() = row * ncols() + col;
1504 if (cur.idx() > cur.lastidx()) {
1505 cur.idx() = cur.lastidx();
1506 cur.pos() = cur.lastpos();
1508 if (cur.pos() > cur.lastpos())
1509 cur.pos() = cur.lastpos();
1511 cur.forceBufferUpdate();
1512 // FIXME: find some more clever handling of the selection,
1513 // i.e. preserve it.
1514 cur.clearSelection();
1515 //cur.dispatched(FINISHED);
1519 case LFUN_MATH_DISPLAY: {
1520 cur.recordUndoInset();
1521 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1523 cur.pos() = cur.lastpos();
1524 //cur.dispatched(FINISHED);
1529 InsetMathGrid::doDispatch(cur, cmd);
1535 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1536 FuncStatus & status) const
1538 switch (cmd.action()) {
1539 case LFUN_FINISHED_BACKWARD:
1540 case LFUN_FINISHED_FORWARD:
1541 case LFUN_FINISHED_RIGHT:
1542 case LFUN_FINISHED_LEFT:
1545 case LFUN_NEWLINE_INSERT:
1546 case LFUN_MATH_EXTERN:
1548 status.setEnabled(true);
1551 // we never allow this in math, and we want to bind enter
1552 // to another actions in command-alternatives
1553 case LFUN_BREAK_PARAGRAPH:
1554 status.setEnabled(false);
1556 case LFUN_MATH_MUTATE: {
1557 HullType const ht = hullType(cmd.argument());
1558 status.setOnOff(type_ == ht);
1559 status.setEnabled(true);
1561 if (ht != hullSimple) {
1562 Cursor tmpcur = cur;
1563 while (!tmpcur.empty()) {
1564 InsetCode code = tmpcur.inset().lyxCode();
1565 if (code == BOX_CODE) {
1567 } else if (code == TABULAR_CODE) {
1568 FuncRequest tmpcmd(LFUN_MATH_DISPLAY);
1569 if (tmpcur.getStatus(tmpcmd, status) && !status.enabled())
1577 case LFUN_MATH_DISPLAY: {
1579 if (cur.depth() > 1) {
1580 Inset const & in = cur[cur.depth()-2].inset();
1581 if (in.lyxCode() == SCRIPT_CODE)
1582 enable = display() != Inline;
1584 status.setEnabled(enable);
1588 case LFUN_MATH_NUMBER_TOGGLE:
1589 // FIXME: what is the right test, this or the one of
1591 status.setEnabled(display() != Inline);
1592 status.setOnOff(numberedType());
1595 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1596 // FIXME: what is the right test, this or the one of
1598 bool const enable = (type_ == hullMultline)
1599 ? (nrows() - 1 == cur.row())
1600 : display() != Inline;
1601 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1602 status.setEnabled(enable);
1603 status.setOnOff(enable && numbered(r));
1607 case LFUN_LABEL_INSERT:
1608 status.setEnabled(type_ != hullSimple);
1611 case LFUN_LABEL_COPY_AS_REF: {
1612 bool enabled = false;
1614 if (cmd.argument().empty() && &cur.inset() == this) {
1615 // if there is no argument and we're inside math, we retrieve
1616 // the row number from the cursor position.
1617 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1618 enabled = numberedType() && label_[row] && numbered_[row];
1620 // if there is an argument, find the corresponding label, else
1621 // check whether there is at least one label.
1622 for (row_type row = 0; row != nrows(); ++row) {
1623 if (numbered_[row] && label_[row] &&
1624 (cmd.argument().empty() || label(row) == cmd.argument())) {
1630 status.setEnabled(enabled);
1634 case LFUN_INSET_INSERT:
1635 if (cmd.getArg(0) == "label") {
1636 status.setEnabled(type_ != hullSimple);
1639 return InsetMathGrid::getStatus(cur, cmd, status);
1641 case LFUN_INSET_MODIFY: {
1642 istringstream is(to_utf8(cmd.argument()));
1646 return InsetMathGrid::getStatus(cur, cmd, status);
1649 && (s == "append-row"
1650 || s == "delete-row"
1651 || s == "copy-row")) {
1652 status.message(bformat(
1653 from_utf8(N_("Can't change number of rows in '%1$s'")),
1655 status.setEnabled(false);
1659 && (s == "append-column"
1660 || s == "delete-column"
1661 || s == "copy-column")) {
1662 status.message(bformat(
1663 from_utf8(N_("Can't change number of columns in '%1$s'")),
1665 status.setEnabled(false);
1668 if ((type_ == hullSimple
1669 || type_ == hullEquation
1670 || type_ == hullNone) &&
1671 (s == "add-hline-above" || s == "add-hline-below")) {
1672 status.message(bformat(
1673 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1675 status.setEnabled(false);
1678 if (s == "add-vline-left" || s == "add-vline-right") {
1679 status.message(bformat(
1680 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1682 status.setEnabled(false);
1685 if (s == "valign-top" || s == "valign-middle"
1686 || s == "valign-bottom" || s == "align-left"
1687 || s == "align-center" || s == "align-right") {
1688 status.setEnabled(false);
1691 return InsetMathGrid::getStatus(cur, cmd, status);
1695 return InsetMathGrid::getStatus(cur, cmd, status);
1698 // This cannot really happen, but inserted to shut-up gcc
1699 return InsetMathGrid::getStatus(cur, cmd, status);
1703 /////////////////////////////////////////////////////////////////////
1707 // simply scrap this function if you want
1708 void InsetMathHull::mutateToText()
1711 // translate to latex
1713 latex(os, false, false);
1714 string str = os.str();
1717 Text * lt = view_->cursor().innerText();
1718 string::const_iterator cit = str.begin();
1719 string::const_iterator end = str.end();
1720 for (; cit != end; ++cit)
1721 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1724 //dispatch(LFUN_ESCAPE);
1729 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1730 docstring const & font)
1732 // this whole function is a hack and won't work for incremental font
1735 if (cur.inset().asInsetMath()->name() == font)
1736 cur.handleFont(to_utf8(font));
1738 cur.handleNest(createInsetMath(font, cur.buffer()));
1744 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1749 font.fromString(to_utf8(arg), b);
1750 if (font.fontInfo().color() != Color_inherit) {
1751 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1752 cur.handleNest(at, 0);
1757 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1760 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1761 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1762 enter_front ? idxFirst(cur) : idxLast(cur);
1763 // The inset formula dimension is not necessarily the same as the
1764 // one of the instant preview image, so we have to indicate to the
1765 // BufferView that a metrics update is needed.
1766 cur.screenUpdateFlags(Update::Force);
1770 void InsetMathHull::revealCodes(Cursor & cur) const
1772 if (!cur.inMathed())
1774 odocstringstream os;
1776 cur.message(os.str());
1778 // write something to the minibuffer
1779 // translate to latex
1783 string str = os.str();
1785 string::size_type pos = 0;
1787 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1790 else if (*it == '\0') {
1792 pos = it - str.begin();
1798 res = res.substr(pos - 30);
1799 if (res.size() > 60)
1800 res = res.substr(0, 60);
1806 /////////////////////////////////////////////////////////////////////
1810 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1813 // FIXME: completely broken
1814 static InsetMathHull * lastformula = 0;
1815 static CursorBase current = DocIterator(ibegin(nucleus()));
1817 static string laststr;
1819 if (lastformula != this || laststr != str) {
1820 //lyxerr << "reset lastformula to " << this << endl;
1823 current = ibegin(nucleus());
1825 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1829 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1831 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1832 CursorSlice & top = it.back();
1833 MathData const & a = top.asInsetMath()->cell(top.idx_);
1834 if (a.matchpart(ar, top.pos_)) {
1835 bv->cursor().setSelection(it, ar.size());
1837 top.pos_ += ar.size();
1843 //lyxerr << "not found!" << endl;
1850 void InsetMathHull::write(ostream & os) const
1852 odocstringstream oss;
1853 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1856 os << to_utf8(oss.str());
1860 void InsetMathHull::read(Lexer & lex)
1863 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1864 operator=(*at->asHullInset());
1868 bool InsetMathHull::readQuiet(Lexer & lex)
1871 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1873 operator=(*at->asHullInset());
1878 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1880 // disables ASCII-art for export of equations. See #2275.
1881 if (0 && display()) {
1885 TextPainter tpain(dim.width(), dim.height());
1886 drawT(tpain, 0, dim.ascent());
1888 // reset metrics cache to "real" values
1890 return tpain.textheight();
1892 odocstringstream oss;
1893 Encoding const * const enc = encodings.fromLyXName("utf8");
1894 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1896 if (type_ == hullRegexp)
1900 docstring const str = oss.str();
1907 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1912 if (getType() == hullSimple)
1913 name = from_ascii("inlineequation");
1915 name = from_ascii("informalequation");
1917 docstring bname = name;
1918 if (!label(0).empty())
1919 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1921 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1923 odocstringstream ls;
1924 if (runparams.flavor == OutputParams::XML) {
1925 ms << MTag("alt role='tex' ");
1926 // Workaround for db2latex: db2latex always includes equations with
1927 // \ensuremath{} or \begin{display}\end{display}
1928 // so we strip LyX' math environment
1929 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1930 InsetMathGrid::write(wi);
1931 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1936 InsetMathGrid::mathmlize(ms);
1941 otexstream ols(ls, texrow);
1942 ms << MTag("alt role='tex'");
1943 latex(ols, runparams);
1944 res = texrow.rows();
1945 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1949 ms << from_ascii("<graphic fileref=\"eqn/");
1950 if (!label(0).empty())
1951 ms << sgml::cleanID(buffer(), runparams, label(0));
1953 ms << sgml::uniqueID(from_ascii("anon"));
1955 if (runparams.flavor == OutputParams::XML)
1956 ms << from_ascii("\"/>");
1958 ms << from_ascii("\">");
1960 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1962 return ms.line() + res;
1966 bool InsetMathHull::haveNumbers() const
1968 bool havenumbers = false;
1969 // inline formulas are never numbered (bug 7351 part 3)
1970 if (getType() == hullSimple)
1972 for (size_t i = 0; i != numbered_.size(); ++i) {
1983 // We need to do something about alignment here.
1985 // This duplicates code from InsetMathGrid, but
1986 // we need access here to number information,
1987 // and we simply do not have that in InsetMathGrid.
1988 void InsetMathHull::htmlize(HtmlStream & os) const
1990 bool const havenumbers = haveNumbers();
1991 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
1994 os << cell(index(0, 0));
1998 os << MTag("table", "class='mathtable'");
1999 for (row_type row = 0; row < nrows(); ++row) {
2001 for (col_type col = 0; col < ncols(); ++col) {
2003 os << cell(index(row, col));
2008 docstring const & num = numbers_[row];
2010 os << '(' << num << ')';
2015 os << ETag("table");
2019 // this duplicates code from InsetMathGrid, but
2020 // we need access here to number information,
2021 // and we simply do not have that in InsetMathGrid.
2022 void InsetMathHull::mathmlize(MathStream & os) const
2024 bool const havenumbers = haveNumbers();
2025 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2028 os << MTag("mtable");
2029 char const * const celltag = havetable ? "mtd" : "mrow";
2030 // FIXME There does not seem to be wide support at the moment
2031 // for mlabeledtr, so we have to use just mtr for now.
2032 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2033 char const * const rowtag = "mtr";
2034 for (row_type row = 0; row < nrows(); ++row) {
2037 for (col_type col = 0; col < ncols(); ++col) {
2039 << cell(index(row, col))
2045 docstring const & num = numbers_[row];
2047 os << '(' << num << ')';
2054 os << ETag("mtable");
2058 void InsetMathHull::mathAsLatex(WriteStream & os) const
2060 MathEnsurer ensurer(os, false);
2061 bool havenumbers = haveNumbers();
2062 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2065 os << cell(index(0, 0));
2069 os << "<table class='mathtable'>";
2070 for (row_type row = 0; row < nrows(); ++row) {
2072 for (col_type col = 0; col < ncols(); ++col) {
2073 os << "<td class='math'>";
2074 os << cell(index(row, col));
2079 docstring const & num = numbers_[row];
2081 os << '(' << num << ')';
2090 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2092 BufferParams::MathOutput const mathtype =
2093 buffer().params().html_math_output;
2095 bool success = false;
2097 // we output all the labels just at the beginning of the equation.
2098 // this should be fine.
2099 for (size_t i = 0; i != label_.size(); ++i) {
2100 InsetLabel const * const il = label_[i];
2106 // FIXME Eventually we would like to do this inset by inset.
2107 if (mathtype == BufferParams::MathML) {
2108 odocstringstream os;
2113 } catch (MathExportException const &) {}
2115 if (getType() == hullSimple)
2116 xs << html::StartTag("math",
2117 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2119 xs << html::StartTag("math",
2120 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2121 xs << XHTMLStream::ESCAPE_NONE
2123 << html::EndTag("math");
2125 } else if (mathtype == BufferParams::HTML) {
2126 odocstringstream os;
2131 } catch (MathExportException const &) {}
2133 string const tag = (getType() == hullSimple) ? "span" : "div";
2134 xs << html::StartTag(tag, "class='formula'", true)
2135 << XHTMLStream::ESCAPE_NONE
2137 << html::EndTag(tag);
2141 // what we actually want is this:
2143 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2145 // || mathtype == BufferParams::Images
2147 // but what follows is equivalent, since we'll enter only if either (a) we
2148 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2149 // aren't doing LaTeX, in which case we are doing Images.
2150 if (!success && mathtype != BufferParams::LaTeX) {
2151 graphics::PreviewImage const * pimage = 0;
2153 loadPreview(docit_);
2154 pimage = preview_->getPreviewImage(buffer());
2155 // FIXME Do we always have png?
2158 if (pimage || op.dryrun) {
2159 string const filename = pimage ? pimage->filename().onlyFileName()
2160 : "previewimage.png";
2162 // if we are not in the master buffer, then we need to see that the
2163 // generated image is copied there; otherwise, preview fails.
2164 Buffer const * mbuf = buffer().masterBuffer();
2165 if (mbuf != &buffer()) {
2166 string mbtmp = mbuf->temppath();
2167 FileName const mbufimg(support::addName(mbtmp, filename));
2168 pimage->filename().copyTo(mbufimg);
2170 // add the file to the list of files to be exported
2171 op.exportdata->addExternalFile("xhtml", pimage->filename());
2174 string const tag = (getType() == hullSimple) ? "span" : "div";
2176 << html::StartTag(tag)
2177 << html::CompTag("img", "src=\"" + filename + "\"")
2178 << html::EndTag(tag)
2184 // so we'll pass this test if we've failed everything else, or
2185 // if mathtype was LaTeX, since we won't have entered any of the
2187 if (!success /* || mathtype != BufferParams::LaTeX */) {
2188 // Unfortunately, we cannot use latexString() because we do not want
2189 // $...$ or whatever.
2190 odocstringstream ls;
2191 WriteStream wi(ls, false, true, WriteStream::wsPreview);
2192 ModeSpecifier specifier(wi, MATH_MODE);
2194 docstring const latex = ls.str();
2196 // class='math' allows for use of jsMath
2197 // http://www.math.union.edu/~dpvc/jsMath/
2199 // probably should allow for some kind of customization here
2200 string const tag = (getType() == hullSimple) ? "span" : "div";
2201 xs << html::StartTag(tag, "class='math'")
2203 << html::EndTag(tag)
2210 void InsetMathHull::toString(odocstream & os) const
2212 plaintext(os, OutputParams(0));
2216 void InsetMathHull::forToc(docstring & os, size_t) const
2218 odocstringstream ods;
2219 plaintext(ods, OutputParams(0));
2224 docstring InsetMathHull::contextMenuName() const
2226 return from_ascii("context-math");
2230 void InsetMathHull::recordLocation(DocIterator const & di)