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);
228 // FIXME This should really be controlled by the TOC level, or
229 // something of the sort.
231 const char * counters_to_save[] = {"section", "chapter"};
232 unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
236 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
239 //FIXME: buffer_ should be set at creation for this inset! Problem is
240 // This inset is created at too many places (see Parser::parse1() in
245 // if any of the equations are numbered, then we want to save the values
246 // of some of the counters.
248 BufferParams const & bp = buffer_->params();
249 string const & lang = it->getParLanguage(bp)->code();
251 buffer_->masterBuffer()->params().documentClass().counters();
253 // right now, we only need to do this at export time
254 if (utype == OutputUpdate) {
255 for (size_t i = 0; i < numcnts; ++i) {
256 docstring const cnt = from_ascii(counters_to_save[i]);
257 if (cnts.hasCounter(cnt))
258 counter_map[cnt] = cnts.value(cnt);
262 // this has to be done separately
263 docstring const eqstr = from_ascii("equation");
264 if (cnts.hasCounter(eqstr)) {
265 if (utype == OutputUpdate)
266 counter_map[eqstr] = cnts.value(eqstr);
267 for (size_t i = 0; i != label_.size(); ++i) {
269 cnts.step(eqstr, utype);
270 numbers_[i] = cnts.theCounter(eqstr, lang);
272 numbers_[i] = empty_docstring();
278 for (size_t i = 0; i != label_.size(); ++i) {
280 label_[i]->updateBuffer(it, utype);
283 InsetMathGrid::updateBuffer(it, utype);
287 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active) const
290 //FIXME: buffer_ should be set at creation for this inset! Problem is
291 // This inset is created at too many places (see Parser::parse1() in
296 Toc & toc = buffer().tocBackend().toc("equation");
298 for (row_type row = 0; row != nrows(); ++row) {
302 label_[row]->addToToc(pit, output_active);
303 toc.push_back(TocItem(pit, 0, nicelabel(row), output_active));
308 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
314 return InsetMathNest::editXY(cur, x, y);
318 InsetMath::mode_type InsetMathHull::currentMode() const
320 if (type_ == hullNone)
321 return UNDECIDED_MODE;
322 // definitely math mode ...
327 bool InsetMathHull::idxFirst(Cursor & cur) const
335 bool InsetMathHull::idxLast(Cursor & cur) const
337 cur.idx() = nargs() - 1;
338 cur.pos() = cur.lastpos();
343 char InsetMathHull::defaultColAlign(col_type col)
345 if (type_ == hullEqnArray)
347 if (type_ == hullMultline)
349 if (type_ == hullGather)
351 if (type_ >= hullAlign)
352 return "rl"[col & 1];
357 char InsetMathHull::displayColAlign(col_type col, row_type row) const
359 if (type_ == hullMultline) {
362 if (row == nrows() - 1)
365 return InsetMathGrid::displayColAlign(col, row);
369 int InsetMathHull::defaultColSpace(col_type col)
371 if (type_ == hullAlign || type_ == hullAlignAt)
373 if (type_ == hullXAlignAt)
374 return (col & 1) ? 20 : 0;
375 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
376 return (col & 1) ? 40 : 0;
381 docstring InsetMathHull::standardFont() const
386 font_name = from_ascii("texttt");
389 font_name = from_ascii("lyxnochange");
392 font_name = from_ascii("mathnormal");
398 ColorCode InsetMathHull::standardColor() const
404 color = Color_foreground;
413 bool InsetMathHull::previewState(BufferView * bv) const
415 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
416 graphics::PreviewImage const * pimage =
417 preview_->getPreviewImage(bv->buffer());
418 return pimage && pimage->image();
424 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
426 if (previewState(mi.base.bv)) {
427 preview_->metrics(mi, dim);
428 // insert a one pixel gap in front of the formula
431 dim.des += displayMargin();
432 // Cache the inset dimension.
433 setDimCache(mi, dim);
437 FontSetChanger dummy1(mi.base, standardFont());
438 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
440 // let the cells adjust themselves
441 InsetMathGrid::metrics(mi, dim);
444 dim.asc += displayMargin();
445 dim.des += displayMargin();
448 if (numberedType()) {
449 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
451 for (row_type row = 0; row < nrows(); ++row)
452 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
458 if (type_ == hullRegexp)
460 // make it at least as high as the current font
463 math_font_max_dim(mi.base.font, asc, des);
464 dim.asc = max(dim.asc, asc);
465 dim.des = max(dim.des, des);
466 // Cache the inset dimension.
467 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
468 setDimCache(mi, dim);
472 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
474 if (previewState(pi.base.bv))
475 return graphics::PreviewLoader::backgroundColor();
480 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
482 Dimension const dim = dimension(*pi.base.bv);
483 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
484 dim.asc + dim.des - 1, pi.backgroundColor(this));
488 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
490 use_preview_ = previewState(pi.base.bv);
492 if (type_ == hullRegexp) {
493 Dimension const dim = dimension(*pi.base.bv);
494 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
495 dim.width() - 2, dim.height() - 2, Color_regexpframe);
498 // one pixel gap in front
499 preview_->draw(pi, x + 1, y);
500 setPosCache(pi, x, y);
504 ColorCode color = pi.selected && lyxrc.use_system_colors
505 ? Color_selectiontext : standardColor();
506 bool const really_change_color = pi.base.font.color() == Color_none;
507 ColorChanger dummy0(pi.base.font, color, really_change_color);
508 FontSetChanger dummy1(pi.base, standardFont());
509 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
511 InsetMathGrid::draw(pi, x + 1, y);
513 if (numberedType()) {
514 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
515 for (row_type row = 0; row < nrows(); ++row) {
516 int const yy = y + rowinfo_[row].offset_;
517 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
518 docstring const nl = nicelabel(row);
522 setPosCache(pi, x, y);
526 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
529 InsetMathGrid::metricsT(mi, dim);
532 WriteStream wi(os, false, true, WriteStream::wsDefault);
534 dim.wid = os.str().size();
541 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
544 InsetMathGrid::drawT(pain, x, y);
547 WriteStream wi(os, false, true, WriteStream::wsDefault);
549 pain.draw(x, y, os.str().c_str());
554 static docstring latexString(InsetMathHull const & inset)
557 // This has to be static, because a preview snippet or a math
558 // macro containing math in text mode (such as $\text{$\phi$}$ or
559 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
560 // first time as a whole, and the second time only the inner math.
561 // In this last case inset.buffer() would be invalid.
562 static Encoding const * encoding = 0;
563 if (inset.isBufferValid())
564 encoding = &(inset.buffer().params().encoding());
565 WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
571 void InsetMathHull::initUnicodeMath() const
573 // Trigger classification of the unicode symbols in this inset
574 docstring const dummy = latexString(*this);
578 void InsetMathHull::addPreview(DocIterator const & inset_pos,
579 graphics::PreviewLoader & /*ploader*/) const
581 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
582 preparePreview(inset_pos);
587 void InsetMathHull::preparePreview(DocIterator const & pos,
588 bool forexport) const
590 // there is no need to do all the macro stuff if we're not
591 // actually going to generate the preview.
592 if (RenderPreview::status() != LyXRC::PREVIEW_ON && !forexport)
595 Buffer const * buffer = pos.buffer();
597 // collect macros at this position
599 buffer->listMacroNames(macros);
600 MacroNameSet::iterator it = macros.begin();
601 MacroNameSet::iterator end = macros.end();
602 odocstringstream macro_preamble;
603 for (; it != end; ++it) {
604 MacroData const * data = buffer->getMacro(*it, pos, true);
606 data->write(macro_preamble, true);
607 macro_preamble << endl;
612 if (forexport && haveNumbers()) {
613 docstring eqstr = from_ascii("equation");
614 CounterMap::const_iterator it = counter_map.find(eqstr);
615 if (it != counter_map.end()) {
616 int num = it->second;
618 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
619 '{' + convert<docstring>(num) + '}' + '\n';
621 for (size_t i = 0; i != numcnts; ++i) {
622 docstring cnt = from_ascii(counters_to_save[i]);
623 it = counter_map.find(cnt);
624 if (it == counter_map.end())
626 int num = it->second;
628 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
629 '{' + convert<docstring>(num) + '}';
632 docstring const snippet = macro_preamble.str() +
633 setcnt + latexString(*this);
634 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
635 preview_->addPreview(snippet, *buffer, forexport);
639 void InsetMathHull::reloadPreview(DocIterator const & pos) const
642 preview_->startLoading(*pos.buffer());
646 void InsetMathHull::loadPreview(DocIterator const & pos) const
648 bool const forexport = true;
649 preparePreview(pos, forexport);
650 preview_->startLoading(*pos.buffer(), forexport);
654 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
656 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
658 cur.screenUpdateFlags(Update::Force);
664 docstring InsetMathHull::label(row_type row) const
666 LASSERT(row < nrows(), return docstring());
667 if (InsetLabel * il = label_[row])
668 return il->screenLabel();
673 void InsetMathHull::label(row_type row, docstring const & label)
675 //lyxerr << "setting label '" << label << "' for row " << row << endl;
679 label_[row] = dummy_pointer;
682 label_[row]->updateLabelAndRefs(label);
684 label_[row]->setParam("name", label);
688 InsetCommandParams p(LABEL_CODE);
690 label_[row] = new InsetLabel(buffer_, p);
692 label_[row]->setBuffer(buffer());
696 void InsetMathHull::numbered(row_type row, bool num)
698 numbered_[row] = num;
699 if (!numbered_[row] && label_[row]) {
706 bool InsetMathHull::numbered(row_type row) const
708 return numbered_[row];
712 bool InsetMathHull::ams() const
714 return type_ == hullAlign
715 || type_ == hullFlAlign
716 || type_ == hullMultline
717 || type_ == hullGather
718 || type_ == hullAlignAt
719 || type_ == hullXAlignAt
720 || type_ == hullXXAlignAt;
724 Inset::DisplayType InsetMathHull::display() const
726 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
731 bool InsetMathHull::numberedType() const
733 if (type_ == hullNone)
735 if (type_ == hullSimple)
737 if (type_ == hullXXAlignAt)
739 if (type_ == hullRegexp)
741 for (row_type row = 0; row < nrows(); ++row)
748 void InsetMathHull::validate(LaTeXFeatures & features) const
750 if (features.runparams().isLaTeX()) {
752 features.require("amsmath");
754 if (type_ == hullRegexp) {
755 features.require("color");
756 string frcol = lcolor.getLaTeXName(Color_regexpframe);
757 string bgcol = "white";
758 features.addPreambleSnippet(
759 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
760 + frcol + string("}{")
761 + bgcol + string("}{\\ensuremath{\\mathtt{#1}}}}"));
762 features.addPreambleSnippet(
763 string("\\newcommand{\\endregexp}{}"));
766 // Validation is necessary only if not using AMS math.
767 // To be safe, we will always run mathedvalidate.
768 //if (features.amsstyle)
771 //features.binom = true;
772 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
773 // it would be better to do this elsewhere, but we can't validate in
774 // InsetMathMatrix and we have no way, outside MathExtern, to know if
775 // we even have any matrices.
776 features.addCSSSnippet(
777 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
778 "table.matrix td{padding: 0.25px;}\n"
779 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
780 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
782 InsetMathGrid::validate(features);
786 void InsetMathHull::header_write(WriteStream & os) const
788 bool n = numberedType();
802 os << "\n\\begin{equation" << star(n) << "}\n";
812 os << "\n\\begin{" << hullName(type_) << star(n) << "}\n";
817 os << "\n\\begin{" << hullName(type_) << star(n) << '}'
818 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
822 os << "\n\\begin{" << hullName(type_) << '}'
823 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
831 os << "\n\\begin{unknown" << star(n) << "}\n";
837 void InsetMathHull::footer_write(WriteStream & os) const
839 bool n = numberedType();
852 os << "\n\\end{equation" << star(n) << "}\n";
864 os << "\n\\end{" << hullName(type_) << star(n) << "}\n";
868 os << "\n\\end{" << hullName(type_) << "}\n";
872 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
873 os << "\\endregexp{}}";
877 os << "\n\\end{unknown" << star(n) << "}\n";
883 bool InsetMathHull::rowChangeOK() const
886 type_ == hullEqnArray || type_ == hullAlign ||
887 type_ == hullFlAlign || type_ == hullAlignAt ||
888 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
889 type_ == hullGather || type_ == hullMultline;
893 bool InsetMathHull::colChangeOK() const
896 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
897 type_ == hullXAlignAt || type_ == hullXXAlignAt;
901 void InsetMathHull::addRow(row_type row)
906 bool numbered = numberedType();
907 // Move the number and raw pointer, do not call label() (bug 7511)
908 InsetLabel * label = dummy_pointer;
909 docstring number = empty_docstring();
910 if (type_ == hullMultline) {
911 if (row + 1 == nrows()) {
912 numbered_[row] = false;
913 swap(label, label_[row]);
914 swap(number, numbers_[row]);
919 numbered_.insert(numbered_.begin() + row + 1, numbered);
920 numbers_.insert(numbers_.begin() + row + 1, number);
921 label_.insert(label_.begin() + row + 1, label);
922 InsetMathGrid::addRow(row);
926 void InsetMathHull::swapRow(row_type row)
930 if (row + 1 == nrows())
932 // gcc implements the standard std::vector<bool> which is *not* a container:
933 // http://www.gotw.ca/publications/N1185.pdf
934 // As a results, it doesn't like this:
935 // swap(numbered_[row], numbered_[row + 1]);
936 // so we do it manually:
937 bool const b = numbered_[row];
938 numbered_[row] = numbered_[row + 1];
939 numbered_[row + 1] = b;
940 swap(numbers_[row], numbers_[row + 1]);
941 swap(label_[row], label_[row + 1]);
942 InsetMathGrid::swapRow(row);
946 void InsetMathHull::delRow(row_type row)
948 if (nrows() <= 1 || !rowChangeOK())
950 if (row + 1 == nrows() && type_ == hullMultline) {
951 bool const b = numbered_[row - 1];
952 numbered_[row - 1] = numbered_[row];
954 swap(numbers_[row - 1], numbers_[row]);
955 swap(label_[row - 1], label_[row]);
956 InsetMathGrid::delRow(row);
959 InsetMathGrid::delRow(row);
960 // The last dummy row has no number info nor a label.
961 // Test nrows() + 1 because we have already erased the row.
962 if (row == nrows() + 1)
964 numbered_.erase(numbered_.begin() + row);
965 numbers_.erase(numbers_.begin() + row);
967 label_.erase(label_.begin() + row);
971 void InsetMathHull::addCol(col_type col)
975 InsetMathGrid::addCol(col);
979 void InsetMathHull::delCol(col_type col)
981 if (ncols() <= 1 || !colChangeOK())
983 InsetMathGrid::delCol(col);
987 docstring InsetMathHull::nicelabel(row_type row) const
991 docstring const & val = numbers_[row];
993 return '(' + val + ')';
994 return '(' + val + ',' + label_[row]->screenLabel() + ')';
998 void InsetMathHull::glueall(HullType type)
1001 for (idx_type i = 0; i < nargs(); ++i)
1003 InsetLabel * label = 0;
1004 if (type == hullEquation) {
1005 // preserve first non-empty label
1006 for (row_type row = 0; row < nrows(); ++row) {
1008 label = label_[row];
1014 *this = InsetMathHull(buffer_, hullSimple);
1021 void InsetMathHull::splitTo2Cols()
1023 LASSERT(ncols() == 1, return);
1024 InsetMathGrid::addCol(1);
1025 for (row_type row = 0; row < nrows(); ++row) {
1026 idx_type const i = 2 * row;
1027 pos_type pos = firstRelOp(cell(i));
1028 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1029 cell(i).erase(pos, cell(i).size());
1034 void InsetMathHull::splitTo3Cols()
1036 LASSERT(ncols() < 3, return);
1039 InsetMathGrid::addCol(2);
1040 for (row_type row = 0; row < nrows(); ++row) {
1041 idx_type const i = 3 * row + 1;
1042 if (!cell(i).empty()) {
1043 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1044 cell(i).erase(1, cell(i).size());
1050 void InsetMathHull::changeCols(col_type cols)
1052 if (ncols() == cols)
1054 else if (ncols() < cols) {
1060 while (ncols() < cols)
1061 InsetMathGrid::addCol(ncols());
1067 for (row_type row = 0; row < nrows(); ++row) {
1068 idx_type const i = row * ncols();
1069 for (col_type col = cols; col < ncols(); ++col) {
1070 cell(i + cols - 1).append(cell(i + col));
1074 while (ncols() > cols) {
1075 InsetMathGrid::delCol(ncols() - 1);
1080 HullType InsetMathHull::getType() const
1086 void InsetMathHull::setType(HullType type)
1093 void InsetMathHull::mutate(HullType newtype)
1095 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1097 // we try to move along the chain
1098 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1100 // +-------------------------------------+
1101 // we use eqnarray as intermediate type for mutations that are not
1102 // directly supported because it handles labels and numbering for
1105 if (newtype == type_) {
1109 else if (newtype < hullNone) {
1114 else if (type_ == hullNone) {
1115 setType(hullSimple);
1120 else if (type_ == hullSimple) {
1121 if (newtype == hullNone) {
1125 setType(hullEquation);
1126 numbered(0, label_[0] ? true : false);
1131 else if (type_ == hullEquation) {
1132 if (newtype < type_) {
1133 setType(hullSimple);
1136 } else if (newtype == hullEqnArray) {
1137 // split it "nicely" on the first relop
1139 setType(hullEqnArray);
1140 } else if (newtype == hullMultline || newtype == hullGather) {
1143 // split it "nicely"
1150 else if (type_ == hullEqnArray) {
1151 if (newtype < type_) {
1154 } else { // align & Co.
1161 else if (type_ == hullAlign || type_ == hullAlignAt ||
1162 type_ == hullXAlignAt || type_ == hullFlAlign) {
1163 if (newtype < hullAlign) {
1165 setType(hullEqnArray);
1167 } else if (newtype == hullGather || newtype == hullMultline) {
1170 } else if (newtype == hullXXAlignAt) {
1171 for (row_type row = 0; row < nrows(); ++row)
1172 numbered(row, false);
1179 else if (type_ == hullXXAlignAt) {
1180 for (row_type row = 0; row < nrows(); ++row)
1181 numbered(row, false);
1182 if (newtype < hullAlign) {
1184 setType(hullEqnArray);
1186 } else if (newtype == hullGather || newtype == hullMultline) {
1194 else if (type_ == hullMultline || type_ == hullGather) {
1195 if (newtype == hullGather || newtype == hullMultline)
1197 else if (newtype == hullAlign || newtype == hullFlAlign ||
1198 newtype == hullAlignAt || newtype == hullXAlignAt) {
1201 } else if (newtype == hullXXAlignAt) {
1203 for (row_type row = 0; row < nrows(); ++row)
1204 numbered(row, false);
1208 setType(hullEqnArray);
1214 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1215 << "' to '" << to_utf8(hullName(newtype))
1216 << "' not implemented" << endl;
1221 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1222 bool last_eoln) const
1225 if (numberedType()) {
1226 if (label_[row] && numbered_[row]) {
1227 docstring const name =
1228 latex ? escape(label_[row]->getParam("name"))
1229 : label_[row]->getParam("name");
1230 res += "\\label{" + name + '}';
1232 if (!numbered_[row] && (type_ != hullMultline))
1233 res += "\\nonumber ";
1235 // Never add \\ on the last empty line of eqnarray and friends
1237 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1241 void InsetMathHull::write(WriteStream & os) const
1243 ModeSpecifier specifier(os,
1244 type_ == hullRegexp ? TEXT_MODE : MATH_MODE);
1246 InsetMathGrid::write(os);
1251 void InsetMathHull::normalize(NormalStream & os) const
1253 os << "[formula " << hullName(type_) << ' ';
1254 InsetMathGrid::normalize(os);
1259 void InsetMathHull::infoize(odocstream & os) const
1261 os << "Type: " << hullName(type_);
1265 void InsetMathHull::check() const
1267 LATTEST(numbered_.size() == nrows());
1268 LATTEST(numbers_.size() == nrows());
1269 LATTEST(label_.size() == nrows());
1273 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1277 idocstringstream iss(func.argument());
1278 iss >> dlang >> extra;
1280 extra = from_ascii("noextra");
1281 string const lang = to_ascii(dlang);
1283 // FIXME: temporarily disabled
1284 //if (cur.selection()) {
1287 // lyxerr << "use selection: " << ar << endl;
1288 // insert(pipeThroughExtern(lang, extra, ar));
1292 // only inline, display or eqnarray math is allowed
1293 if (getType() > hullEqnArray) {
1294 frontend::Alert::warning(_("Bad math environment"),
1295 _("Computation cannot be performed for AMS "
1296 "math environments.\nChange the math "
1297 "formula type and try again."));
1302 eq.push_back(MathAtom(new InsetMathChar('=')));
1304 // go to first item in line
1305 cur.idx() -= cur.idx() % ncols();
1308 if (getType() == hullSimple) {
1309 size_type pos = cur.cell().find_last(eq);
1311 if (cur.inMathed() && cur.selection()) {
1312 asArray(grabAndEraseSelection(cur), ar);
1313 } else if (!pos == cur.cell().empty()) {
1315 lyxerr << "use whole cell: " << ar << endl;
1317 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1318 lyxerr << "use partial cell form pos: " << pos << endl;
1320 cur.cell().append(eq);
1321 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1322 cur.pos() = cur.lastpos();
1326 if (getType() == hullEquation) {
1327 lyxerr << "use equation inset" << endl;
1328 mutate(hullEqnArray);
1329 MathData & ar = cur.cell();
1330 lyxerr << "use cell: " << ar << endl;
1334 cur.cell() = pipeThroughExtern(lang, extra, ar);
1335 // move to end of line
1336 cur.pos() = cur.lastpos();
1341 lyxerr << "use eqnarray" << endl;
1342 cur.idx() += 2 - cur.idx() % ncols();
1344 MathData ar = cur.cell();
1345 lyxerr << "use cell: " << ar << endl;
1346 // FIXME: temporarily disabled
1352 cur.cell() = pipeThroughExtern(lang, extra, ar);
1353 cur.pos() = cur.lastpos();
1358 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1360 //lyxerr << "action: " << cmd.action() << endl;
1361 switch (cmd.action()) {
1363 case LFUN_FINISHED_BACKWARD:
1364 case LFUN_FINISHED_FORWARD:
1365 case LFUN_FINISHED_RIGHT:
1366 case LFUN_FINISHED_LEFT:
1367 //lyxerr << "action: " << cmd.action() << endl;
1368 InsetMathGrid::doDispatch(cur, cmd);
1372 case LFUN_PARAGRAPH_BREAK:
1373 // just swallow this
1376 case LFUN_NEWLINE_INSERT:
1377 // some magic for the common case
1378 if (type_ == hullSimple || type_ == hullEquation) {
1379 cur.recordUndoInset();
1381 cur.bv().buffer().params().use_package("amsmath") == BufferParams::package_on;
1382 mutate(align ? hullAlign : hullEqnArray);
1383 // mutate() may change labels and such.
1384 cur.forceBufferUpdate();
1385 cur.idx() = nrows() * ncols() - 1;
1386 cur.pos() = cur.lastpos();
1388 InsetMathGrid::doDispatch(cur, cmd);
1391 case LFUN_MATH_NUMBER_TOGGLE: {
1392 //lyxerr << "toggling all numbers" << endl;
1393 cur.recordUndoInset();
1394 bool old = numberedType();
1395 if (type_ == hullMultline)
1396 numbered(nrows() - 1, !old);
1398 for (row_type row = 0; row < nrows(); ++row)
1399 numbered(row, !old);
1401 cur.message(old ? _("No number") : _("Number"));
1402 cur.forceBufferUpdate();
1406 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1407 cur.recordUndoInset();
1408 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1409 bool old = numbered(r);
1410 cur.message(old ? _("No number") : _("Number"));
1412 cur.forceBufferUpdate();
1416 case LFUN_LABEL_INSERT: {
1417 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1418 docstring old_label = label(r);
1419 docstring const default_label = from_ascii("eq:");
1420 if (old_label.empty())
1421 old_label = default_label;
1423 InsetCommandParams p(LABEL_CODE);
1424 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1425 string const data = InsetCommand::params2string(p);
1427 if (cmd.argument().empty())
1428 cur.bv().showDialog("label", data);
1430 FuncRequest fr(LFUN_INSET_INSERT, data);
1436 case LFUN_LABEL_COPY_AS_REF: {
1438 if (cmd.argument().empty() && &cur.inset() == this)
1439 // if there is no argument and we're inside math, we retrieve
1440 // the row number from the cursor position.
1441 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1443 // if there is an argument, find the corresponding label, else
1444 // check whether there is at least one label.
1445 for (row = 0; row != nrows(); ++row)
1446 if (numbered_[row] && label_[row]
1447 && (cmd.argument().empty() || label(row) == cmd.argument()))
1454 InsetCommandParams p(REF_CODE, "ref");
1455 p["reference"] = label(row);
1456 cap::clearSelection();
1457 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1461 case LFUN_WORD_DELETE_FORWARD:
1462 case LFUN_CHAR_DELETE_FORWARD:
1463 if (col(cur.idx()) + 1 == ncols()
1464 && cur.pos() == cur.lastpos()
1465 && !cur.selection()) {
1466 if (!label(row(cur.idx())).empty()) {
1467 cur.recordUndoInset();
1468 label(row(cur.idx()), docstring());
1469 } else if (numbered(row(cur.idx()))) {
1470 cur.recordUndoInset();
1471 numbered(row(cur.idx()), false);
1472 cur.forceBufferUpdate();
1474 InsetMathGrid::doDispatch(cur, cmd);
1478 InsetMathGrid::doDispatch(cur, cmd);
1483 case LFUN_INSET_INSERT: {
1484 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1485 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1486 string const name = cmd.getArg(0);
1487 if (name == "label") {
1488 InsetCommandParams p(LABEL_CODE);
1489 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1490 docstring str = p["name"];
1491 cur.recordUndoInset();
1492 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1496 docstring old = label(r);
1499 // The label will take care of the reference update.
1503 // Newly created inset so initialize it.
1504 label_[r]->initView();
1507 cur.forceBufferUpdate();
1510 InsetMathGrid::doDispatch(cur, cmd);
1514 case LFUN_MATH_EXTERN:
1515 cur.recordUndoInset();
1519 case LFUN_MATH_MUTATE: {
1520 cur.recordUndoInset();
1521 row_type row = cur.row();
1522 col_type col = cur.col();
1523 mutate(hullType(cmd.argument()));
1524 cur.idx() = row * ncols() + col;
1525 if (cur.idx() > cur.lastidx()) {
1526 cur.idx() = cur.lastidx();
1527 cur.pos() = cur.lastpos();
1529 if (cur.pos() > cur.lastpos())
1530 cur.pos() = cur.lastpos();
1532 cur.forceBufferUpdate();
1533 // FIXME: find some more clever handling of the selection,
1534 // i.e. preserve it.
1535 cur.clearSelection();
1536 //cur.dispatched(FINISHED);
1540 case LFUN_MATH_DISPLAY: {
1541 cur.recordUndoInset();
1542 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1544 cur.pos() = cur.lastpos();
1545 //cur.dispatched(FINISHED);
1550 InsetMathGrid::doDispatch(cur, cmd);
1556 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1557 FuncStatus & status) const
1559 switch (cmd.action()) {
1560 case LFUN_FINISHED_BACKWARD:
1561 case LFUN_FINISHED_FORWARD:
1562 case LFUN_FINISHED_RIGHT:
1563 case LFUN_FINISHED_LEFT:
1566 case LFUN_NEWLINE_INSERT:
1567 case LFUN_MATH_EXTERN:
1569 status.setEnabled(true);
1572 // we never allow this in math, and we want to bind enter
1573 // to another actions in command-alternatives
1574 case LFUN_PARAGRAPH_BREAK:
1575 status.setEnabled(false);
1577 case LFUN_MATH_MUTATE: {
1578 HullType const ht = hullType(cmd.argument());
1579 status.setOnOff(type_ == ht);
1580 status.setEnabled(true);
1582 if (ht != hullSimple) {
1583 Cursor tmpcur = cur;
1584 while (!tmpcur.empty()) {
1585 InsetCode code = tmpcur.inset().lyxCode();
1586 if (code == BOX_CODE) {
1588 } else if (code == TABULAR_CODE) {
1589 FuncRequest tmpcmd(LFUN_MATH_DISPLAY);
1590 if (tmpcur.getStatus(tmpcmd, status) && !status.enabled())
1598 case LFUN_MATH_DISPLAY: {
1600 if (cur.depth() > 1) {
1601 Inset const & in = cur[cur.depth()-2].inset();
1602 if (in.lyxCode() == SCRIPT_CODE)
1603 enable = display() != Inline;
1605 status.setEnabled(enable);
1609 case LFUN_MATH_NUMBER_TOGGLE:
1610 // FIXME: what is the right test, this or the one of
1612 status.setEnabled(display() != Inline);
1613 status.setOnOff(numberedType());
1616 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1617 // FIXME: what is the right test, this or the one of
1619 bool const enable = (type_ == hullMultline)
1620 ? (nrows() - 1 == cur.row())
1621 : display() != Inline;
1622 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1623 status.setEnabled(enable);
1624 status.setOnOff(enable && numbered(r));
1628 case LFUN_LABEL_INSERT:
1629 status.setEnabled(type_ != hullSimple);
1632 case LFUN_LABEL_COPY_AS_REF: {
1633 bool enabled = false;
1635 if (cmd.argument().empty() && &cur.inset() == this) {
1636 // if there is no argument and we're inside math, we retrieve
1637 // the row number from the cursor position.
1638 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1639 enabled = numberedType() && label_[row] && numbered_[row];
1641 // if there is an argument, find the corresponding label, else
1642 // check whether there is at least one label.
1643 for (row_type row = 0; row != nrows(); ++row) {
1644 if (numbered_[row] && label_[row] &&
1645 (cmd.argument().empty() || label(row) == cmd.argument())) {
1651 status.setEnabled(enabled);
1655 case LFUN_INSET_INSERT:
1656 if (cmd.getArg(0) == "label") {
1657 status.setEnabled(type_ != hullSimple);
1660 return InsetMathGrid::getStatus(cur, cmd, status);
1662 case LFUN_INSET_MODIFY: {
1663 istringstream is(to_utf8(cmd.argument()));
1667 return InsetMathGrid::getStatus(cur, cmd, status);
1670 && (s == "append-row"
1671 || s == "delete-row"
1672 || s == "copy-row")) {
1673 status.message(bformat(
1674 from_utf8(N_("Can't change number of rows in '%1$s'")),
1676 status.setEnabled(false);
1680 && (s == "append-column"
1681 || s == "delete-column"
1682 || s == "copy-column")) {
1683 status.message(bformat(
1684 from_utf8(N_("Can't change number of columns in '%1$s'")),
1686 status.setEnabled(false);
1689 if ((type_ == hullSimple
1690 || type_ == hullEquation
1691 || type_ == hullNone) &&
1692 (s == "add-hline-above" || s == "add-hline-below")) {
1693 status.message(bformat(
1694 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1696 status.setEnabled(false);
1699 if (s == "add-vline-left" || s == "add-vline-right") {
1700 status.message(bformat(
1701 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1703 status.setEnabled(false);
1706 if (s == "valign-top" || s == "valign-middle"
1707 || s == "valign-bottom" || s == "align-left"
1708 || s == "align-center" || s == "align-right") {
1709 status.setEnabled(false);
1712 return InsetMathGrid::getStatus(cur, cmd, status);
1716 return InsetMathGrid::getStatus(cur, cmd, status);
1719 // This cannot really happen, but inserted to shut-up gcc
1720 return InsetMathGrid::getStatus(cur, cmd, status);
1724 /////////////////////////////////////////////////////////////////////
1728 // simply scrap this function if you want
1729 void InsetMathHull::mutateToText()
1732 // translate to latex
1734 latex(os, false, false);
1735 string str = os.str();
1738 Text * lt = view_->cursor().innerText();
1739 string::const_iterator cit = str.begin();
1740 string::const_iterator end = str.end();
1741 for (; cit != end; ++cit)
1742 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1745 //dispatch(LFUN_ESCAPE);
1750 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1751 docstring const & font)
1753 // this whole function is a hack and won't work for incremental font
1756 if (cur.inset().asInsetMath()->name() == font)
1757 cur.handleFont(to_utf8(font));
1759 cur.handleNest(createInsetMath(font, cur.buffer()));
1765 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1770 font.fromString(to_utf8(arg), b);
1771 if (font.fontInfo().color() != Color_inherit) {
1772 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1773 cur.handleNest(at, 0);
1778 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1781 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1782 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1783 enter_front ? idxFirst(cur) : idxLast(cur);
1784 // The inset formula dimension is not necessarily the same as the
1785 // one of the instant preview image, so we have to indicate to the
1786 // BufferView that a metrics update is needed.
1787 cur.screenUpdateFlags(Update::Force);
1791 void InsetMathHull::revealCodes(Cursor & cur) const
1793 if (!cur.inMathed())
1795 odocstringstream os;
1797 cur.message(os.str());
1799 // write something to the minibuffer
1800 // translate to latex
1804 string str = os.str();
1806 string::size_type pos = 0;
1808 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1811 else if (*it == '\0') {
1813 pos = it - str.begin();
1819 res = res.substr(pos - 30);
1820 if (res.size() > 60)
1821 res = res.substr(0, 60);
1827 /////////////////////////////////////////////////////////////////////
1831 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1834 // FIXME: completely broken
1835 static InsetMathHull * lastformula = 0;
1836 static CursorBase current = DocIterator(ibegin(nucleus()));
1838 static string laststr;
1840 if (lastformula != this || laststr != str) {
1841 //lyxerr << "reset lastformula to " << this << endl;
1844 current = ibegin(nucleus());
1846 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1850 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1852 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1853 CursorSlice & top = it.back();
1854 MathData const & a = top.asInsetMath()->cell(top.idx_);
1855 if (a.matchpart(ar, top.pos_)) {
1856 bv->cursor().setSelection(it, ar.size());
1858 top.pos_ += ar.size();
1864 //lyxerr << "not found!" << endl;
1871 void InsetMathHull::write(ostream & os) const
1873 odocstringstream oss;
1874 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1877 os << to_utf8(oss.str());
1881 void InsetMathHull::read(Lexer & lex)
1884 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1885 operator=(*at->asHullInset());
1889 bool InsetMathHull::readQuiet(Lexer & lex)
1892 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1894 operator=(*at->asHullInset());
1899 int InsetMathHull::plaintext(odocstringstream & os,
1900 OutputParams const & op, size_t max_length) const
1902 // disables ASCII-art for export of equations. See #2275.
1903 if (0 && display()) {
1907 TextPainter tpain(dim.width(), dim.height());
1908 drawT(tpain, 0, dim.ascent());
1910 // reset metrics cache to "real" values
1912 return tpain.textheight();
1915 odocstringstream oss;
1916 Encoding const * const enc = encodings.fromLyXName("utf8");
1917 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1920 if (type_ == hullRegexp)
1923 for (row_type r = 0; r < nrows(); ++r) {
1924 for (col_type c = 0; c < ncols(); ++c)
1925 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
1926 // if it's for the TOC, we write just the first line
1927 // and do not include the newline.
1928 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
1933 docstring const str = oss.str();
1939 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1944 if (getType() == hullSimple)
1945 name = from_ascii("inlineequation");
1947 name = from_ascii("informalequation");
1949 docstring bname = name;
1950 if (!label(0).empty())
1951 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1953 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1955 odocstringstream ls;
1956 if (runparams.flavor == OutputParams::XML) {
1957 ms << MTag("alt role='tex' ");
1958 // Workaround for db2latex: db2latex always includes equations with
1959 // \ensuremath{} or \begin{display}\end{display}
1960 // so we strip LyX' math environment
1961 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1962 InsetMathGrid::write(wi);
1963 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1968 InsetMathGrid::mathmlize(ms);
1973 otexstream ols(ls, texrow);
1974 ms << MTag("alt role='tex'");
1975 latex(ols, runparams);
1976 res = texrow.rows();
1977 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1981 ms << from_ascii("<graphic fileref=\"eqn/");
1982 if (!label(0).empty())
1983 ms << sgml::cleanID(buffer(), runparams, label(0));
1985 ms << sgml::uniqueID(from_ascii("anon"));
1987 if (runparams.flavor == OutputParams::XML)
1988 ms << from_ascii("\"/>");
1990 ms << from_ascii("\">");
1992 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1994 return ms.line() + res;
1998 bool InsetMathHull::haveNumbers() const
2000 bool havenumbers = false;
2001 // inline formulas are never numbered (bug 7351 part 3)
2002 if (getType() == hullSimple)
2004 for (size_t i = 0; i != numbered_.size(); ++i) {
2015 // We need to do something about alignment here.
2017 // This duplicates code from InsetMathGrid, but
2018 // we need access here to number information,
2019 // and we simply do not have that in InsetMathGrid.
2020 void InsetMathHull::htmlize(HtmlStream & os) const
2022 bool const havenumbers = haveNumbers();
2023 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2026 os << cell(index(0, 0));
2030 os << MTag("table", "class='mathtable'");
2031 for (row_type row = 0; row < nrows(); ++row) {
2033 for (col_type col = 0; col < ncols(); ++col) {
2035 os << cell(index(row, col));
2040 docstring const & num = numbers_[row];
2042 os << '(' << num << ')';
2047 os << ETag("table");
2051 // this duplicates code from InsetMathGrid, but
2052 // we need access here to number information,
2053 // and we simply do not have that in InsetMathGrid.
2054 void InsetMathHull::mathmlize(MathStream & os) const
2056 bool const havenumbers = haveNumbers();
2057 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2060 os << MTag("mtable");
2061 char const * const celltag = havetable ? "mtd" : "mrow";
2062 // FIXME There does not seem to be wide support at the moment
2063 // for mlabeledtr, so we have to use just mtr for now.
2064 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2065 char const * const rowtag = "mtr";
2066 for (row_type row = 0; row < nrows(); ++row) {
2069 for (col_type col = 0; col < ncols(); ++col) {
2071 << cell(index(row, col))
2077 docstring const & num = numbers_[row];
2079 os << '(' << num << ')';
2086 os << ETag("mtable");
2090 void InsetMathHull::mathAsLatex(WriteStream & os) const
2092 MathEnsurer ensurer(os, false);
2093 bool havenumbers = haveNumbers();
2094 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2097 os << cell(index(0, 0));
2101 os << "<table class='mathtable'>";
2102 for (row_type row = 0; row < nrows(); ++row) {
2104 for (col_type col = 0; col < ncols(); ++col) {
2105 os << "<td class='math'>";
2106 os << cell(index(row, col));
2111 docstring const & num = numbers_[row];
2113 os << '(' << num << ')';
2122 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2124 BufferParams::MathOutput const mathtype =
2125 buffer().masterBuffer()->params().html_math_output;
2127 bool success = false;
2129 // we output all the labels just at the beginning of the equation.
2130 // this should be fine.
2131 for (size_t i = 0; i != label_.size(); ++i) {
2132 InsetLabel const * const il = label_[i];
2138 // FIXME Eventually we would like to do this inset by inset.
2139 if (mathtype == BufferParams::MathML) {
2140 odocstringstream os;
2145 } catch (MathExportException const &) {}
2147 if (getType() == hullSimple)
2148 xs << html::StartTag("math",
2149 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2151 xs << html::StartTag("math",
2152 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2153 xs << XHTMLStream::ESCAPE_NONE
2155 << html::EndTag("math");
2157 } else if (mathtype == BufferParams::HTML) {
2158 odocstringstream os;
2163 } catch (MathExportException const &) {}
2165 string const tag = (getType() == hullSimple) ? "span" : "div";
2166 xs << html::StartTag(tag, "class='formula'", true)
2167 << XHTMLStream::ESCAPE_NONE
2169 << html::EndTag(tag);
2173 // what we actually want is this:
2175 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2177 // || mathtype == BufferParams::Images
2179 // but what follows is equivalent, since we'll enter only if either (a) we
2180 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2181 // aren't doing LaTeX, in which case we are doing Images.
2182 if (!success && mathtype != BufferParams::LaTeX) {
2183 graphics::PreviewImage const * pimage = 0;
2185 loadPreview(docit_);
2186 pimage = preview_->getPreviewImage(buffer());
2187 // FIXME Do we always have png?
2190 if (pimage || op.dryrun) {
2191 string const filename = pimage ? pimage->filename().onlyFileName()
2192 : "previewimage.png";
2194 // if we are not in the master buffer, then we need to see that the
2195 // generated image is copied there; otherwise, preview fails.
2196 Buffer const * mbuf = buffer().masterBuffer();
2197 if (mbuf != &buffer()) {
2198 string mbtmp = mbuf->temppath();
2199 FileName const mbufimg(support::addName(mbtmp, filename));
2200 pimage->filename().copyTo(mbufimg);
2202 // add the file to the list of files to be exported
2203 op.exportdata->addExternalFile("xhtml", pimage->filename());
2206 string const tag = (getType() == hullSimple) ? "span" : "div";
2208 << html::StartTag(tag)
2209 << html::CompTag("img", "src=\"" + filename + "\"")
2210 << html::EndTag(tag)
2216 // so we'll pass this test if we've failed everything else, or
2217 // if mathtype was LaTeX, since we won't have entered any of the
2219 if (!success /* || mathtype != BufferParams::LaTeX */) {
2220 // Unfortunately, we cannot use latexString() because we do not want
2221 // $...$ or whatever.
2222 odocstringstream ls;
2223 WriteStream wi(ls, false, true, WriteStream::wsPreview);
2224 ModeSpecifier specifier(wi, MATH_MODE);
2226 docstring const latex = ls.str();
2228 // class='math' allows for use of jsMath
2229 // http://www.math.union.edu/~dpvc/jsMath/
2231 // probably should allow for some kind of customization here
2232 string const tag = (getType() == hullSimple) ? "span" : "div";
2233 xs << html::StartTag(tag, "class='math'")
2235 << html::EndTag(tag)
2242 void InsetMathHull::toString(odocstream & os) const
2244 odocstringstream ods;
2245 plaintext(ods, OutputParams(0));
2250 void InsetMathHull::forToc(docstring & os, size_t) const
2252 odocstringstream ods;
2260 string InsetMathHull::contextMenuName() const
2262 return "context-math";
2266 void InsetMathHull::recordLocation(DocIterator const & di)