2 * \file InsetMathHull.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 #include "InsetMathHull.h"
15 #include "InsetMathChar.h"
16 #include "InsetMathColor.h"
17 #include "MathExtern.h"
18 #include "MathFactory.h"
19 #include "MathStream.h"
20 #include "MathSupport.h"
23 #include "BufferParams.h"
24 #include "BufferView.h"
26 #include "CutAndPaste.h"
29 #include "FuncRequest.h"
30 #include "FuncStatus.h"
32 #include "LaTeXFeatures.h"
34 #include "MacroTable.h"
35 #include "output_xhtml.h"
36 #include "Paragraph.h"
37 #include "ParIterator.h"
39 #include "TextClass.h"
40 #include "TextPainter.h"
41 #include "TocBackend.h"
43 #include "insets/InsetLabel.h"
44 #include "insets/InsetRef.h"
45 #include "insets/RenderPreview.h"
47 #include "graphics/GraphicsImage.h"
48 #include "graphics/PreviewImage.h"
49 #include "graphics/PreviewLoader.h"
51 #include "frontends/alert.h"
52 #include "frontends/Painter.h"
54 #include "support/convert.h"
55 #include "support/lassert.h"
56 #include "support/debug.h"
57 #include "support/filetools.h"
58 #include "support/gettext.h"
59 #include "support/lstrings.h"
64 using namespace lyx::support;
68 using cap::grabAndEraseSelection;
69 using cap::reduceSelectionToOneCell;
73 int getCols(HullType type)
90 // returns position of first relation operator in the array
91 // used for "intelligent splitting"
92 size_t firstRelOp(MathData const & ar)
94 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
96 return it - ar.begin();
101 char const * star(bool numbered)
103 return numbered ? "" : "*";
107 } // end anon namespace
110 HullType hullType(docstring const & s)
112 if (s == "none") return hullNone;
113 if (s == "simple") return hullSimple;
114 if (s == "equation") return hullEquation;
115 if (s == "eqnarray") return hullEqnArray;
116 if (s == "align") return hullAlign;
117 if (s == "alignat") return hullAlignAt;
118 if (s == "xalignat") return hullXAlignAt;
119 if (s == "xxalignat") return hullXXAlignAt;
120 if (s == "multline") return hullMultline;
121 if (s == "gather") return hullGather;
122 if (s == "flalign") return hullFlAlign;
123 if (s == "regexp") return hullRegexp;
124 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
129 docstring hullName(HullType type)
132 case hullNone: return from_ascii("none");
133 case hullSimple: return from_ascii("simple");
134 case hullEquation: return from_ascii("equation");
135 case hullEqnArray: return from_ascii("eqnarray");
136 case hullAlign: return from_ascii("align");
137 case hullAlignAt: return from_ascii("alignat");
138 case hullXAlignAt: return from_ascii("xalignat");
139 case hullXXAlignAt: return from_ascii("xxalignat");
140 case hullMultline: return from_ascii("multline");
141 case hullGather: return from_ascii("gather");
142 case hullFlAlign: return from_ascii("flalign");
143 case hullRegexp: return from_ascii("regexp");
145 lyxerr << "unknown hull type '" << type << "'" << endl;
146 return from_ascii("none");
150 static InsetLabel * dummy_pointer = 0;
152 InsetMathHull::InsetMathHull(Buffer * buf)
153 : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, NUMBER),
154 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
155 preview_(new RenderPreview(this)), use_preview_(false)
157 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
158 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
159 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
160 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
167 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
168 : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, NUMBER),
169 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
170 preview_(new RenderPreview(this)), use_preview_(false)
178 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
184 InsetMathHull::~InsetMathHull()
186 for (size_t i = 0; i < label_.size(); ++i)
191 Inset * InsetMathHull::clone() const
193 return new InsetMathHull(*this);
197 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
201 InsetMathGrid::operator=(other);
203 numbered_ = other.numbered_;
204 numbers_ = other.numbers_;
205 buffer_ = other.buffer_;
206 for (size_t i = 0; i < label_.size(); ++i)
208 label_ = other.label_;
209 for (size_t i = 0; i != label_.size(); ++i) {
211 label_[i] = new InsetLabel(*label_[i]);
213 preview_.reset(new RenderPreview(*other.preview_, this));
219 void InsetMathHull::setBuffer(Buffer & buffer)
221 InsetMathGrid::setBuffer(buffer);
223 for (size_t i = 0; i != label_.size(); ++i) {
225 label_[i]->setBuffer(buffer);
230 // FIXME This should really be controlled by the TOC level, or
231 // something of the sort.
233 const char * counters_to_save[] = {"section", "chapter"};
234 unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
238 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
241 //FIXME: buffer_ should be set at creation for this inset! Problem is
242 // This inset is created at too many places (see Parser::parse1() in
247 // if any of the equations are numbered, then we want to save the values
248 // of some of the counters.
250 BufferParams const & bp = buffer_->params();
251 string const & lang = it->getParLanguage(bp)->code();
253 buffer_->masterBuffer()->params().documentClass().counters();
255 // right now, we only need to do this at export time
256 if (utype == OutputUpdate) {
257 for (size_t i = 0; i < numcnts; ++i) {
258 docstring const cnt = from_ascii(counters_to_save[i]);
259 if (cnts.hasCounter(cnt))
260 counter_map[cnt] = cnts.value(cnt);
264 // this has to be done separately
265 docstring const eqstr = from_ascii("equation");
266 if (cnts.hasCounter(eqstr)) {
267 if (utype == OutputUpdate)
268 counter_map[eqstr] = cnts.value(eqstr);
269 for (size_t i = 0; i != label_.size(); ++i) {
271 cnts.step(eqstr, utype);
272 numbers_[i] = cnts.theCounter(eqstr, lang);
274 numbers_[i] = empty_docstring();
280 for (size_t i = 0; i != label_.size(); ++i) {
282 label_[i]->updateBuffer(it, utype);
285 InsetMathGrid::updateBuffer(it, utype);
289 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active) const
292 //FIXME: buffer_ should be set at creation for this inset! Problem is
293 // This inset is created at too many places (see Parser::parse1() in
298 Toc & toc = buffer().tocBackend().toc("equation");
300 for (row_type row = 0; row != nrows(); ++row) {
304 label_[row]->addToToc(pit, output_active);
305 toc.push_back(TocItem(pit, 0, nicelabel(row), output_active));
310 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
316 return InsetMathNest::editXY(cur, x, y);
320 InsetMath::mode_type InsetMathHull::currentMode() const
322 if (type_ == hullNone)
323 return UNDECIDED_MODE;
324 // definitely math mode ...
329 bool InsetMathHull::idxFirst(Cursor & cur) const
337 bool InsetMathHull::idxLast(Cursor & cur) const
339 cur.idx() = nargs() - 1;
340 cur.pos() = cur.lastpos();
345 char InsetMathHull::defaultColAlign(col_type col)
347 if (type_ == hullEqnArray)
349 if (type_ == hullMultline)
351 if (type_ == hullGather)
353 if (type_ >= hullAlign)
354 return "rl"[col & 1];
359 char InsetMathHull::displayColAlign(col_type col, row_type row) const
361 if (type_ == hullMultline) {
364 if (row == nrows() - 1)
367 return InsetMathGrid::displayColAlign(col, row);
371 int InsetMathHull::defaultColSpace(col_type col)
373 if (type_ == hullAlign || type_ == hullAlignAt)
375 if (type_ == hullXAlignAt)
376 return (col & 1) ? 20 : 0;
377 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
378 return (col & 1) ? 40 : 0;
383 docstring InsetMathHull::standardFont() const
388 font_name = from_ascii("texttt");
391 font_name = from_ascii("lyxnochange");
394 font_name = from_ascii("mathnormal");
400 ColorCode InsetMathHull::standardColor() const
406 color = Color_foreground;
415 bool InsetMathHull::previewState(const BufferView *const bv) const
417 if (!editing(bv) && RenderPreview::previewMath()
418 && type_ != hullRegexp)
420 graphics::PreviewImage const * pimage =
421 preview_->getPreviewImage(bv->buffer());
422 return pimage && pimage->image();
429 static const int ERROR_FRAME_WIDTH = 2;
432 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
434 if (previewState(mi.base.bv)) {
435 preview_->metrics(mi, dim);
436 if (previewTooSmall(dim)) {
437 // preview image is too small
438 dim.wid += 2 * ERROR_FRAME_WIDTH;
439 dim.asc += 2 * ERROR_FRAME_WIDTH;
441 // insert a one pixel gap in front of the formula
444 dim.des += displayMargin();
446 // Cache the inset dimension.
447 setDimCache(mi, dim);
451 FontSetChanger dummy1(mi.base, standardFont());
452 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
454 // let the cells adjust themselves
455 InsetMathGrid::metrics(mi, dim);
458 dim.asc += displayMargin();
459 dim.des += displayMargin();
462 if (numberedType()) {
463 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
465 for (row_type row = 0; row < nrows(); ++row)
466 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
472 if (type_ == hullRegexp)
474 // make it at least as high as the current font
477 math_font_max_dim(mi.base.font, asc, des);
478 dim.asc = max(dim.asc, asc);
479 dim.des = max(dim.des, des);
480 // Cache the inset dimension.
481 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
482 setDimCache(mi, dim);
486 bool InsetMathHull::previewTooSmall(Dimension const & dim) const
488 return dim.width() <= 10 && dim.height() <= 10;
492 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
494 BufferView const * const bv = pi.base.bv;
495 if (previewState(bv)) {
496 Dimension const dim = dimension(*pi.base.bv);
497 if (previewTooSmall(dim))
499 return graphics::PreviewLoader::backgroundColor();
505 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
507 Dimension const dim = dimension(*pi.base.bv);
508 if (previewTooSmall(dim)) {
509 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
510 dim.wid, dim.asc + dim.des, backgroundColor(pi));
513 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
514 dim.asc + dim.des - 1, pi.backgroundColor(this));
518 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
520 BufferView const * const bv = pi.base.bv;
521 use_preview_ = previewState(bv);
523 if (type_ == hullRegexp) {
524 Dimension const dim = dimension(*bv);
525 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
526 dim.width() - 2, dim.height() - 2, Color_regexpframe);
530 Dimension const dim = dimension(*bv);
531 if (previewTooSmall(dim)) {
532 // we have an extra frame
533 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
535 // one pixel gap in front
536 preview_->draw(pi, x + 1, y);
538 setPosCache(pi, x, y);
542 ColorCode color = pi.selected && lyxrc.use_system_colors
543 ? Color_selectiontext : standardColor();
544 bool const really_change_color = pi.base.font.color() == Color_none;
545 ColorChanger dummy0(pi.base.font, color, really_change_color);
546 FontSetChanger dummy1(pi.base, standardFont());
547 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
549 InsetMathGrid::draw(pi, x + 1, y);
551 if (numberedType()) {
552 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
553 for (row_type row = 0; row < nrows(); ++row) {
554 int const yy = y + rowinfo_[row].offset_;
555 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
556 docstring const nl = nicelabel(row);
560 setPosCache(pi, x, y);
564 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
567 InsetMathGrid::metricsT(mi, dim);
570 WriteStream wi(os, false, true, WriteStream::wsDefault);
572 dim.wid = os.str().size();
579 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
582 InsetMathGrid::drawT(pain, x, y);
585 WriteStream wi(os, false, true, WriteStream::wsDefault);
587 pain.draw(x, y, os.str().c_str());
592 static docstring latexString(InsetMathHull const & inset)
595 // This has to be static, because a preview snippet or a math
596 // macro containing math in text mode (such as $\text{$\phi$}$ or
597 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
598 // first time as a whole, and the second time only the inner math.
599 // In this last case inset.buffer() would be invalid.
600 static Encoding const * encoding = 0;
601 if (inset.isBufferValid())
602 encoding = &(inset.buffer().params().encoding());
603 WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
609 void InsetMathHull::initUnicodeMath() const
611 // Trigger classification of the unicode symbols in this inset
612 docstring const dummy = latexString(*this);
616 void InsetMathHull::addPreview(DocIterator const & inset_pos,
617 graphics::PreviewLoader & /*ploader*/) const
619 if (RenderPreview::previewMath()) {
620 preparePreview(inset_pos);
625 void InsetMathHull::preparePreview(DocIterator const & pos,
626 bool forexport) const
628 // there is no need to do all the macro stuff if we're not
629 // actually going to generate the preview.
630 if (!RenderPreview::previewMath() && !forexport)
633 Buffer const * buffer = pos.buffer();
635 // collect macros at this position
637 buffer->listMacroNames(macros);
638 MacroNameSet::iterator it = macros.begin();
639 MacroNameSet::iterator end = macros.end();
640 odocstringstream macro_preamble;
641 for (; it != end; ++it) {
642 MacroData const * data = buffer->getMacro(*it, pos, true);
644 data->write(macro_preamble, true);
645 macro_preamble << endl;
650 if (forexport && haveNumbers()) {
651 docstring eqstr = from_ascii("equation");
652 CounterMap::const_iterator it = counter_map.find(eqstr);
653 if (it != counter_map.end()) {
654 int num = it->second;
656 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
657 '{' + convert<docstring>(num) + '}' + '\n';
659 for (size_t i = 0; i != numcnts; ++i) {
660 docstring cnt = from_ascii(counters_to_save[i]);
661 it = counter_map.find(cnt);
662 if (it == counter_map.end())
664 int num = it->second;
666 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
667 '{' + convert<docstring>(num) + '}';
670 docstring const snippet = macro_preamble.str() +
671 setcnt + latexString(*this);
672 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
673 preview_->addPreview(snippet, *buffer, forexport);
677 void InsetMathHull::reloadPreview(DocIterator const & pos) const
680 preview_->startLoading(*pos.buffer());
684 void InsetMathHull::loadPreview(DocIterator const & pos) const
686 bool const forexport = true;
687 preparePreview(pos, forexport);
688 preview_->startLoading(*pos.buffer(), forexport);
692 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
694 if (RenderPreview::previewMath()) {
696 cur.screenUpdateFlags(Update::Force);
702 docstring InsetMathHull::label(row_type row) const
704 LASSERT(row < nrows(), return docstring());
705 if (InsetLabel * il = label_[row])
706 return il->screenLabel();
711 void InsetMathHull::label(row_type row, docstring const & label)
713 //lyxerr << "setting label '" << label << "' for row " << row << endl;
717 label_[row] = dummy_pointer;
720 label_[row]->updateLabelAndRefs(label);
722 label_[row]->setParam("name", label);
726 InsetCommandParams p(LABEL_CODE);
728 label_[row] = new InsetLabel(buffer_, p);
730 label_[row]->setBuffer(buffer());
734 void InsetMathHull::numbered(row_type row, Numbered num)
736 numbered_[row] = num;
737 if (!numbered(row) && label_[row]) {
744 bool InsetMathHull::numbered(row_type row) const
746 return numbered_[row] == NUMBER;
750 bool InsetMathHull::ams() const
768 for (size_t row = 0; row < numbered_.size(); ++row)
769 if (numbered_[row] == NOTAG)
775 Inset::DisplayType InsetMathHull::display() const
777 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
782 bool InsetMathHull::numberedType() const
784 if (type_ == hullNone)
786 if (type_ == hullSimple)
788 if (type_ == hullXXAlignAt)
790 if (type_ == hullRegexp)
792 for (row_type row = 0; row < nrows(); ++row)
799 void InsetMathHull::validate(LaTeXFeatures & features) const
801 if (features.runparams().isLaTeX()) {
803 features.require("amsmath");
805 if (type_ == hullRegexp) {
806 features.require("color");
807 string frcol = lcolor.getLaTeXName(Color_regexpframe);
808 string bgcol = "white";
809 features.addPreambleSnippet(
810 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
811 + frcol + string("}{")
812 + bgcol + string("}{\\ensuremath{\\mathtt{#1}}}}"));
813 features.addPreambleSnippet(
814 string("\\newcommand{\\endregexp}{}"));
817 // Validation is necessary only if not using AMS math.
818 // To be safe, we will always run mathedvalidate.
819 //if (features.amsstyle)
822 //features.binom = true;
823 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
824 // it would be better to do this elsewhere, but we can't validate in
825 // InsetMathMatrix and we have no way, outside MathExtern, to know if
826 // we even have any matrices.
827 features.addCSSSnippet(
828 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
829 "table.matrix td{padding: 0.25px;}\n"
830 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
831 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
833 InsetMathGrid::validate(features);
837 void InsetMathHull::header_write(WriteStream & os) const
839 bool n = numberedType();
853 os << "\n\\begin{equation" << star(n) << "}\n";
863 os << "\n\\begin{" << hullName(type_) << star(n) << "}\n";
868 os << "\n\\begin{" << hullName(type_) << star(n) << '}'
869 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
873 os << "\n\\begin{" << hullName(type_) << '}'
874 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
882 os << "\n\\begin{unknown" << star(n) << "}\n";
888 void InsetMathHull::footer_write(WriteStream & os) const
890 bool n = numberedType();
903 os << "\n\\end{equation" << star(n) << "}\n";
915 os << "\n\\end{" << hullName(type_) << star(n) << "}\n";
919 os << "\n\\end{" << hullName(type_) << "}\n";
923 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
924 os << "\\endregexp{}}";
928 os << "\n\\end{unknown" << star(n) << "}\n";
934 bool InsetMathHull::rowChangeOK() const
937 type_ == hullEqnArray || type_ == hullAlign ||
938 type_ == hullFlAlign || type_ == hullAlignAt ||
939 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
940 type_ == hullGather || type_ == hullMultline;
944 bool InsetMathHull::colChangeOK() const
947 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
948 type_ == hullXAlignAt || type_ == hullXXAlignAt;
952 void InsetMathHull::addRow(row_type row)
957 bool numbered = numberedType();
958 // Move the number and raw pointer, do not call label() (bug 7511)
959 InsetLabel * label = dummy_pointer;
960 docstring number = empty_docstring();
961 if (type_ == hullMultline) {
962 if (row + 1 == nrows()) {
963 numbered_[row] = NONUMBER;
964 swap(label, label_[row]);
965 swap(number, numbers_[row]);
970 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
971 numbers_.insert(numbers_.begin() + row + 1, number);
972 label_.insert(label_.begin() + row + 1, label);
973 InsetMathGrid::addRow(row);
977 void InsetMathHull::swapRow(row_type row)
981 if (row + 1 == nrows())
983 swap(numbered_[row], numbered_[row + 1]);
984 swap(numbers_[row], numbers_[row + 1]);
985 swap(label_[row], label_[row + 1]);
986 InsetMathGrid::swapRow(row);
990 void InsetMathHull::delRow(row_type row)
992 if (nrows() <= 1 || !rowChangeOK())
994 if (row + 1 == nrows() && type_ == hullMultline) {
995 swap(numbered_[row - 1], numbered_[row]);
996 swap(numbers_[row - 1], numbers_[row]);
997 swap(label_[row - 1], label_[row]);
998 InsetMathGrid::delRow(row);
1001 InsetMathGrid::delRow(row);
1002 // The last dummy row has no number info nor a label.
1003 // Test nrows() + 1 because we have already erased the row.
1004 if (row == nrows() + 1)
1006 numbered_.erase(numbered_.begin() + row);
1007 numbers_.erase(numbers_.begin() + row);
1009 label_.erase(label_.begin() + row);
1013 void InsetMathHull::addCol(col_type col)
1017 InsetMathGrid::addCol(col);
1021 void InsetMathHull::delCol(col_type col)
1023 if (ncols() <= 1 || !colChangeOK())
1025 InsetMathGrid::delCol(col);
1029 docstring InsetMathHull::nicelabel(row_type row) const
1033 docstring const & val = numbers_[row];
1035 return '(' + val + ')';
1036 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1040 void InsetMathHull::glueall(HullType type)
1043 for (idx_type i = 0; i < nargs(); ++i)
1045 InsetLabel * label = 0;
1046 if (type == hullEquation) {
1047 // preserve first non-empty label
1048 for (row_type row = 0; row < nrows(); ++row) {
1050 label = label_[row];
1056 *this = InsetMathHull(buffer_, hullSimple);
1063 void InsetMathHull::splitTo2Cols()
1065 LASSERT(ncols() == 1, return);
1066 InsetMathGrid::addCol(1);
1067 for (row_type row = 0; row < nrows(); ++row) {
1068 idx_type const i = 2 * row;
1069 pos_type pos = firstRelOp(cell(i));
1070 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1071 cell(i).erase(pos, cell(i).size());
1076 void InsetMathHull::splitTo3Cols()
1078 LASSERT(ncols() < 3, return);
1081 InsetMathGrid::addCol(2);
1082 for (row_type row = 0; row < nrows(); ++row) {
1083 idx_type const i = 3 * row + 1;
1084 if (!cell(i).empty()) {
1085 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1086 cell(i).erase(1, cell(i).size());
1092 void InsetMathHull::changeCols(col_type cols)
1094 if (ncols() == cols)
1096 else if (ncols() < cols) {
1102 while (ncols() < cols)
1103 InsetMathGrid::addCol(ncols());
1109 for (row_type row = 0; row < nrows(); ++row) {
1110 idx_type const i = row * ncols();
1111 for (col_type col = cols; col < ncols(); ++col) {
1112 cell(i + cols - 1).append(cell(i + col));
1116 while (ncols() > cols) {
1117 InsetMathGrid::delCol(ncols() - 1);
1122 HullType InsetMathHull::getType() const
1128 void InsetMathHull::setType(HullType type)
1135 void InsetMathHull::mutate(HullType newtype)
1137 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1139 // we try to move along the chain
1140 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1142 // +-------------------------------------+
1143 // we use eqnarray as intermediate type for mutations that are not
1144 // directly supported because it handles labels and numbering for
1147 if (newtype == type_) {
1151 else if (newtype < hullNone) {
1156 else if (type_ == hullNone) {
1157 setType(hullSimple);
1162 else if (type_ == hullSimple) {
1163 if (newtype == hullNone) {
1167 setType(hullEquation);
1168 numbered(0, label_[0] ? true : false);
1173 else if (type_ == hullEquation) {
1174 if (newtype < type_) {
1175 setType(hullSimple);
1178 } else if (newtype == hullEqnArray) {
1179 // split it "nicely" on the first relop
1181 setType(hullEqnArray);
1182 } else if (newtype == hullMultline || newtype == hullGather) {
1185 // split it "nicely"
1192 else if (type_ == hullEqnArray) {
1193 if (newtype < type_) {
1196 } else { // align & Co.
1203 else if (type_ == hullAlign || type_ == hullAlignAt ||
1204 type_ == hullXAlignAt || type_ == hullFlAlign) {
1205 if (newtype < hullAlign) {
1207 setType(hullEqnArray);
1209 } else if (newtype == hullGather || newtype == hullMultline) {
1212 } else if (newtype == hullXXAlignAt) {
1213 for (row_type row = 0; row < nrows(); ++row)
1214 numbered(row, false);
1221 else if (type_ == hullXXAlignAt) {
1222 for (row_type row = 0; row < nrows(); ++row)
1223 numbered(row, false);
1224 if (newtype < hullAlign) {
1226 setType(hullEqnArray);
1228 } else if (newtype == hullGather || newtype == hullMultline) {
1236 else if (type_ == hullMultline || type_ == hullGather) {
1237 if (newtype == hullGather || newtype == hullMultline)
1239 else if (newtype == hullAlign || newtype == hullFlAlign ||
1240 newtype == hullAlignAt || newtype == hullXAlignAt) {
1243 } else if (newtype == hullXXAlignAt) {
1245 for (row_type row = 0; row < nrows(); ++row)
1246 numbered(row, false);
1250 setType(hullEqnArray);
1256 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1257 << "' to '" << to_utf8(hullName(newtype))
1258 << "' not implemented" << endl;
1263 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1264 bool last_eoln) const
1267 if (numberedType()) {
1268 if (label_[row] && numbered(row)) {
1269 docstring const name =
1270 latex ? escape(label_[row]->getParam("name"))
1271 : label_[row]->getParam("name");
1272 res += "\\label{" + name + '}';
1274 if (type_ != hullMultline) {
1275 if (numbered_[row] == NONUMBER)
1276 res += "\\nonumber ";
1277 else if (numbered_[row] == NOTAG)
1281 // Never add \\ on the last empty line of eqnarray and friends
1283 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1287 void InsetMathHull::write(WriteStream & os) const
1289 ModeSpecifier specifier(os, MATH_MODE);
1291 InsetMathGrid::write(os);
1296 void InsetMathHull::normalize(NormalStream & os) const
1298 os << "[formula " << hullName(type_) << ' ';
1299 InsetMathGrid::normalize(os);
1304 void InsetMathHull::infoize(odocstream & os) const
1306 os << bformat(_("Type: %1$s"), hullName(type_));
1310 void InsetMathHull::check() const
1312 LATTEST(numbered_.size() == nrows());
1313 LATTEST(numbers_.size() == nrows());
1314 LATTEST(label_.size() == nrows());
1318 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1322 idocstringstream iss(func.argument());
1323 iss >> dlang >> extra;
1325 extra = from_ascii("noextra");
1326 string const lang = to_ascii(dlang);
1328 // replace selection with result of computation
1329 if (reduceSelectionToOneCell(cur)) {
1331 asArray(grabAndEraseSelection(cur), ar);
1332 lyxerr << "use selection: " << ar << endl;
1333 cur.insert(pipeThroughExtern(lang, extra, ar));
1337 // only inline, display or eqnarray math is allowed
1338 if (getType() > hullEqnArray) {
1339 frontend::Alert::warning(_("Bad math environment"),
1340 _("Computation cannot be performed for AMS "
1341 "math environments.\nChange the math "
1342 "formula type and try again."));
1347 eq.push_back(MathAtom(new InsetMathChar('=')));
1349 // go to first item in line
1350 cur.idx() -= cur.idx() % ncols();
1353 if (getType() == hullSimple) {
1354 size_type pos = cur.cell().find_last(eq);
1356 if (pos == cur.cell().size()) {
1358 lyxerr << "use whole cell: " << ar << endl;
1360 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1361 lyxerr << "use partial cell form pos: " << pos << endl;
1363 cur.cell().append(eq);
1364 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1365 cur.pos() = cur.lastpos();
1369 if (getType() == hullEquation) {
1370 lyxerr << "use equation inset" << endl;
1371 mutate(hullEqnArray);
1372 MathData & ar = cur.cell();
1373 lyxerr << "use cell: " << ar << endl;
1377 cur.cell() = pipeThroughExtern(lang, extra, ar);
1378 // move to end of line
1379 cur.pos() = cur.lastpos();
1384 lyxerr << "use eqnarray" << endl;
1385 cur.idx() += 2 - cur.idx() % ncols();
1387 MathData ar = cur.cell();
1388 lyxerr << "use cell: " << ar << endl;
1389 // FIXME: temporarily disabled
1395 cur.cell() = pipeThroughExtern(lang, extra, ar);
1396 cur.pos() = cur.lastpos();
1401 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1403 //lyxerr << "action: " << cmd.action() << endl;
1404 switch (cmd.action()) {
1406 case LFUN_FINISHED_BACKWARD:
1407 case LFUN_FINISHED_FORWARD:
1408 case LFUN_FINISHED_RIGHT:
1409 case LFUN_FINISHED_LEFT:
1410 //lyxerr << "action: " << cmd.action() << endl;
1411 InsetMathGrid::doDispatch(cur, cmd);
1414 case LFUN_PARAGRAPH_BREAK:
1415 // just swallow this
1418 case LFUN_NEWLINE_INSERT:
1419 // some magic for the common case
1420 if (type_ == hullSimple || type_ == hullEquation) {
1421 cur.recordUndoInset();
1423 cur.bv().buffer().params().use_package("amsmath") == BufferParams::package_on;
1424 mutate(align ? hullAlign : hullEqnArray);
1425 // mutate() may change labels and such.
1426 cur.forceBufferUpdate();
1427 cur.idx() = nrows() * ncols() - 1;
1428 cur.pos() = cur.lastpos();
1430 InsetMathGrid::doDispatch(cur, cmd);
1433 case LFUN_MATH_NUMBER_TOGGLE: {
1434 //lyxerr << "toggling all numbers" << endl;
1435 cur.recordUndoInset();
1436 bool old = numberedType();
1437 if (type_ == hullMultline)
1438 numbered(nrows() - 1, !old);
1440 for (row_type row = 0; row < nrows(); ++row)
1441 numbered(row, !old);
1443 cur.message(old ? _("No number") : _("Number"));
1444 cur.forceBufferUpdate();
1448 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1449 cur.recordUndoInset();
1450 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1451 bool old = numbered(r);
1452 cur.message(old ? _("No number") : _("Number"));
1454 cur.forceBufferUpdate();
1458 case LFUN_LABEL_INSERT: {
1459 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1460 docstring old_label = label(r);
1461 docstring const default_label = from_ascii("eq:");
1462 if (old_label.empty())
1463 old_label = default_label;
1465 InsetCommandParams p(LABEL_CODE);
1466 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1467 string const data = InsetCommand::params2string(p);
1469 if (cmd.argument().empty())
1470 cur.bv().showDialog("label", data);
1472 FuncRequest fr(LFUN_INSET_INSERT, data);
1478 case LFUN_LABEL_COPY_AS_REFERENCE: {
1480 if (cmd.argument().empty() && &cur.inset() == this)
1481 // if there is no argument and we're inside math, we retrieve
1482 // the row number from the cursor position.
1483 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1485 // if there is an argument, find the corresponding label, else
1486 // check whether there is at least one label.
1487 for (row = 0; row != nrows(); ++row)
1488 if (numbered(row) && label_[row]
1489 && (cmd.argument().empty() || label(row) == cmd.argument()))
1496 InsetCommandParams p(REF_CODE, "ref");
1497 p["reference"] = label(row);
1498 cap::clearSelection();
1499 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1503 case LFUN_WORD_DELETE_FORWARD:
1504 case LFUN_CHAR_DELETE_FORWARD:
1505 if (col(cur.idx()) + 1 == ncols()
1506 && cur.pos() == cur.lastpos()
1507 && !cur.selection()) {
1508 if (!label(row(cur.idx())).empty()) {
1509 cur.recordUndoInset();
1510 label(row(cur.idx()), docstring());
1511 } else if (numbered(row(cur.idx()))) {
1512 cur.recordUndoInset();
1513 numbered(row(cur.idx()), false);
1514 cur.forceBufferUpdate();
1516 InsetMathGrid::doDispatch(cur, cmd);
1520 InsetMathGrid::doDispatch(cur, cmd);
1525 case LFUN_INSET_INSERT: {
1526 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1527 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1528 string const name = cmd.getArg(0);
1529 if (name == "label") {
1530 InsetCommandParams p(LABEL_CODE);
1531 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1532 docstring str = p["name"];
1533 cur.recordUndoInset();
1534 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1538 docstring old = label(r);
1541 // The label will take care of the reference update.
1545 // Newly created inset so initialize it.
1546 label_[r]->initView();
1549 cur.forceBufferUpdate();
1552 InsetMathGrid::doDispatch(cur, cmd);
1556 case LFUN_MATH_EXTERN:
1557 cur.recordUndoInset();
1561 case LFUN_MATH_MUTATE: {
1562 cur.recordUndoInset();
1563 row_type row = cur.row();
1564 col_type col = cur.col();
1565 mutate(hullType(cmd.argument()));
1566 cur.idx() = row * ncols() + col;
1567 if (cur.idx() > cur.lastidx()) {
1568 cur.idx() = cur.lastidx();
1569 cur.pos() = cur.lastpos();
1571 if (cur.pos() > cur.lastpos())
1572 cur.pos() = cur.lastpos();
1574 cur.forceBufferUpdate();
1575 // FIXME: find some more clever handling of the selection,
1576 // i.e. preserve it.
1577 cur.clearSelection();
1578 //cur.dispatched(FINISHED);
1582 case LFUN_MATH_DISPLAY: {
1583 cur.recordUndoInset();
1584 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1586 cur.pos() = cur.lastpos();
1587 //cur.dispatched(FINISHED);
1592 InsetMathGrid::doDispatch(cur, cmd);
1598 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1599 FuncStatus & status) const
1601 switch (cmd.action()) {
1602 case LFUN_FINISHED_BACKWARD:
1603 case LFUN_FINISHED_FORWARD:
1604 case LFUN_FINISHED_RIGHT:
1605 case LFUN_FINISHED_LEFT:
1608 case LFUN_NEWLINE_INSERT:
1609 case LFUN_MATH_EXTERN:
1611 status.setEnabled(true);
1614 // we never allow this in math, and we want to bind enter
1615 // to another actions in command-alternatives
1616 case LFUN_PARAGRAPH_BREAK:
1617 status.setEnabled(false);
1619 case LFUN_MATH_MUTATE: {
1620 HullType const ht = hullType(cmd.argument());
1621 status.setOnOff(type_ == ht);
1622 status.setEnabled(true);
1624 if (ht != hullSimple) {
1625 Cursor tmpcur = cur;
1626 while (!tmpcur.empty()) {
1627 InsetCode code = tmpcur.inset().lyxCode();
1628 if (code == BOX_CODE) {
1630 } else if (code == TABULAR_CODE) {
1631 FuncRequest tmpcmd(LFUN_MATH_DISPLAY);
1632 if (tmpcur.getStatus(tmpcmd, status) && !status.enabled())
1640 case LFUN_MATH_DISPLAY: {
1642 if (cur.depth() > 1) {
1643 Inset const & in = cur[cur.depth()-2].inset();
1644 if (in.lyxCode() == SCRIPT_CODE)
1645 enable = display() != Inline;
1647 status.setEnabled(enable);
1651 case LFUN_MATH_NUMBER_TOGGLE:
1652 // FIXME: what is the right test, this or the one of
1654 status.setEnabled(display() != Inline);
1655 status.setOnOff(numberedType());
1658 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1659 // FIXME: what is the right test, this or the one of
1661 bool const enable = (type_ == hullMultline)
1662 ? (nrows() - 1 == cur.row())
1663 : display() != Inline;
1664 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1665 status.setEnabled(enable);
1666 status.setOnOff(enable && numbered(r));
1670 case LFUN_LABEL_INSERT:
1671 status.setEnabled(type_ != hullSimple);
1674 case LFUN_LABEL_COPY_AS_REFERENCE: {
1675 bool enabled = false;
1677 if (cmd.argument().empty() && &cur.inset() == this) {
1678 // if there is no argument and we're inside math, we retrieve
1679 // the row number from the cursor position.
1680 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1681 enabled = numberedType() && label_[row] && numbered(row);
1683 // if there is an argument, find the corresponding label, else
1684 // check whether there is at least one label.
1685 for (row_type row = 0; row != nrows(); ++row) {
1686 if (numbered(row) && label_[row] &&
1687 (cmd.argument().empty() || label(row) == cmd.argument())) {
1693 status.setEnabled(enabled);
1697 case LFUN_INSET_INSERT:
1698 if (cmd.getArg(0) == "label") {
1699 status.setEnabled(type_ != hullSimple);
1702 return InsetMathGrid::getStatus(cur, cmd, status);
1704 case LFUN_INSET_MODIFY: {
1705 istringstream is(to_utf8(cmd.argument()));
1709 return InsetMathGrid::getStatus(cur, cmd, status);
1712 && (s == "append-row"
1713 || s == "delete-row"
1714 || s == "copy-row")) {
1715 status.message(bformat(
1716 from_utf8(N_("Can't change number of rows in '%1$s'")),
1718 status.setEnabled(false);
1722 && (s == "append-column"
1723 || s == "delete-column"
1724 || s == "copy-column")) {
1725 status.message(bformat(
1726 from_utf8(N_("Can't change number of columns in '%1$s'")),
1728 status.setEnabled(false);
1731 if ((type_ == hullSimple
1732 || type_ == hullEquation
1733 || type_ == hullNone) &&
1734 (s == "add-hline-above" || s == "add-hline-below")) {
1735 status.message(bformat(
1736 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1738 status.setEnabled(false);
1741 if (s == "add-vline-left" || s == "add-vline-right") {
1742 status.message(bformat(
1743 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1745 status.setEnabled(false);
1748 if (s == "valign-top" || s == "valign-middle"
1749 || s == "valign-bottom" || s == "align-left"
1750 || s == "align-center" || s == "align-right") {
1751 status.setEnabled(false);
1754 return InsetMathGrid::getStatus(cur, cmd, status);
1758 return InsetMathGrid::getStatus(cur, cmd, status);
1761 // This cannot really happen, but inserted to shut-up gcc
1762 return InsetMathGrid::getStatus(cur, cmd, status);
1766 /////////////////////////////////////////////////////////////////////
1770 // simply scrap this function if you want
1771 void InsetMathHull::mutateToText()
1774 // translate to latex
1776 latex(os, false, false);
1777 string str = os.str();
1780 Text * lt = view_->cursor().innerText();
1781 string::const_iterator cit = str.begin();
1782 string::const_iterator end = str.end();
1783 for (; cit != end; ++cit)
1784 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1787 //dispatch(LFUN_ESCAPE);
1792 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1793 docstring const & font)
1795 // this whole function is a hack and won't work for incremental font
1798 if (cur.inset().asInsetMath()->name() == font)
1799 cur.handleFont(to_utf8(font));
1801 cur.handleNest(createInsetMath(font, cur.buffer()));
1807 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1812 font.fromString(to_utf8(arg), b);
1813 if (font.fontInfo().color() != Color_inherit) {
1814 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1815 cur.handleNest(at, 0);
1820 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1823 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1824 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1825 enter_front ? idxFirst(cur) : idxLast(cur);
1826 // The inset formula dimension is not necessarily the same as the
1827 // one of the instant preview image, so we have to indicate to the
1828 // BufferView that a metrics update is needed.
1829 cur.screenUpdateFlags(Update::Force);
1833 void InsetMathHull::revealCodes(Cursor & cur) const
1835 if (!cur.inMathed())
1837 odocstringstream os;
1839 cur.message(os.str());
1841 // write something to the minibuffer
1842 // translate to latex
1846 string str = os.str();
1848 string::size_type pos = 0;
1850 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1853 else if (*it == '\0') {
1855 pos = it - str.begin();
1861 res = res.substr(pos - 30);
1862 if (res.size() > 60)
1863 res = res.substr(0, 60);
1869 /////////////////////////////////////////////////////////////////////
1873 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1876 // FIXME: completely broken
1877 static InsetMathHull * lastformula = 0;
1878 static CursorBase current = DocIterator(ibegin(nucleus()));
1880 static string laststr;
1882 if (lastformula != this || laststr != str) {
1883 //lyxerr << "reset lastformula to " << this << endl;
1886 current = ibegin(nucleus());
1888 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1892 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1894 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1895 CursorSlice & top = it.back();
1896 MathData const & a = top.asInsetMath()->cell(top.idx_);
1897 if (a.matchpart(ar, top.pos_)) {
1898 bv->cursor().setSelection(it, ar.size());
1900 top.pos_ += ar.size();
1906 //lyxerr << "not found!" << endl;
1913 void InsetMathHull::write(ostream & os) const
1915 odocstringstream oss;
1916 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1919 os << to_utf8(oss.str());
1923 void InsetMathHull::read(Lexer & lex)
1926 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1927 operator=(*at->asHullInset());
1931 bool InsetMathHull::readQuiet(Lexer & lex)
1934 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1936 operator=(*at->asHullInset());
1941 int InsetMathHull::plaintext(odocstringstream & os,
1942 OutputParams const & op, size_t max_length) const
1944 // disables ASCII-art for export of equations. See #2275.
1945 if (0 && display()) {
1949 TextPainter tpain(dim.width(), dim.height());
1950 drawT(tpain, 0, dim.ascent());
1952 // reset metrics cache to "real" values
1954 return tpain.textheight();
1957 odocstringstream oss;
1958 Encoding const * const enc = encodings.fromLyXName("utf8");
1959 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1962 if (type_ == hullRegexp)
1965 for (row_type r = 0; r < nrows(); ++r) {
1966 for (col_type c = 0; c < ncols(); ++c)
1967 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
1968 // if it's for the TOC, we write just the first line
1969 // and do not include the newline.
1970 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
1972 if (r < nrows() - 1)
1976 docstring const str = oss.str();
1982 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1987 if (getType() == hullSimple)
1988 name = from_ascii("inlineequation");
1990 name = from_ascii("informalequation");
1992 docstring bname = name;
1993 if (!label(0).empty())
1994 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1996 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1998 odocstringstream ls;
1999 if (runparams.flavor == OutputParams::XML) {
2000 ms << MTag("alt role='tex' ");
2001 // Workaround for db2latex: db2latex always includes equations with
2002 // \ensuremath{} or \begin{display}\end{display}
2003 // so we strip LyX' math environment
2004 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
2005 InsetMathGrid::write(wi);
2006 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2011 InsetMathGrid::mathmlize(ms);
2016 otexstream ols(ls, texrow);
2017 ms << MTag("alt role='tex'");
2018 latex(ols, runparams);
2019 res = texrow.rows();
2020 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2024 ms << from_ascii("<graphic fileref=\"eqn/");
2025 if (!label(0).empty())
2026 ms << sgml::cleanID(buffer(), runparams, label(0));
2028 ms << sgml::uniqueID(from_ascii("anon"));
2030 if (runparams.flavor == OutputParams::XML)
2031 ms << from_ascii("\"/>");
2033 ms << from_ascii("\">");
2035 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2037 return ms.line() + res;
2041 bool InsetMathHull::haveNumbers() const
2043 bool havenumbers = false;
2044 // inline formulas are never numbered (bug 7351 part 3)
2045 if (getType() == hullSimple)
2047 for (size_t i = 0; i != numbered_.size(); ++i) {
2058 // We need to do something about alignment here.
2060 // This duplicates code from InsetMathGrid, but
2061 // we need access here to number information,
2062 // and we simply do not have that in InsetMathGrid.
2063 void InsetMathHull::htmlize(HtmlStream & os) const
2065 bool const havenumbers = haveNumbers();
2066 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2069 os << cell(index(0, 0));
2073 os << MTag("table", "class='mathtable'");
2074 for (row_type row = 0; row < nrows(); ++row) {
2076 for (col_type col = 0; col < ncols(); ++col) {
2078 os << cell(index(row, col));
2083 docstring const & num = numbers_[row];
2085 os << '(' << num << ')';
2090 os << ETag("table");
2094 // this duplicates code from InsetMathGrid, but
2095 // we need access here to number information,
2096 // and we simply do not have that in InsetMathGrid.
2097 void InsetMathHull::mathmlize(MathStream & os) const
2099 bool const havenumbers = haveNumbers();
2100 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2103 os << MTag("mtable");
2104 char const * const celltag = havetable ? "mtd" : "mrow";
2105 // FIXME There does not seem to be wide support at the moment
2106 // for mlabeledtr, so we have to use just mtr for now.
2107 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2108 char const * const rowtag = "mtr";
2109 for (row_type row = 0; row < nrows(); ++row) {
2112 for (col_type col = 0; col < ncols(); ++col) {
2114 << cell(index(row, col))
2120 docstring const & num = numbers_[row];
2122 os << '(' << num << ')';
2129 os << ETag("mtable");
2133 void InsetMathHull::mathAsLatex(WriteStream & os) const
2135 MathEnsurer ensurer(os, false);
2136 bool havenumbers = haveNumbers();
2137 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2140 os << cell(index(0, 0));
2144 os << "<table class='mathtable'>";
2145 for (row_type row = 0; row < nrows(); ++row) {
2147 for (col_type col = 0; col < ncols(); ++col) {
2148 os << "<td class='math'>";
2149 os << cell(index(row, col));
2154 docstring const & num = numbers_[row];
2156 os << '(' << num << ')';
2165 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2167 BufferParams::MathOutput const mathtype =
2168 buffer().masterBuffer()->params().html_math_output;
2170 bool success = false;
2172 // we output all the labels just at the beginning of the equation.
2173 // this should be fine.
2174 for (size_t i = 0; i != label_.size(); ++i) {
2175 InsetLabel const * const il = label_[i];
2181 // FIXME Eventually we would like to do this inset by inset.
2182 if (mathtype == BufferParams::MathML) {
2183 odocstringstream os;
2188 } catch (MathExportException const &) {}
2190 if (getType() == hullSimple)
2191 xs << html::StartTag("math",
2192 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2194 xs << html::StartTag("math",
2195 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2196 xs << XHTMLStream::ESCAPE_NONE
2198 << html::EndTag("math");
2200 } else if (mathtype == BufferParams::HTML) {
2201 odocstringstream os;
2206 } catch (MathExportException const &) {}
2208 string const tag = (getType() == hullSimple) ? "span" : "div";
2209 xs << html::StartTag(tag, "class='formula'", true)
2210 << XHTMLStream::ESCAPE_NONE
2212 << html::EndTag(tag);
2216 // what we actually want is this:
2218 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2220 // || mathtype == BufferParams::Images
2222 // but what follows is equivalent, since we'll enter only if either (a) we
2223 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2224 // aren't doing LaTeX, in which case we are doing Images.
2225 if (!success && mathtype != BufferParams::LaTeX) {
2226 graphics::PreviewImage const * pimage = 0;
2228 loadPreview(docit_);
2229 pimage = preview_->getPreviewImage(buffer());
2230 // FIXME Do we always have png?
2233 if (pimage || op.dryrun) {
2234 string const filename = pimage ? pimage->filename().onlyFileName()
2235 : "previewimage.png";
2237 // if we are not in the master buffer, then we need to see that the
2238 // generated image is copied there; otherwise, preview fails.
2239 Buffer const * mbuf = buffer().masterBuffer();
2240 if (mbuf != &buffer()) {
2241 string mbtmp = mbuf->temppath();
2242 FileName const mbufimg(support::addName(mbtmp, filename));
2243 pimage->filename().copyTo(mbufimg);
2245 // add the file to the list of files to be exported
2246 op.exportdata->addExternalFile("xhtml", pimage->filename());
2249 string const tag = (getType() == hullSimple) ? "span" : "div";
2251 << html::StartTag(tag)
2252 << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2253 << html::EndTag(tag)
2259 // so we'll pass this test if we've failed everything else, or
2260 // if mathtype was LaTeX, since we won't have entered any of the
2262 if (!success /* || mathtype != BufferParams::LaTeX */) {
2263 // Unfortunately, we cannot use latexString() because we do not want
2264 // $...$ or whatever.
2265 odocstringstream ls;
2266 WriteStream wi(ls, false, true, WriteStream::wsPreview);
2267 ModeSpecifier specifier(wi, MATH_MODE);
2269 docstring const latex = ls.str();
2271 // class='math' allows for use of jsMath
2272 // http://www.math.union.edu/~dpvc/jsMath/
2274 // probably should allow for some kind of customization here
2275 string const tag = (getType() == hullSimple) ? "span" : "div";
2276 xs << html::StartTag(tag, "class='math'")
2278 << html::EndTag(tag)
2285 void InsetMathHull::toString(odocstream & os) const
2287 odocstringstream ods;
2288 plaintext(ods, OutputParams(0));
2293 void InsetMathHull::forOutliner(docstring & os, size_t) const
2295 odocstringstream ods;
2303 string InsetMathHull::contextMenuName() const
2305 return "context-math";
2309 void InsetMathHull::recordLocation(DocIterator const & di)