2 * \file InsetMathHull.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 #include "InsetMathHull.h"
15 #include "InsetMathChar.h"
16 #include "InsetMathColor.h"
17 #include "MathExtern.h"
18 #include "MathFactory.h"
19 #include "MathStream.h"
20 #include "MathSupport.h"
23 #include "BufferParams.h"
24 #include "BufferView.h"
26 #include "CutAndPaste.h"
29 #include "FuncRequest.h"
30 #include "FuncStatus.h"
32 #include "LaTeXFeatures.h"
34 #include "MacroTable.h"
35 #include "output_xhtml.h"
36 #include "Paragraph.h"
37 #include "ParIterator.h"
39 #include "TextClass.h"
40 #include "TextPainter.h"
41 #include "TocBackend.h"
43 #include "insets/InsetLabel.h"
44 #include "insets/InsetRef.h"
45 #include "insets/RenderPreview.h"
47 #include "graphics/GraphicsImage.h"
48 #include "graphics/PreviewImage.h"
49 #include "graphics/PreviewLoader.h"
51 #include "frontends/alert.h"
52 #include "frontends/Painter.h"
54 #include "support/convert.h"
55 #include "support/lassert.h"
56 #include "support/debug.h"
57 #include "support/filetools.h"
58 #include "support/gettext.h"
59 #include "support/lstrings.h"
64 using namespace lyx::support;
68 using cap::grabAndEraseSelection;
72 int getCols(HullType type)
89 // returns position of first relation operator in the array
90 // used for "intelligent splitting"
91 size_t firstRelOp(MathData const & ar)
93 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
95 return it - ar.begin();
100 char const * star(bool numbered)
102 return numbered ? "" : "*";
106 } // end anon namespace
109 HullType hullType(docstring const & s)
111 if (s == "none") return hullNone;
112 if (s == "simple") return hullSimple;
113 if (s == "equation") return hullEquation;
114 if (s == "eqnarray") return hullEqnArray;
115 if (s == "align") return hullAlign;
116 if (s == "alignat") return hullAlignAt;
117 if (s == "xalignat") return hullXAlignAt;
118 if (s == "xxalignat") return hullXXAlignAt;
119 if (s == "multline") return hullMultline;
120 if (s == "gather") return hullGather;
121 if (s == "flalign") return hullFlAlign;
122 if (s == "regexp") return hullRegexp;
123 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
128 docstring hullName(HullType type)
131 case hullNone: return from_ascii("none");
132 case hullSimple: return from_ascii("simple");
133 case hullEquation: return from_ascii("equation");
134 case hullEqnArray: return from_ascii("eqnarray");
135 case hullAlign: return from_ascii("align");
136 case hullAlignAt: return from_ascii("alignat");
137 case hullXAlignAt: return from_ascii("xalignat");
138 case hullXXAlignAt: return from_ascii("xxalignat");
139 case hullMultline: return from_ascii("multline");
140 case hullGather: return from_ascii("gather");
141 case hullFlAlign: return from_ascii("flalign");
142 case hullRegexp: return from_ascii("regexp");
144 lyxerr << "unknown hull type '" << type << "'" << endl;
145 return from_ascii("none");
149 static InsetLabel * dummy_pointer = 0;
151 InsetMathHull::InsetMathHull(Buffer * buf)
152 : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, NUMBER),
153 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
154 preview_(new RenderPreview(this)), use_preview_(false)
156 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
157 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
158 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
159 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
166 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
167 : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, NUMBER),
168 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
169 preview_(new RenderPreview(this)), use_preview_(false)
177 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
183 InsetMathHull::~InsetMathHull()
185 for (size_t i = 0; i < label_.size(); ++i)
190 Inset * InsetMathHull::clone() const
192 return new InsetMathHull(*this);
196 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
200 InsetMathGrid::operator=(other);
202 numbered_ = other.numbered_;
203 numbers_ = other.numbers_;
204 buffer_ = other.buffer_;
205 for (size_t i = 0; i < label_.size(); ++i)
207 label_ = other.label_;
208 for (size_t i = 0; i != label_.size(); ++i) {
210 label_[i] = new InsetLabel(*label_[i]);
212 preview_.reset(new RenderPreview(*other.preview_, this));
218 void InsetMathHull::setBuffer(Buffer & buffer)
220 InsetMathGrid::setBuffer(buffer);
222 for (size_t i = 0; i != label_.size(); ++i) {
224 label_[i]->setBuffer(buffer);
229 // FIXME This should really be controlled by the TOC level, or
230 // something of the sort.
232 const char * counters_to_save[] = {"section", "chapter"};
233 unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
237 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
240 //FIXME: buffer_ should be set at creation for this inset! Problem is
241 // This inset is created at too many places (see Parser::parse1() in
246 // if any of the equations are numbered, then we want to save the values
247 // of some of the counters.
249 BufferParams const & bp = buffer_->params();
250 string const & lang = it->getParLanguage(bp)->code();
252 buffer_->masterBuffer()->params().documentClass().counters();
254 // right now, we only need to do this at export time
255 if (utype == OutputUpdate) {
256 for (size_t i = 0; i < numcnts; ++i) {
257 docstring const cnt = from_ascii(counters_to_save[i]);
258 if (cnts.hasCounter(cnt))
259 counter_map[cnt] = cnts.value(cnt);
263 // this has to be done separately
264 docstring const eqstr = from_ascii("equation");
265 if (cnts.hasCounter(eqstr)) {
266 if (utype == OutputUpdate)
267 counter_map[eqstr] = cnts.value(eqstr);
268 for (size_t i = 0; i != label_.size(); ++i) {
270 cnts.step(eqstr, utype);
271 numbers_[i] = cnts.theCounter(eqstr, lang);
273 numbers_[i] = empty_docstring();
279 for (size_t i = 0; i != label_.size(); ++i) {
281 label_[i]->updateBuffer(it, utype);
284 InsetMathGrid::updateBuffer(it, utype);
288 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active) const
291 //FIXME: buffer_ should be set at creation for this inset! Problem is
292 // This inset is created at too many places (see Parser::parse1() in
297 Toc & toc = buffer().tocBackend().toc("equation");
299 for (row_type row = 0; row != nrows(); ++row) {
303 label_[row]->addToToc(pit, output_active);
304 toc.push_back(TocItem(pit, 0, nicelabel(row), output_active));
309 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
315 return InsetMathNest::editXY(cur, x, y);
319 InsetMath::mode_type InsetMathHull::currentMode() const
321 if (type_ == hullNone)
322 return UNDECIDED_MODE;
323 // definitely math mode ...
328 bool InsetMathHull::idxFirst(Cursor & cur) const
336 bool InsetMathHull::idxLast(Cursor & cur) const
338 cur.idx() = nargs() - 1;
339 cur.pos() = cur.lastpos();
344 char InsetMathHull::defaultColAlign(col_type col)
346 if (type_ == hullEqnArray)
348 if (type_ == hullMultline)
350 if (type_ == hullGather)
352 if (type_ >= hullAlign)
353 return "rl"[col & 1];
358 char InsetMathHull::displayColAlign(col_type col, row_type row) const
360 if (type_ == hullMultline) {
363 if (row == nrows() - 1)
366 return InsetMathGrid::displayColAlign(col, row);
370 int InsetMathHull::defaultColSpace(col_type col)
372 if (type_ == hullAlign || type_ == hullAlignAt)
374 if (type_ == hullXAlignAt)
375 return (col & 1) ? 20 : 0;
376 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
377 return (col & 1) ? 40 : 0;
382 docstring InsetMathHull::standardFont() const
387 font_name = from_ascii("texttt");
390 font_name = from_ascii("lyxnochange");
393 font_name = from_ascii("mathnormal");
399 ColorCode InsetMathHull::standardColor() const
405 color = Color_foreground;
414 bool InsetMathHull::previewState(const BufferView *const bv) const
416 if (!editing(bv) && RenderPreview::previewMath()
417 && type_ != hullRegexp)
419 graphics::PreviewImage const * pimage =
420 preview_->getPreviewImage(bv->buffer());
421 return pimage && pimage->image();
428 static const int ERROR_FRAME_WIDTH = 2;
431 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
433 if (previewState(mi.base.bv)) {
434 preview_->metrics(mi, dim);
435 if (previewTooSmall(dim)) {
436 // preview image is too small
437 dim.wid += 2 * ERROR_FRAME_WIDTH;
438 dim.asc += 2 * ERROR_FRAME_WIDTH;
440 // insert a one pixel gap in front of the formula
443 dim.des += displayMargin();
445 // Cache the inset dimension.
446 setDimCache(mi, dim);
450 FontSetChanger dummy1(mi.base, standardFont());
451 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
453 // let the cells adjust themselves
454 InsetMathGrid::metrics(mi, dim);
457 dim.asc += displayMargin();
458 dim.des += displayMargin();
461 if (numberedType()) {
462 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
464 for (row_type row = 0; row < nrows(); ++row)
465 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
471 if (type_ == hullRegexp)
473 // make it at least as high as the current font
476 math_font_max_dim(mi.base.font, asc, des);
477 dim.asc = max(dim.asc, asc);
478 dim.des = max(dim.des, des);
479 // Cache the inset dimension.
480 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
481 setDimCache(mi, dim);
485 bool InsetMathHull::previewTooSmall(Dimension const & dim) const
487 return dim.width() <= 10 && dim.height() <= 10;
491 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
493 BufferView const * const bv = pi.base.bv;
494 if (previewState(bv)) {
495 Dimension const dim = dimension(*pi.base.bv);
496 if (previewTooSmall(dim))
498 return graphics::PreviewLoader::backgroundColor();
504 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
506 Dimension const dim = dimension(*pi.base.bv);
507 if (previewTooSmall(dim)) {
508 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
509 dim.wid, dim.asc + dim.des, backgroundColor(pi));
512 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
513 dim.asc + dim.des - 1, pi.backgroundColor(this));
517 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
519 BufferView const * const bv = pi.base.bv;
520 use_preview_ = previewState(bv);
522 if (type_ == hullRegexp) {
523 Dimension const dim = dimension(*bv);
524 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
525 dim.width() - 2, dim.height() - 2, Color_regexpframe);
529 Dimension const dim = dimension(*bv);
530 if (previewTooSmall(dim)) {
531 // we have an extra frame
532 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
534 // one pixel gap in front
535 preview_->draw(pi, x + 1, y);
537 setPosCache(pi, x, y);
541 ColorCode color = pi.selected && lyxrc.use_system_colors
542 ? Color_selectiontext : standardColor();
543 bool const really_change_color = pi.base.font.color() == Color_none;
544 ColorChanger dummy0(pi.base.font, color, really_change_color);
545 FontSetChanger dummy1(pi.base, standardFont());
546 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
548 InsetMathGrid::draw(pi, x + 1, y);
550 if (numberedType()) {
551 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
552 for (row_type row = 0; row < nrows(); ++row) {
553 int const yy = y + rowinfo_[row].offset_;
554 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
555 docstring const nl = nicelabel(row);
559 setPosCache(pi, x, y);
563 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
566 InsetMathGrid::metricsT(mi, dim);
569 WriteStream wi(os, false, true, WriteStream::wsDefault);
571 dim.wid = os.str().size();
578 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
581 InsetMathGrid::drawT(pain, x, y);
584 WriteStream wi(os, false, true, WriteStream::wsDefault);
586 pain.draw(x, y, os.str().c_str());
591 static docstring latexString(InsetMathHull const & inset)
594 // This has to be static, because a preview snippet or a math
595 // macro containing math in text mode (such as $\text{$\phi$}$ or
596 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
597 // first time as a whole, and the second time only the inner math.
598 // In this last case inset.buffer() would be invalid.
599 static Encoding const * encoding = 0;
600 if (inset.isBufferValid())
601 encoding = &(inset.buffer().params().encoding());
602 WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
608 void InsetMathHull::initUnicodeMath() const
610 // Trigger classification of the unicode symbols in this inset
611 docstring const dummy = latexString(*this);
615 void InsetMathHull::addPreview(DocIterator const & inset_pos,
616 graphics::PreviewLoader & /*ploader*/) const
618 if (RenderPreview::previewMath()) {
619 preparePreview(inset_pos);
624 void InsetMathHull::preparePreview(DocIterator const & pos,
625 bool forexport) const
627 // there is no need to do all the macro stuff if we're not
628 // actually going to generate the preview.
629 if (!RenderPreview::previewMath() && !forexport)
632 Buffer const * buffer = pos.buffer();
634 // collect macros at this position
636 buffer->listMacroNames(macros);
637 MacroNameSet::iterator it = macros.begin();
638 MacroNameSet::iterator end = macros.end();
639 odocstringstream macro_preamble;
640 for (; it != end; ++it) {
641 MacroData const * data = buffer->getMacro(*it, pos, true);
643 data->write(macro_preamble, true);
644 macro_preamble << endl;
649 if (forexport && haveNumbers()) {
650 docstring eqstr = from_ascii("equation");
651 CounterMap::const_iterator it = counter_map.find(eqstr);
652 if (it != counter_map.end()) {
653 int num = it->second;
655 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
656 '{' + convert<docstring>(num) + '}' + '\n';
658 for (size_t i = 0; i != numcnts; ++i) {
659 docstring cnt = from_ascii(counters_to_save[i]);
660 it = counter_map.find(cnt);
661 if (it == counter_map.end())
663 int num = it->second;
665 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
666 '{' + convert<docstring>(num) + '}';
669 docstring const snippet = macro_preamble.str() +
670 setcnt + latexString(*this);
671 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
672 preview_->addPreview(snippet, *buffer, forexport);
676 void InsetMathHull::reloadPreview(DocIterator const & pos) const
679 preview_->startLoading(*pos.buffer());
683 void InsetMathHull::loadPreview(DocIterator const & pos) const
685 bool const forexport = true;
686 preparePreview(pos, forexport);
687 preview_->startLoading(*pos.buffer(), forexport);
691 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
693 if (RenderPreview::previewMath()) {
695 cur.screenUpdateFlags(Update::Force);
701 docstring InsetMathHull::label(row_type row) const
703 LASSERT(row < nrows(), return docstring());
704 if (InsetLabel * il = label_[row])
705 return il->screenLabel();
710 void InsetMathHull::label(row_type row, docstring const & label)
712 //lyxerr << "setting label '" << label << "' for row " << row << endl;
716 label_[row] = dummy_pointer;
719 label_[row]->updateLabelAndRefs(label);
721 label_[row]->setParam("name", label);
725 InsetCommandParams p(LABEL_CODE);
727 label_[row] = new InsetLabel(buffer_, p);
729 label_[row]->setBuffer(buffer());
733 void InsetMathHull::numbered(row_type row, Numbered num)
735 numbered_[row] = num;
736 if (!numbered(row) && label_[row]) {
743 bool InsetMathHull::numbered(row_type row) const
745 return numbered_[row] == NUMBER;
749 bool InsetMathHull::ams() const
767 for (size_t row = 0; row < numbered_.size(); ++row)
768 if (numbered_[row] == NOTAG)
774 Inset::DisplayType InsetMathHull::display() const
776 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
781 bool InsetMathHull::numberedType() const
783 if (type_ == hullNone)
785 if (type_ == hullSimple)
787 if (type_ == hullXXAlignAt)
789 if (type_ == hullRegexp)
791 for (row_type row = 0; row < nrows(); ++row)
798 void InsetMathHull::validate(LaTeXFeatures & features) const
800 if (features.runparams().isLaTeX()) {
802 features.require("amsmath");
804 if (type_ == hullRegexp) {
805 features.require("color");
806 string frcol = lcolor.getLaTeXName(Color_regexpframe);
807 string bgcol = "white";
808 features.addPreambleSnippet(
809 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
810 + frcol + string("}{")
811 + bgcol + string("}{\\ensuremath{\\mathtt{#1}}}}"));
812 features.addPreambleSnippet(
813 string("\\newcommand{\\endregexp}{}"));
816 // Validation is necessary only if not using AMS math.
817 // To be safe, we will always run mathedvalidate.
818 //if (features.amsstyle)
821 //features.binom = true;
822 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
823 // it would be better to do this elsewhere, but we can't validate in
824 // InsetMathMatrix and we have no way, outside MathExtern, to know if
825 // we even have any matrices.
826 features.addCSSSnippet(
827 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
828 "table.matrix td{padding: 0.25px;}\n"
829 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
830 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
832 InsetMathGrid::validate(features);
836 void InsetMathHull::header_write(WriteStream & os) const
838 bool n = numberedType();
852 os << "\n\\begin{equation" << star(n) << "}\n";
862 os << "\n\\begin{" << hullName(type_) << star(n) << "}\n";
867 os << "\n\\begin{" << hullName(type_) << star(n) << '}'
868 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
872 os << "\n\\begin{" << hullName(type_) << '}'
873 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
881 os << "\n\\begin{unknown" << star(n) << "}\n";
887 void InsetMathHull::footer_write(WriteStream & os) const
889 bool n = numberedType();
902 os << "\n\\end{equation" << star(n) << "}\n";
914 os << "\n\\end{" << hullName(type_) << star(n) << "}\n";
918 os << "\n\\end{" << hullName(type_) << "}\n";
922 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
923 os << "\\endregexp{}}";
927 os << "\n\\end{unknown" << star(n) << "}\n";
933 bool InsetMathHull::rowChangeOK() const
936 type_ == hullEqnArray || type_ == hullAlign ||
937 type_ == hullFlAlign || type_ == hullAlignAt ||
938 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
939 type_ == hullGather || type_ == hullMultline;
943 bool InsetMathHull::colChangeOK() const
946 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
947 type_ == hullXAlignAt || type_ == hullXXAlignAt;
951 void InsetMathHull::addRow(row_type row)
956 bool numbered = numberedType();
957 // Move the number and raw pointer, do not call label() (bug 7511)
958 InsetLabel * label = dummy_pointer;
959 docstring number = empty_docstring();
960 if (type_ == hullMultline) {
961 if (row + 1 == nrows()) {
962 numbered_[row] = NONUMBER;
963 swap(label, label_[row]);
964 swap(number, numbers_[row]);
969 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
970 numbers_.insert(numbers_.begin() + row + 1, number);
971 label_.insert(label_.begin() + row + 1, label);
972 InsetMathGrid::addRow(row);
976 void InsetMathHull::swapRow(row_type row)
980 if (row + 1 == nrows())
982 swap(numbered_[row], numbered_[row + 1]);
983 swap(numbers_[row], numbers_[row + 1]);
984 swap(label_[row], label_[row + 1]);
985 InsetMathGrid::swapRow(row);
989 void InsetMathHull::delRow(row_type row)
991 if (nrows() <= 1 || !rowChangeOK())
993 if (row + 1 == nrows() && type_ == hullMultline) {
994 swap(numbered_[row - 1], numbered_[row]);
995 swap(numbers_[row - 1], numbers_[row]);
996 swap(label_[row - 1], label_[row]);
997 InsetMathGrid::delRow(row);
1000 InsetMathGrid::delRow(row);
1001 // The last dummy row has no number info nor a label.
1002 // Test nrows() + 1 because we have already erased the row.
1003 if (row == nrows() + 1)
1005 numbered_.erase(numbered_.begin() + row);
1006 numbers_.erase(numbers_.begin() + row);
1008 label_.erase(label_.begin() + row);
1012 void InsetMathHull::addCol(col_type col)
1016 InsetMathGrid::addCol(col);
1020 void InsetMathHull::delCol(col_type col)
1022 if (ncols() <= 1 || !colChangeOK())
1024 InsetMathGrid::delCol(col);
1028 docstring InsetMathHull::nicelabel(row_type row) const
1032 docstring const & val = numbers_[row];
1034 return '(' + val + ')';
1035 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1039 void InsetMathHull::glueall(HullType type)
1042 for (idx_type i = 0; i < nargs(); ++i)
1044 InsetLabel * label = 0;
1045 if (type == hullEquation) {
1046 // preserve first non-empty label
1047 for (row_type row = 0; row < nrows(); ++row) {
1049 label = label_[row];
1055 *this = InsetMathHull(buffer_, hullSimple);
1062 void InsetMathHull::splitTo2Cols()
1064 LASSERT(ncols() == 1, return);
1065 InsetMathGrid::addCol(1);
1066 for (row_type row = 0; row < nrows(); ++row) {
1067 idx_type const i = 2 * row;
1068 pos_type pos = firstRelOp(cell(i));
1069 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1070 cell(i).erase(pos, cell(i).size());
1075 void InsetMathHull::splitTo3Cols()
1077 LASSERT(ncols() < 3, return);
1080 InsetMathGrid::addCol(2);
1081 for (row_type row = 0; row < nrows(); ++row) {
1082 idx_type const i = 3 * row + 1;
1083 if (!cell(i).empty()) {
1084 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1085 cell(i).erase(1, cell(i).size());
1091 void InsetMathHull::changeCols(col_type cols)
1093 if (ncols() == cols)
1095 else if (ncols() < cols) {
1101 while (ncols() < cols)
1102 InsetMathGrid::addCol(ncols());
1108 for (row_type row = 0; row < nrows(); ++row) {
1109 idx_type const i = row * ncols();
1110 for (col_type col = cols; col < ncols(); ++col) {
1111 cell(i + cols - 1).append(cell(i + col));
1115 while (ncols() > cols) {
1116 InsetMathGrid::delCol(ncols() - 1);
1121 HullType InsetMathHull::getType() const
1127 void InsetMathHull::setType(HullType type)
1134 void InsetMathHull::mutate(HullType newtype)
1136 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1138 // we try to move along the chain
1139 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1141 // +-------------------------------------+
1142 // we use eqnarray as intermediate type for mutations that are not
1143 // directly supported because it handles labels and numbering for
1146 if (newtype == type_) {
1150 else if (newtype < hullNone) {
1155 else if (type_ == hullNone) {
1156 setType(hullSimple);
1161 else if (type_ == hullSimple) {
1162 if (newtype == hullNone) {
1166 setType(hullEquation);
1167 numbered(0, label_[0] ? true : false);
1172 else if (type_ == hullEquation) {
1173 if (newtype < type_) {
1174 setType(hullSimple);
1177 } else if (newtype == hullEqnArray) {
1178 // split it "nicely" on the first relop
1180 setType(hullEqnArray);
1181 } else if (newtype == hullMultline || newtype == hullGather) {
1184 // split it "nicely"
1191 else if (type_ == hullEqnArray) {
1192 if (newtype < type_) {
1195 } else { // align & Co.
1202 else if (type_ == hullAlign || type_ == hullAlignAt ||
1203 type_ == hullXAlignAt || type_ == hullFlAlign) {
1204 if (newtype < hullAlign) {
1206 setType(hullEqnArray);
1208 } else if (newtype == hullGather || newtype == hullMultline) {
1211 } else if (newtype == hullXXAlignAt) {
1212 for (row_type row = 0; row < nrows(); ++row)
1213 numbered(row, false);
1220 else if (type_ == hullXXAlignAt) {
1221 for (row_type row = 0; row < nrows(); ++row)
1222 numbered(row, false);
1223 if (newtype < hullAlign) {
1225 setType(hullEqnArray);
1227 } else if (newtype == hullGather || newtype == hullMultline) {
1235 else if (type_ == hullMultline || type_ == hullGather) {
1236 if (newtype == hullGather || newtype == hullMultline)
1238 else if (newtype == hullAlign || newtype == hullFlAlign ||
1239 newtype == hullAlignAt || newtype == hullXAlignAt) {
1242 } else if (newtype == hullXXAlignAt) {
1244 for (row_type row = 0; row < nrows(); ++row)
1245 numbered(row, false);
1249 setType(hullEqnArray);
1255 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1256 << "' to '" << to_utf8(hullName(newtype))
1257 << "' not implemented" << endl;
1262 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1263 bool last_eoln) const
1266 if (numberedType()) {
1267 if (label_[row] && numbered(row)) {
1268 docstring const name =
1269 latex ? escape(label_[row]->getParam("name"))
1270 : label_[row]->getParam("name");
1271 res += "\\label{" + name + '}';
1273 if (type_ != hullMultline) {
1274 if (numbered_[row] == NONUMBER)
1275 res += "\\nonumber ";
1276 else if (numbered_[row] == NOTAG)
1280 // Never add \\ on the last empty line of eqnarray and friends
1282 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1286 void InsetMathHull::write(WriteStream & os) const
1288 ModeSpecifier specifier(os, MATH_MODE);
1290 InsetMathGrid::write(os);
1295 void InsetMathHull::normalize(NormalStream & os) const
1297 os << "[formula " << hullName(type_) << ' ';
1298 InsetMathGrid::normalize(os);
1303 void InsetMathHull::infoize(odocstream & os) const
1305 os << "Type: " << hullName(type_);
1309 void InsetMathHull::check() const
1311 LATTEST(numbered_.size() == nrows());
1312 LATTEST(numbers_.size() == nrows());
1313 LATTEST(label_.size() == nrows());
1317 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1321 idocstringstream iss(func.argument());
1322 iss >> dlang >> extra;
1324 extra = from_ascii("noextra");
1325 string const lang = to_ascii(dlang);
1327 // FIXME: temporarily disabled
1328 //if (cur.selection()) {
1331 // lyxerr << "use selection: " << ar << endl;
1332 // insert(pipeThroughExtern(lang, extra, ar));
1336 // only inline, display or eqnarray math is allowed
1337 if (getType() > hullEqnArray) {
1338 frontend::Alert::warning(_("Bad math environment"),
1339 _("Computation cannot be performed for AMS "
1340 "math environments.\nChange the math "
1341 "formula type and try again."));
1346 eq.push_back(MathAtom(new InsetMathChar('=')));
1348 // go to first item in line
1349 cur.idx() -= cur.idx() % ncols();
1352 if (getType() == hullSimple) {
1353 size_type pos = cur.cell().find_last(eq);
1355 if (cur.inMathed() && cur.selection()) {
1356 asArray(grabAndEraseSelection(cur), ar);
1357 } else if (!pos == cur.cell().empty()) {
1359 lyxerr << "use whole cell: " << ar << endl;
1361 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1362 lyxerr << "use partial cell form pos: " << pos << endl;
1364 cur.cell().append(eq);
1365 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1366 cur.pos() = cur.lastpos();
1370 if (getType() == hullEquation) {
1371 lyxerr << "use equation inset" << endl;
1372 mutate(hullEqnArray);
1373 MathData & ar = cur.cell();
1374 lyxerr << "use cell: " << ar << endl;
1378 cur.cell() = pipeThroughExtern(lang, extra, ar);
1379 // move to end of line
1380 cur.pos() = cur.lastpos();
1385 lyxerr << "use eqnarray" << endl;
1386 cur.idx() += 2 - cur.idx() % ncols();
1388 MathData ar = cur.cell();
1389 lyxerr << "use cell: " << ar << endl;
1390 // FIXME: temporarily disabled
1396 cur.cell() = pipeThroughExtern(lang, extra, ar);
1397 cur.pos() = cur.lastpos();
1402 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1404 //lyxerr << "action: " << cmd.action() << endl;
1405 switch (cmd.action()) {
1407 case LFUN_FINISHED_BACKWARD:
1408 case LFUN_FINISHED_FORWARD:
1409 case LFUN_FINISHED_RIGHT:
1410 case LFUN_FINISHED_LEFT:
1411 //lyxerr << "action: " << cmd.action() << endl;
1412 InsetMathGrid::doDispatch(cur, cmd);
1416 case LFUN_PARAGRAPH_BREAK:
1417 // just swallow this
1420 case LFUN_NEWLINE_INSERT:
1421 // some magic for the common case
1422 if (type_ == hullSimple || type_ == hullEquation) {
1423 cur.recordUndoInset();
1425 cur.bv().buffer().params().use_package("amsmath") == BufferParams::package_on;
1426 mutate(align ? hullAlign : hullEqnArray);
1427 // mutate() may change labels and such.
1428 cur.forceBufferUpdate();
1429 cur.idx() = nrows() * ncols() - 1;
1430 cur.pos() = cur.lastpos();
1432 InsetMathGrid::doDispatch(cur, cmd);
1435 case LFUN_MATH_NUMBER_TOGGLE: {
1436 //lyxerr << "toggling all numbers" << endl;
1437 cur.recordUndoInset();
1438 bool old = numberedType();
1439 if (type_ == hullMultline)
1440 numbered(nrows() - 1, !old);
1442 for (row_type row = 0; row < nrows(); ++row)
1443 numbered(row, !old);
1445 cur.message(old ? _("No number") : _("Number"));
1446 cur.forceBufferUpdate();
1450 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1451 cur.recordUndoInset();
1452 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1453 bool old = numbered(r);
1454 cur.message(old ? _("No number") : _("Number"));
1456 cur.forceBufferUpdate();
1460 case LFUN_LABEL_INSERT: {
1461 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1462 docstring old_label = label(r);
1463 docstring const default_label = from_ascii("eq:");
1464 if (old_label.empty())
1465 old_label = default_label;
1467 InsetCommandParams p(LABEL_CODE);
1468 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1469 string const data = InsetCommand::params2string(p);
1471 if (cmd.argument().empty())
1472 cur.bv().showDialog("label", data);
1474 FuncRequest fr(LFUN_INSET_INSERT, data);
1480 case LFUN_LABEL_COPY_AS_REFERENCE: {
1482 if (cmd.argument().empty() && &cur.inset() == this)
1483 // if there is no argument and we're inside math, we retrieve
1484 // the row number from the cursor position.
1485 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1487 // if there is an argument, find the corresponding label, else
1488 // check whether there is at least one label.
1489 for (row = 0; row != nrows(); ++row)
1490 if (numbered(row) && label_[row]
1491 && (cmd.argument().empty() || label(row) == cmd.argument()))
1498 InsetCommandParams p(REF_CODE, "ref");
1499 p["reference"] = label(row);
1500 cap::clearSelection();
1501 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1505 case LFUN_WORD_DELETE_FORWARD:
1506 case LFUN_CHAR_DELETE_FORWARD:
1507 if (col(cur.idx()) + 1 == ncols()
1508 && cur.pos() == cur.lastpos()
1509 && !cur.selection()) {
1510 if (!label(row(cur.idx())).empty()) {
1511 cur.recordUndoInset();
1512 label(row(cur.idx()), docstring());
1513 } else if (numbered(row(cur.idx()))) {
1514 cur.recordUndoInset();
1515 numbered(row(cur.idx()), false);
1516 cur.forceBufferUpdate();
1518 InsetMathGrid::doDispatch(cur, cmd);
1522 InsetMathGrid::doDispatch(cur, cmd);
1527 case LFUN_INSET_INSERT: {
1528 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1529 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1530 string const name = cmd.getArg(0);
1531 if (name == "label") {
1532 InsetCommandParams p(LABEL_CODE);
1533 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1534 docstring str = p["name"];
1535 cur.recordUndoInset();
1536 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1540 docstring old = label(r);
1543 // The label will take care of the reference update.
1547 // Newly created inset so initialize it.
1548 label_[r]->initView();
1551 cur.forceBufferUpdate();
1554 InsetMathGrid::doDispatch(cur, cmd);
1558 case LFUN_MATH_EXTERN:
1559 cur.recordUndoInset();
1563 case LFUN_MATH_MUTATE: {
1564 cur.recordUndoInset();
1565 row_type row = cur.row();
1566 col_type col = cur.col();
1567 mutate(hullType(cmd.argument()));
1568 cur.idx() = row * ncols() + col;
1569 if (cur.idx() > cur.lastidx()) {
1570 cur.idx() = cur.lastidx();
1571 cur.pos() = cur.lastpos();
1573 if (cur.pos() > cur.lastpos())
1574 cur.pos() = cur.lastpos();
1576 cur.forceBufferUpdate();
1577 // FIXME: find some more clever handling of the selection,
1578 // i.e. preserve it.
1579 cur.clearSelection();
1580 //cur.dispatched(FINISHED);
1584 case LFUN_MATH_DISPLAY: {
1585 cur.recordUndoInset();
1586 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1588 cur.pos() = cur.lastpos();
1589 //cur.dispatched(FINISHED);
1594 InsetMathGrid::doDispatch(cur, cmd);
1600 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1601 FuncStatus & status) const
1603 switch (cmd.action()) {
1604 case LFUN_FINISHED_BACKWARD:
1605 case LFUN_FINISHED_FORWARD:
1606 case LFUN_FINISHED_RIGHT:
1607 case LFUN_FINISHED_LEFT:
1610 case LFUN_NEWLINE_INSERT:
1611 case LFUN_MATH_EXTERN:
1613 status.setEnabled(true);
1616 // we never allow this in math, and we want to bind enter
1617 // to another actions in command-alternatives
1618 case LFUN_PARAGRAPH_BREAK:
1619 status.setEnabled(false);
1621 case LFUN_MATH_MUTATE: {
1622 HullType const ht = hullType(cmd.argument());
1623 status.setOnOff(type_ == ht);
1624 status.setEnabled(true);
1626 if (ht != hullSimple) {
1627 Cursor tmpcur = cur;
1628 while (!tmpcur.empty()) {
1629 InsetCode code = tmpcur.inset().lyxCode();
1630 if (code == BOX_CODE) {
1632 } else if (code == TABULAR_CODE) {
1633 FuncRequest tmpcmd(LFUN_MATH_DISPLAY);
1634 if (tmpcur.getStatus(tmpcmd, status) && !status.enabled())
1642 case LFUN_MATH_DISPLAY: {
1644 if (cur.depth() > 1) {
1645 Inset const & in = cur[cur.depth()-2].inset();
1646 if (in.lyxCode() == SCRIPT_CODE)
1647 enable = display() != Inline;
1649 status.setEnabled(enable);
1653 case LFUN_MATH_NUMBER_TOGGLE:
1654 // FIXME: what is the right test, this or the one of
1656 status.setEnabled(display() != Inline);
1657 status.setOnOff(numberedType());
1660 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1661 // FIXME: what is the right test, this or the one of
1663 bool const enable = (type_ == hullMultline)
1664 ? (nrows() - 1 == cur.row())
1665 : display() != Inline;
1666 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1667 status.setEnabled(enable);
1668 status.setOnOff(enable && numbered(r));
1672 case LFUN_LABEL_INSERT:
1673 status.setEnabled(type_ != hullSimple);
1676 case LFUN_LABEL_COPY_AS_REFERENCE: {
1677 bool enabled = false;
1679 if (cmd.argument().empty() && &cur.inset() == this) {
1680 // if there is no argument and we're inside math, we retrieve
1681 // the row number from the cursor position.
1682 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1683 enabled = numberedType() && label_[row] && numbered(row);
1685 // if there is an argument, find the corresponding label, else
1686 // check whether there is at least one label.
1687 for (row_type row = 0; row != nrows(); ++row) {
1688 if (numbered(row) && label_[row] &&
1689 (cmd.argument().empty() || label(row) == cmd.argument())) {
1695 status.setEnabled(enabled);
1699 case LFUN_INSET_INSERT:
1700 if (cmd.getArg(0) == "label") {
1701 status.setEnabled(type_ != hullSimple);
1704 return InsetMathGrid::getStatus(cur, cmd, status);
1706 case LFUN_INSET_MODIFY: {
1707 istringstream is(to_utf8(cmd.argument()));
1711 return InsetMathGrid::getStatus(cur, cmd, status);
1714 && (s == "append-row"
1715 || s == "delete-row"
1716 || s == "copy-row")) {
1717 status.message(bformat(
1718 from_utf8(N_("Can't change number of rows in '%1$s'")),
1720 status.setEnabled(false);
1724 && (s == "append-column"
1725 || s == "delete-column"
1726 || s == "copy-column")) {
1727 status.message(bformat(
1728 from_utf8(N_("Can't change number of columns in '%1$s'")),
1730 status.setEnabled(false);
1733 if ((type_ == hullSimple
1734 || type_ == hullEquation
1735 || type_ == hullNone) &&
1736 (s == "add-hline-above" || s == "add-hline-below")) {
1737 status.message(bformat(
1738 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1740 status.setEnabled(false);
1743 if (s == "add-vline-left" || s == "add-vline-right") {
1744 status.message(bformat(
1745 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1747 status.setEnabled(false);
1750 if (s == "valign-top" || s == "valign-middle"
1751 || s == "valign-bottom" || s == "align-left"
1752 || s == "align-center" || s == "align-right") {
1753 status.setEnabled(false);
1756 return InsetMathGrid::getStatus(cur, cmd, status);
1760 return InsetMathGrid::getStatus(cur, cmd, status);
1763 // This cannot really happen, but inserted to shut-up gcc
1764 return InsetMathGrid::getStatus(cur, cmd, status);
1768 /////////////////////////////////////////////////////////////////////
1772 // simply scrap this function if you want
1773 void InsetMathHull::mutateToText()
1776 // translate to latex
1778 latex(os, false, false);
1779 string str = os.str();
1782 Text * lt = view_->cursor().innerText();
1783 string::const_iterator cit = str.begin();
1784 string::const_iterator end = str.end();
1785 for (; cit != end; ++cit)
1786 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1789 //dispatch(LFUN_ESCAPE);
1794 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1795 docstring const & font)
1797 // this whole function is a hack and won't work for incremental font
1800 if (cur.inset().asInsetMath()->name() == font)
1801 cur.handleFont(to_utf8(font));
1803 cur.handleNest(createInsetMath(font, cur.buffer()));
1809 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1814 font.fromString(to_utf8(arg), b);
1815 if (font.fontInfo().color() != Color_inherit) {
1816 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1817 cur.handleNest(at, 0);
1822 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1825 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1826 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1827 enter_front ? idxFirst(cur) : idxLast(cur);
1828 // The inset formula dimension is not necessarily the same as the
1829 // one of the instant preview image, so we have to indicate to the
1830 // BufferView that a metrics update is needed.
1831 cur.screenUpdateFlags(Update::Force);
1835 void InsetMathHull::revealCodes(Cursor & cur) const
1837 if (!cur.inMathed())
1839 odocstringstream os;
1841 cur.message(os.str());
1843 // write something to the minibuffer
1844 // translate to latex
1848 string str = os.str();
1850 string::size_type pos = 0;
1852 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1855 else if (*it == '\0') {
1857 pos = it - str.begin();
1863 res = res.substr(pos - 30);
1864 if (res.size() > 60)
1865 res = res.substr(0, 60);
1871 /////////////////////////////////////////////////////////////////////
1875 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1878 // FIXME: completely broken
1879 static InsetMathHull * lastformula = 0;
1880 static CursorBase current = DocIterator(ibegin(nucleus()));
1882 static string laststr;
1884 if (lastformula != this || laststr != str) {
1885 //lyxerr << "reset lastformula to " << this << endl;
1888 current = ibegin(nucleus());
1890 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1894 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1896 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1897 CursorSlice & top = it.back();
1898 MathData const & a = top.asInsetMath()->cell(top.idx_);
1899 if (a.matchpart(ar, top.pos_)) {
1900 bv->cursor().setSelection(it, ar.size());
1902 top.pos_ += ar.size();
1908 //lyxerr << "not found!" << endl;
1915 void InsetMathHull::write(ostream & os) const
1917 odocstringstream oss;
1918 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1921 os << to_utf8(oss.str());
1925 void InsetMathHull::read(Lexer & lex)
1928 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1929 operator=(*at->asHullInset());
1933 bool InsetMathHull::readQuiet(Lexer & lex)
1936 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1938 operator=(*at->asHullInset());
1943 int InsetMathHull::plaintext(odocstringstream & os,
1944 OutputParams const & op, size_t max_length) const
1946 // disables ASCII-art for export of equations. See #2275.
1947 if (0 && display()) {
1951 TextPainter tpain(dim.width(), dim.height());
1952 drawT(tpain, 0, dim.ascent());
1954 // reset metrics cache to "real" values
1956 return tpain.textheight();
1959 odocstringstream oss;
1960 Encoding const * const enc = encodings.fromLyXName("utf8");
1961 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1964 if (type_ == hullRegexp)
1967 for (row_type r = 0; r < nrows(); ++r) {
1968 for (col_type c = 0; c < ncols(); ++c)
1969 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
1970 // if it's for the TOC, we write just the first line
1971 // and do not include the newline.
1972 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
1977 docstring const str = oss.str();
1983 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1988 if (getType() == hullSimple)
1989 name = from_ascii("inlineequation");
1991 name = from_ascii("informalequation");
1993 docstring bname = name;
1994 if (!label(0).empty())
1995 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1997 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1999 odocstringstream ls;
2000 if (runparams.flavor == OutputParams::XML) {
2001 ms << MTag("alt role='tex' ");
2002 // Workaround for db2latex: db2latex always includes equations with
2003 // \ensuremath{} or \begin{display}\end{display}
2004 // so we strip LyX' math environment
2005 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
2006 InsetMathGrid::write(wi);
2007 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2012 InsetMathGrid::mathmlize(ms);
2017 otexstream ols(ls, texrow);
2018 ms << MTag("alt role='tex'");
2019 latex(ols, runparams);
2020 res = texrow.rows();
2021 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2025 ms << from_ascii("<graphic fileref=\"eqn/");
2026 if (!label(0).empty())
2027 ms << sgml::cleanID(buffer(), runparams, label(0));
2029 ms << sgml::uniqueID(from_ascii("anon"));
2031 if (runparams.flavor == OutputParams::XML)
2032 ms << from_ascii("\"/>");
2034 ms << from_ascii("\">");
2036 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2038 return ms.line() + res;
2042 bool InsetMathHull::haveNumbers() const
2044 bool havenumbers = false;
2045 // inline formulas are never numbered (bug 7351 part 3)
2046 if (getType() == hullSimple)
2048 for (size_t i = 0; i != numbered_.size(); ++i) {
2059 // We need to do something about alignment here.
2061 // This duplicates code from InsetMathGrid, but
2062 // we need access here to number information,
2063 // and we simply do not have that in InsetMathGrid.
2064 void InsetMathHull::htmlize(HtmlStream & os) const
2066 bool const havenumbers = haveNumbers();
2067 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2070 os << cell(index(0, 0));
2074 os << MTag("table", "class='mathtable'");
2075 for (row_type row = 0; row < nrows(); ++row) {
2077 for (col_type col = 0; col < ncols(); ++col) {
2079 os << cell(index(row, col));
2084 docstring const & num = numbers_[row];
2086 os << '(' << num << ')';
2091 os << ETag("table");
2095 // this duplicates code from InsetMathGrid, but
2096 // we need access here to number information,
2097 // and we simply do not have that in InsetMathGrid.
2098 void InsetMathHull::mathmlize(MathStream & os) const
2100 bool const havenumbers = haveNumbers();
2101 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2104 os << MTag("mtable");
2105 char const * const celltag = havetable ? "mtd" : "mrow";
2106 // FIXME There does not seem to be wide support at the moment
2107 // for mlabeledtr, so we have to use just mtr for now.
2108 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2109 char const * const rowtag = "mtr";
2110 for (row_type row = 0; row < nrows(); ++row) {
2113 for (col_type col = 0; col < ncols(); ++col) {
2115 << cell(index(row, col))
2121 docstring const & num = numbers_[row];
2123 os << '(' << num << ')';
2130 os << ETag("mtable");
2134 void InsetMathHull::mathAsLatex(WriteStream & os) const
2136 MathEnsurer ensurer(os, false);
2137 bool havenumbers = haveNumbers();
2138 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2141 os << cell(index(0, 0));
2145 os << "<table class='mathtable'>";
2146 for (row_type row = 0; row < nrows(); ++row) {
2148 for (col_type col = 0; col < ncols(); ++col) {
2149 os << "<td class='math'>";
2150 os << cell(index(row, col));
2155 docstring const & num = numbers_[row];
2157 os << '(' << num << ')';
2166 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2168 BufferParams::MathOutput const mathtype =
2169 buffer().masterBuffer()->params().html_math_output;
2171 bool success = false;
2173 // we output all the labels just at the beginning of the equation.
2174 // this should be fine.
2175 for (size_t i = 0; i != label_.size(); ++i) {
2176 InsetLabel const * const il = label_[i];
2182 // FIXME Eventually we would like to do this inset by inset.
2183 if (mathtype == BufferParams::MathML) {
2184 odocstringstream os;
2189 } catch (MathExportException const &) {}
2191 if (getType() == hullSimple)
2192 xs << html::StartTag("math",
2193 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2195 xs << html::StartTag("math",
2196 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2197 xs << XHTMLStream::ESCAPE_NONE
2199 << html::EndTag("math");
2201 } else if (mathtype == BufferParams::HTML) {
2202 odocstringstream os;
2207 } catch (MathExportException const &) {}
2209 string const tag = (getType() == hullSimple) ? "span" : "div";
2210 xs << html::StartTag(tag, "class='formula'", true)
2211 << XHTMLStream::ESCAPE_NONE
2213 << html::EndTag(tag);
2217 // what we actually want is this:
2219 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2221 // || mathtype == BufferParams::Images
2223 // but what follows is equivalent, since we'll enter only if either (a) we
2224 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2225 // aren't doing LaTeX, in which case we are doing Images.
2226 if (!success && mathtype != BufferParams::LaTeX) {
2227 graphics::PreviewImage const * pimage = 0;
2229 loadPreview(docit_);
2230 pimage = preview_->getPreviewImage(buffer());
2231 // FIXME Do we always have png?
2234 if (pimage || op.dryrun) {
2235 string const filename = pimage ? pimage->filename().onlyFileName()
2236 : "previewimage.png";
2238 // if we are not in the master buffer, then we need to see that the
2239 // generated image is copied there; otherwise, preview fails.
2240 Buffer const * mbuf = buffer().masterBuffer();
2241 if (mbuf != &buffer()) {
2242 string mbtmp = mbuf->temppath();
2243 FileName const mbufimg(support::addName(mbtmp, filename));
2244 pimage->filename().copyTo(mbufimg);
2246 // add the file to the list of files to be exported
2247 op.exportdata->addExternalFile("xhtml", pimage->filename());
2250 string const tag = (getType() == hullSimple) ? "span" : "div";
2252 << html::StartTag(tag)
2253 << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2254 << html::EndTag(tag)
2260 // so we'll pass this test if we've failed everything else, or
2261 // if mathtype was LaTeX, since we won't have entered any of the
2263 if (!success /* || mathtype != BufferParams::LaTeX */) {
2264 // Unfortunately, we cannot use latexString() because we do not want
2265 // $...$ or whatever.
2266 odocstringstream ls;
2267 WriteStream wi(ls, false, true, WriteStream::wsPreview);
2268 ModeSpecifier specifier(wi, MATH_MODE);
2270 docstring const latex = ls.str();
2272 // class='math' allows for use of jsMath
2273 // http://www.math.union.edu/~dpvc/jsMath/
2275 // probably should allow for some kind of customization here
2276 string const tag = (getType() == hullSimple) ? "span" : "div";
2277 xs << html::StartTag(tag, "class='math'")
2279 << html::EndTag(tag)
2286 void InsetMathHull::toString(odocstream & os) const
2288 odocstringstream ods;
2289 plaintext(ods, OutputParams(0));
2294 void InsetMathHull::forOutliner(docstring & os, size_t) const
2296 odocstringstream ods;
2304 string InsetMathHull::contextMenuName() const
2306 return "context-math";
2310 void InsetMathHull::recordLocation(DocIterator const & di)