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 docstring macro_preamble;
641 for (; it != end; ++it) {
642 MacroData const * data = buffer->getMacro(*it, pos, true);
644 odocstringstream mac_preamble;
645 data->write(mac_preamble, false);
646 docstring const mps = mac_preamble.str();
647 bool const is_new_def = prefixIs(mps, from_ascii("\\newcomm"));
648 // assure that \newcommand definitions of macros are only added once
649 if (!is_new_def || !preview_->hasMacroDef(mps, *buffer)) {
651 preview_->addMacroDef(mps, *buffer);
652 if (!macro_preamble.empty())
653 macro_preamble += '\n';
654 macro_preamble += mps;
660 if (forexport && haveNumbers()) {
661 docstring eqstr = from_ascii("equation");
662 CounterMap::const_iterator it = counter_map.find(eqstr);
663 if (it != counter_map.end()) {
664 int num = it->second;
666 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
667 '{' + convert<docstring>(num) + '}' + '\n';
669 for (size_t i = 0; i != numcnts; ++i) {
670 docstring cnt = from_ascii(counters_to_save[i]);
671 it = counter_map.find(cnt);
672 if (it == counter_map.end())
674 int num = it->second;
676 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
677 '{' + convert<docstring>(num) + '}';
680 docstring const snippet = macro_preamble + setcnt + latexString(*this);
681 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
682 preview_->addPreview(snippet, *buffer, forexport);
686 void InsetMathHull::reloadPreview(DocIterator const & pos) const
689 preview_->startLoading(*pos.buffer());
693 void InsetMathHull::loadPreview(DocIterator const & pos) const
695 bool const forexport = true;
696 preparePreview(pos, forexport);
697 preview_->startLoading(*pos.buffer(), forexport);
701 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
703 if (RenderPreview::previewMath()) {
705 cur.screenUpdateFlags(Update::Force);
711 docstring InsetMathHull::label(row_type row) const
713 LASSERT(row < nrows(), return docstring());
714 if (InsetLabel * il = label_[row])
715 return il->screenLabel();
720 void InsetMathHull::label(row_type row, docstring const & label)
722 //lyxerr << "setting label '" << label << "' for row " << row << endl;
726 label_[row] = dummy_pointer;
729 label_[row]->updateLabelAndRefs(label);
731 label_[row]->setParam("name", label);
735 InsetCommandParams p(LABEL_CODE);
737 label_[row] = new InsetLabel(buffer_, p);
739 label_[row]->setBuffer(buffer());
743 void InsetMathHull::numbered(row_type row, Numbered num)
745 numbered_[row] = num;
746 if (!numbered(row) && label_[row]) {
753 bool InsetMathHull::numbered(row_type row) const
755 return numbered_[row] == NUMBER;
759 bool InsetMathHull::ams() const
777 for (size_t row = 0; row < numbered_.size(); ++row)
778 if (numbered_[row] == NOTAG)
784 Inset::DisplayType InsetMathHull::display() const
786 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
791 bool InsetMathHull::numberedType() const
793 if (type_ == hullNone)
795 if (type_ == hullSimple)
797 if (type_ == hullXXAlignAt)
799 if (type_ == hullRegexp)
801 for (row_type row = 0; row < nrows(); ++row)
808 void InsetMathHull::validate(LaTeXFeatures & features) const
810 if (features.runparams().isLaTeX()) {
812 features.require("amsmath");
814 if (type_ == hullRegexp) {
815 features.require("color");
816 string frcol = lcolor.getLaTeXName(Color_regexpframe);
817 string bgcol = "white";
818 features.addPreambleSnippet(
819 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
820 + frcol + string("}{")
821 + bgcol + string("}{\\ensuremath{\\mathtt{#1}}}}"));
822 features.addPreambleSnippet(
823 string("\\newcommand{\\endregexp}{}"));
826 // Validation is necessary only if not using AMS math.
827 // To be safe, we will always run mathedvalidate.
828 //if (features.amsstyle)
831 //features.binom = true;
832 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
833 // it would be better to do this elsewhere, but we can't validate in
834 // InsetMathMatrix and we have no way, outside MathExtern, to know if
835 // we even have any matrices.
836 features.addCSSSnippet(
837 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
838 "table.matrix td{padding: 0.25px;}\n"
839 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
840 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
842 InsetMathGrid::validate(features);
846 void InsetMathHull::header_write(WriteStream & os) const
848 bool n = numberedType();
862 os << "\n\\begin{equation" << star(n) << "}\n";
872 os << "\n\\begin{" << hullName(type_) << star(n) << "}\n";
877 os << "\n\\begin{" << hullName(type_) << star(n) << '}'
878 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
882 os << "\n\\begin{" << hullName(type_) << '}'
883 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
891 os << "\n\\begin{unknown" << star(n) << "}\n";
897 void InsetMathHull::footer_write(WriteStream & os) const
899 bool n = numberedType();
912 os << "\n\\end{equation" << star(n) << "}\n";
924 os << "\n\\end{" << hullName(type_) << star(n) << "}\n";
928 os << "\n\\end{" << hullName(type_) << "}\n";
932 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
933 os << "\\endregexp{}}";
937 os << "\n\\end{unknown" << star(n) << "}\n";
943 bool InsetMathHull::rowChangeOK() const
946 type_ == hullEqnArray || type_ == hullAlign ||
947 type_ == hullFlAlign || type_ == hullAlignAt ||
948 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
949 type_ == hullGather || type_ == hullMultline;
953 bool InsetMathHull::colChangeOK() const
956 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
957 type_ == hullXAlignAt || type_ == hullXXAlignAt;
961 void InsetMathHull::addRow(row_type row)
966 bool numbered = numberedType();
967 // Move the number and raw pointer, do not call label() (bug 7511)
968 InsetLabel * label = dummy_pointer;
969 docstring number = empty_docstring();
970 if (type_ == hullMultline) {
971 if (row + 1 == nrows()) {
972 numbered_[row] = NONUMBER;
973 swap(label, label_[row]);
974 swap(number, numbers_[row]);
979 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
980 numbers_.insert(numbers_.begin() + row + 1, number);
981 label_.insert(label_.begin() + row + 1, label);
982 InsetMathGrid::addRow(row);
986 void InsetMathHull::swapRow(row_type row)
990 if (row + 1 == nrows())
992 swap(numbered_[row], numbered_[row + 1]);
993 swap(numbers_[row], numbers_[row + 1]);
994 swap(label_[row], label_[row + 1]);
995 InsetMathGrid::swapRow(row);
999 void InsetMathHull::delRow(row_type row)
1001 if (nrows() <= 1 || !rowChangeOK())
1003 if (row + 1 == nrows() && type_ == hullMultline) {
1004 swap(numbered_[row - 1], numbered_[row]);
1005 swap(numbers_[row - 1], numbers_[row]);
1006 swap(label_[row - 1], label_[row]);
1007 InsetMathGrid::delRow(row);
1010 InsetMathGrid::delRow(row);
1011 // The last dummy row has no number info nor a label.
1012 // Test nrows() + 1 because we have already erased the row.
1013 if (row == nrows() + 1)
1015 numbered_.erase(numbered_.begin() + row);
1016 numbers_.erase(numbers_.begin() + row);
1018 label_.erase(label_.begin() + row);
1022 void InsetMathHull::addCol(col_type col)
1026 InsetMathGrid::addCol(col);
1030 void InsetMathHull::delCol(col_type col)
1032 if (ncols() <= 1 || !colChangeOK())
1034 InsetMathGrid::delCol(col);
1038 docstring InsetMathHull::nicelabel(row_type row) const
1042 docstring const & val = numbers_[row];
1044 return '(' + val + ')';
1045 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1049 void InsetMathHull::glueall(HullType type)
1052 for (idx_type i = 0; i < nargs(); ++i)
1054 InsetLabel * label = 0;
1055 if (type == hullEquation) {
1056 // preserve first non-empty label
1057 for (row_type row = 0; row < nrows(); ++row) {
1059 label = label_[row];
1065 *this = InsetMathHull(buffer_, hullSimple);
1072 void InsetMathHull::splitTo2Cols()
1074 LASSERT(ncols() == 1, return);
1075 InsetMathGrid::addCol(1);
1076 for (row_type row = 0; row < nrows(); ++row) {
1077 idx_type const i = 2 * row;
1078 pos_type pos = firstRelOp(cell(i));
1079 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1080 cell(i).erase(pos, cell(i).size());
1085 void InsetMathHull::splitTo3Cols()
1087 LASSERT(ncols() < 3, return);
1090 InsetMathGrid::addCol(2);
1091 for (row_type row = 0; row < nrows(); ++row) {
1092 idx_type const i = 3 * row + 1;
1093 if (!cell(i).empty()) {
1094 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1095 cell(i).erase(1, cell(i).size());
1101 void InsetMathHull::changeCols(col_type cols)
1103 if (ncols() == cols)
1105 else if (ncols() < cols) {
1111 while (ncols() < cols)
1112 InsetMathGrid::addCol(ncols());
1118 for (row_type row = 0; row < nrows(); ++row) {
1119 idx_type const i = row * ncols();
1120 for (col_type col = cols; col < ncols(); ++col) {
1121 cell(i + cols - 1).append(cell(i + col));
1125 while (ncols() > cols) {
1126 InsetMathGrid::delCol(ncols() - 1);
1131 HullType InsetMathHull::getType() const
1137 void InsetMathHull::setType(HullType type)
1144 void InsetMathHull::mutate(HullType newtype)
1146 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1148 // we try to move along the chain
1149 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1151 // +-------------------------------------+
1152 // we use eqnarray as intermediate type for mutations that are not
1153 // directly supported because it handles labels and numbering for
1156 if (newtype == type_) {
1160 else if (newtype < hullNone) {
1165 else if (type_ == hullNone) {
1166 setType(hullSimple);
1171 else if (type_ == hullSimple) {
1172 if (newtype == hullNone) {
1176 setType(hullEquation);
1177 numbered(0, label_[0] ? true : false);
1182 else if (type_ == hullEquation) {
1183 if (newtype < type_) {
1184 setType(hullSimple);
1187 } else if (newtype == hullEqnArray) {
1188 // split it "nicely" on the first relop
1190 setType(hullEqnArray);
1191 } else if (newtype == hullMultline || newtype == hullGather) {
1194 // split it "nicely"
1201 else if (type_ == hullEqnArray) {
1202 if (newtype < type_) {
1205 } else { // align & Co.
1212 else if (type_ == hullAlign || type_ == hullAlignAt ||
1213 type_ == hullXAlignAt || type_ == hullFlAlign) {
1214 if (newtype < hullAlign) {
1216 setType(hullEqnArray);
1218 } else if (newtype == hullGather || newtype == hullMultline) {
1221 } else if (newtype == hullXXAlignAt) {
1222 for (row_type row = 0; row < nrows(); ++row)
1223 numbered(row, false);
1230 else if (type_ == hullXXAlignAt) {
1231 for (row_type row = 0; row < nrows(); ++row)
1232 numbered(row, false);
1233 if (newtype < hullAlign) {
1235 setType(hullEqnArray);
1237 } else if (newtype == hullGather || newtype == hullMultline) {
1245 else if (type_ == hullMultline || type_ == hullGather) {
1246 if (newtype == hullGather || newtype == hullMultline)
1248 else if (newtype == hullAlign || newtype == hullFlAlign ||
1249 newtype == hullAlignAt || newtype == hullXAlignAt) {
1252 } else if (newtype == hullXXAlignAt) {
1254 for (row_type row = 0; row < nrows(); ++row)
1255 numbered(row, false);
1259 setType(hullEqnArray);
1265 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1266 << "' to '" << to_utf8(hullName(newtype))
1267 << "' not implemented" << endl;
1272 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1273 bool last_eoln) const
1276 if (numberedType()) {
1277 if (label_[row] && numbered(row)) {
1278 docstring const name =
1279 latex ? escape(label_[row]->getParam("name"))
1280 : label_[row]->getParam("name");
1281 res += "\\label{" + name + '}';
1283 if (type_ != hullMultline) {
1284 if (numbered_[row] == NONUMBER)
1285 res += "\\nonumber ";
1286 else if (numbered_[row] == NOTAG)
1290 // Never add \\ on the last empty line of eqnarray and friends
1292 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1296 void InsetMathHull::write(WriteStream & os) const
1298 ModeSpecifier specifier(os, MATH_MODE);
1300 InsetMathGrid::write(os);
1305 void InsetMathHull::normalize(NormalStream & os) const
1307 os << "[formula " << hullName(type_) << ' ';
1308 InsetMathGrid::normalize(os);
1313 void InsetMathHull::infoize(odocstream & os) const
1315 os << bformat(_("Type: %1$s"), hullName(type_));
1319 void InsetMathHull::check() const
1321 LATTEST(numbered_.size() == nrows());
1322 LATTEST(numbers_.size() == nrows());
1323 LATTEST(label_.size() == nrows());
1327 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1331 idocstringstream iss(func.argument());
1332 iss >> dlang >> extra;
1334 extra = from_ascii("noextra");
1335 string const lang = to_ascii(dlang);
1337 // replace selection with result of computation
1338 if (reduceSelectionToOneCell(cur)) {
1340 asArray(grabAndEraseSelection(cur), ar);
1341 lyxerr << "use selection: " << ar << endl;
1342 cur.insert(pipeThroughExtern(lang, extra, ar));
1346 // only inline, display or eqnarray math is allowed
1347 if (getType() > hullEqnArray) {
1348 frontend::Alert::warning(_("Bad math environment"),
1349 _("Computation cannot be performed for AMS "
1350 "math environments.\nChange the math "
1351 "formula type and try again."));
1356 eq.push_back(MathAtom(new InsetMathChar('=')));
1358 // go to first item in line
1359 cur.idx() -= cur.idx() % ncols();
1362 if (getType() == hullSimple) {
1363 size_type pos = cur.cell().find_last(eq);
1365 if (pos == cur.cell().size()) {
1367 lyxerr << "use whole cell: " << ar << endl;
1369 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1370 lyxerr << "use partial cell form pos: " << pos << endl;
1372 cur.cell().append(eq);
1373 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1374 cur.pos() = cur.lastpos();
1378 if (getType() == hullEquation) {
1379 lyxerr << "use equation inset" << endl;
1380 mutate(hullEqnArray);
1381 MathData & ar = cur.cell();
1382 lyxerr << "use cell: " << ar << endl;
1386 cur.cell() = pipeThroughExtern(lang, extra, ar);
1387 // move to end of line
1388 cur.pos() = cur.lastpos();
1393 lyxerr << "use eqnarray" << endl;
1394 cur.idx() += 2 - cur.idx() % ncols();
1396 MathData ar = cur.cell();
1397 lyxerr << "use cell: " << ar << endl;
1398 // FIXME: temporarily disabled
1404 cur.cell() = pipeThroughExtern(lang, extra, ar);
1405 cur.pos() = cur.lastpos();
1410 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1412 //lyxerr << "action: " << cmd.action() << endl;
1413 switch (cmd.action()) {
1415 case LFUN_FINISHED_BACKWARD:
1416 case LFUN_FINISHED_FORWARD:
1417 case LFUN_FINISHED_RIGHT:
1418 case LFUN_FINISHED_LEFT:
1419 //lyxerr << "action: " << cmd.action() << endl;
1420 InsetMathGrid::doDispatch(cur, cmd);
1423 case LFUN_PARAGRAPH_BREAK:
1424 // just swallow this
1427 case LFUN_NEWLINE_INSERT:
1428 // some magic for the common case
1429 if (type_ == hullSimple || type_ == hullEquation) {
1430 cur.recordUndoInset();
1432 cur.bv().buffer().params().use_package("amsmath") == BufferParams::package_on;
1433 mutate(align ? hullAlign : hullEqnArray);
1434 // mutate() may change labels and such.
1435 cur.forceBufferUpdate();
1436 cur.idx() = nrows() * ncols() - 1;
1437 cur.pos() = cur.lastpos();
1439 InsetMathGrid::doDispatch(cur, cmd);
1442 case LFUN_MATH_NUMBER_TOGGLE: {
1443 //lyxerr << "toggling all numbers" << endl;
1444 cur.recordUndoInset();
1445 bool old = numberedType();
1446 if (type_ == hullMultline)
1447 numbered(nrows() - 1, !old);
1449 for (row_type row = 0; row < nrows(); ++row)
1450 numbered(row, !old);
1452 cur.message(old ? _("No number") : _("Number"));
1453 cur.forceBufferUpdate();
1457 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1458 cur.recordUndoInset();
1459 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1460 bool old = numbered(r);
1461 cur.message(old ? _("No number") : _("Number"));
1463 cur.forceBufferUpdate();
1467 case LFUN_LABEL_INSERT: {
1468 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1469 docstring old_label = label(r);
1470 docstring const default_label = from_ascii("eq:");
1471 if (old_label.empty())
1472 old_label = default_label;
1474 InsetCommandParams p(LABEL_CODE);
1475 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1476 string const data = InsetCommand::params2string(p);
1478 if (cmd.argument().empty())
1479 cur.bv().showDialog("label", data);
1481 FuncRequest fr(LFUN_INSET_INSERT, data);
1487 case LFUN_LABEL_COPY_AS_REFERENCE: {
1489 if (cmd.argument().empty() && &cur.inset() == this)
1490 // if there is no argument and we're inside math, we retrieve
1491 // the row number from the cursor position.
1492 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1494 // if there is an argument, find the corresponding label, else
1495 // check whether there is at least one label.
1496 for (row = 0; row != nrows(); ++row)
1497 if (numbered(row) && label_[row]
1498 && (cmd.argument().empty() || label(row) == cmd.argument()))
1505 InsetCommandParams p(REF_CODE, "ref");
1506 p["reference"] = label(row);
1507 cap::clearSelection();
1508 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1512 case LFUN_WORD_DELETE_FORWARD:
1513 case LFUN_CHAR_DELETE_FORWARD:
1514 if (col(cur.idx()) + 1 == ncols()
1515 && cur.pos() == cur.lastpos()
1516 && !cur.selection()) {
1517 if (!label(row(cur.idx())).empty()) {
1518 cur.recordUndoInset();
1519 label(row(cur.idx()), docstring());
1520 } else if (numbered(row(cur.idx()))) {
1521 cur.recordUndoInset();
1522 numbered(row(cur.idx()), false);
1523 cur.forceBufferUpdate();
1525 InsetMathGrid::doDispatch(cur, cmd);
1529 InsetMathGrid::doDispatch(cur, cmd);
1534 case LFUN_INSET_INSERT: {
1535 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1536 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1537 string const name = cmd.getArg(0);
1538 if (name == "label") {
1539 InsetCommandParams p(LABEL_CODE);
1540 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1541 docstring str = p["name"];
1542 cur.recordUndoInset();
1543 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1547 docstring old = label(r);
1550 // The label will take care of the reference update.
1554 // Newly created inset so initialize it.
1555 label_[r]->initView();
1558 cur.forceBufferUpdate();
1561 InsetMathGrid::doDispatch(cur, cmd);
1565 case LFUN_MATH_EXTERN:
1566 cur.recordUndoInset();
1570 case LFUN_MATH_MUTATE: {
1571 cur.recordUndoInset();
1572 row_type row = cur.row();
1573 col_type col = cur.col();
1574 mutate(hullType(cmd.argument()));
1575 cur.idx() = row * ncols() + col;
1576 if (cur.idx() > cur.lastidx()) {
1577 cur.idx() = cur.lastidx();
1578 cur.pos() = cur.lastpos();
1580 if (cur.pos() > cur.lastpos())
1581 cur.pos() = cur.lastpos();
1583 cur.forceBufferUpdate();
1584 // FIXME: find some more clever handling of the selection,
1585 // i.e. preserve it.
1586 cur.clearSelection();
1587 //cur.dispatched(FINISHED);
1591 case LFUN_MATH_DISPLAY: {
1592 cur.recordUndoInset();
1593 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1595 cur.pos() = cur.lastpos();
1596 //cur.dispatched(FINISHED);
1601 InsetMathGrid::doDispatch(cur, cmd);
1607 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1608 FuncStatus & status) const
1610 switch (cmd.action()) {
1611 case LFUN_FINISHED_BACKWARD:
1612 case LFUN_FINISHED_FORWARD:
1613 case LFUN_FINISHED_RIGHT:
1614 case LFUN_FINISHED_LEFT:
1617 case LFUN_NEWLINE_INSERT:
1618 case LFUN_MATH_EXTERN:
1620 status.setEnabled(true);
1623 // we never allow this in math, and we want to bind enter
1624 // to another actions in command-alternatives
1625 case LFUN_PARAGRAPH_BREAK:
1626 status.setEnabled(false);
1628 case LFUN_MATH_MUTATE: {
1629 HullType const ht = hullType(cmd.argument());
1630 status.setOnOff(type_ == ht);
1631 status.setEnabled(true);
1633 if (ht != hullSimple) {
1634 Cursor tmpcur = cur;
1635 while (!tmpcur.empty()) {
1636 InsetCode code = tmpcur.inset().lyxCode();
1637 if (code == BOX_CODE) {
1639 } else if (code == TABULAR_CODE) {
1640 FuncRequest tmpcmd(LFUN_MATH_DISPLAY);
1641 if (tmpcur.getStatus(tmpcmd, status) && !status.enabled())
1649 case LFUN_MATH_DISPLAY: {
1651 if (cur.depth() > 1) {
1652 Inset const & in = cur[cur.depth()-2].inset();
1653 if (in.lyxCode() == SCRIPT_CODE)
1654 enable = display() != Inline;
1656 status.setEnabled(enable);
1657 status.setOnOff(display() != Inline);
1661 case LFUN_MATH_NUMBER_TOGGLE:
1662 // FIXME: what is the right test, this or the one of
1664 status.setEnabled(display() != Inline);
1665 status.setOnOff(numberedType());
1668 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1669 // FIXME: what is the right test, this or the one of
1671 bool const enable = (type_ == hullMultline)
1672 ? (nrows() - 1 == cur.row())
1673 : display() != Inline;
1674 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1675 status.setEnabled(enable);
1676 status.setOnOff(enable && numbered(r));
1680 case LFUN_LABEL_INSERT:
1681 status.setEnabled(type_ != hullSimple);
1684 case LFUN_LABEL_COPY_AS_REFERENCE: {
1685 bool enabled = false;
1687 if (cmd.argument().empty() && &cur.inset() == this) {
1688 // if there is no argument and we're inside math, we retrieve
1689 // the row number from the cursor position.
1690 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1691 enabled = numberedType() && label_[row] && numbered(row);
1693 // if there is an argument, find the corresponding label, else
1694 // check whether there is at least one label.
1695 for (row_type row = 0; row != nrows(); ++row) {
1696 if (numbered(row) && label_[row] &&
1697 (cmd.argument().empty() || label(row) == cmd.argument())) {
1703 status.setEnabled(enabled);
1707 case LFUN_INSET_INSERT:
1708 if (cmd.getArg(0) == "label") {
1709 status.setEnabled(type_ != hullSimple);
1712 return InsetMathGrid::getStatus(cur, cmd, status);
1714 case LFUN_INSET_MODIFY: {
1715 istringstream is(to_utf8(cmd.argument()));
1719 return InsetMathGrid::getStatus(cur, cmd, status);
1722 && (s == "append-row"
1723 || s == "delete-row"
1724 || s == "copy-row")) {
1725 status.message(bformat(
1726 from_utf8(N_("Can't change number of rows in '%1$s'")),
1728 status.setEnabled(false);
1732 && (s == "append-column"
1733 || s == "delete-column"
1734 || s == "copy-column")) {
1735 status.message(bformat(
1736 from_utf8(N_("Can't change number of columns in '%1$s'")),
1738 status.setEnabled(false);
1741 if ((type_ == hullSimple
1742 || type_ == hullEquation
1743 || type_ == hullNone) &&
1744 (s == "add-hline-above" || s == "add-hline-below")) {
1745 status.message(bformat(
1746 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1748 status.setEnabled(false);
1751 if (s == "add-vline-left" || s == "add-vline-right") {
1752 status.message(bformat(
1753 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1755 status.setEnabled(false);
1758 if (s == "valign-top" || s == "valign-middle"
1759 || s == "valign-bottom" || s == "align-left"
1760 || s == "align-center" || s == "align-right") {
1761 status.setEnabled(false);
1764 return InsetMathGrid::getStatus(cur, cmd, status);
1768 return InsetMathGrid::getStatus(cur, cmd, status);
1771 // This cannot really happen, but inserted to shut-up gcc
1772 return InsetMathGrid::getStatus(cur, cmd, status);
1776 /////////////////////////////////////////////////////////////////////
1780 // simply scrap this function if you want
1781 void InsetMathHull::mutateToText()
1784 // translate to latex
1786 latex(os, false, false);
1787 string str = os.str();
1790 Text * lt = view_->cursor().innerText();
1791 string::const_iterator cit = str.begin();
1792 string::const_iterator end = str.end();
1793 for (; cit != end; ++cit)
1794 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1797 //dispatch(LFUN_ESCAPE);
1802 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1803 docstring const & font)
1805 // this whole function is a hack and won't work for incremental font
1808 if (cur.inset().asInsetMath()->name() == font)
1809 cur.handleFont(to_utf8(font));
1811 cur.handleNest(createInsetMath(font, cur.buffer()));
1817 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1822 font.fromString(to_utf8(arg), b);
1823 if (font.fontInfo().color() != Color_inherit) {
1824 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1825 cur.handleNest(at, 0);
1830 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1833 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1834 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1835 enter_front ? idxFirst(cur) : idxLast(cur);
1836 // The inset formula dimension is not necessarily the same as the
1837 // one of the instant preview image, so we have to indicate to the
1838 // BufferView that a metrics update is needed.
1839 cur.screenUpdateFlags(Update::Force);
1843 void InsetMathHull::revealCodes(Cursor & cur) const
1845 if (!cur.inMathed())
1847 odocstringstream os;
1849 cur.message(os.str());
1851 // write something to the minibuffer
1852 // translate to latex
1856 string str = os.str();
1858 string::size_type pos = 0;
1860 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1863 else if (*it == '\0') {
1865 pos = it - str.begin();
1871 res = res.substr(pos - 30);
1872 if (res.size() > 60)
1873 res = res.substr(0, 60);
1879 /////////////////////////////////////////////////////////////////////
1883 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1886 // FIXME: completely broken
1887 static InsetMathHull * lastformula = 0;
1888 static CursorBase current = DocIterator(ibegin(nucleus()));
1890 static string laststr;
1892 if (lastformula != this || laststr != str) {
1893 //lyxerr << "reset lastformula to " << this << endl;
1896 current = ibegin(nucleus());
1898 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1902 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1904 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1905 CursorSlice & top = it.back();
1906 MathData const & a = top.asInsetMath()->cell(top.idx_);
1907 if (a.matchpart(ar, top.pos_)) {
1908 bv->cursor().setSelection(it, ar.size());
1910 top.pos_ += ar.size();
1916 //lyxerr << "not found!" << endl;
1923 void InsetMathHull::write(ostream & os) const
1925 odocstringstream oss;
1926 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1929 os << to_utf8(oss.str());
1933 void InsetMathHull::read(Lexer & lex)
1936 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1937 operator=(*at->asHullInset());
1941 bool InsetMathHull::readQuiet(Lexer & lex)
1944 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1946 operator=(*at->asHullInset());
1951 int InsetMathHull::plaintext(odocstringstream & os,
1952 OutputParams const & op, size_t max_length) const
1954 // disables ASCII-art for export of equations. See #2275.
1955 if (0 && display()) {
1959 TextPainter tpain(dim.width(), dim.height());
1960 drawT(tpain, 0, dim.ascent());
1962 // reset metrics cache to "real" values
1964 return tpain.textheight();
1967 odocstringstream oss;
1968 Encoding const * const enc = encodings.fromLyXName("utf8");
1969 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1972 if (type_ == hullRegexp)
1975 for (row_type r = 0; r < nrows(); ++r) {
1976 for (col_type c = 0; c < ncols(); ++c)
1977 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
1978 // if it's for the TOC, we write just the first line
1979 // and do not include the newline.
1980 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
1982 if (r < nrows() - 1)
1986 docstring const str = oss.str();
1992 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1997 if (getType() == hullSimple)
1998 name = from_ascii("inlineequation");
2000 name = from_ascii("informalequation");
2002 docstring bname = name;
2003 if (!label(0).empty())
2004 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
2006 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
2008 odocstringstream ls;
2009 if (runparams.flavor == OutputParams::XML) {
2010 ms << MTag("alt role='tex' ");
2011 // Workaround for db2latex: db2latex always includes equations with
2012 // \ensuremath{} or \begin{display}\end{display}
2013 // so we strip LyX' math environment
2014 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
2015 InsetMathGrid::write(wi);
2016 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2021 InsetMathGrid::mathmlize(ms);
2026 otexstream ols(ls, texrow);
2027 ms << MTag("alt role='tex'");
2028 latex(ols, runparams);
2029 res = texrow.rows();
2030 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2034 ms << from_ascii("<graphic fileref=\"eqn/");
2035 if (!label(0).empty())
2036 ms << sgml::cleanID(buffer(), runparams, label(0));
2038 ms << sgml::uniqueID(from_ascii("anon"));
2040 if (runparams.flavor == OutputParams::XML)
2041 ms << from_ascii("\"/>");
2043 ms << from_ascii("\">");
2045 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2047 return ms.line() + res;
2051 bool InsetMathHull::haveNumbers() const
2053 bool havenumbers = false;
2054 // inline formulas are never numbered (bug 7351 part 3)
2055 if (getType() == hullSimple)
2057 for (size_t i = 0; i != numbered_.size(); ++i) {
2068 // We need to do something about alignment here.
2070 // This duplicates code from InsetMathGrid, but
2071 // we need access here to number information,
2072 // and we simply do not have that in InsetMathGrid.
2073 void InsetMathHull::htmlize(HtmlStream & os) const
2075 bool const havenumbers = haveNumbers();
2076 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2079 os << cell(index(0, 0));
2083 os << MTag("table", "class='mathtable'");
2084 for (row_type row = 0; row < nrows(); ++row) {
2086 for (col_type col = 0; col < ncols(); ++col) {
2088 os << cell(index(row, col));
2093 docstring const & num = numbers_[row];
2095 os << '(' << num << ')';
2100 os << ETag("table");
2104 // this duplicates code from InsetMathGrid, but
2105 // we need access here to number information,
2106 // and we simply do not have that in InsetMathGrid.
2107 void InsetMathHull::mathmlize(MathStream & os) const
2109 bool const havenumbers = haveNumbers();
2110 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2113 os << MTag("mtable");
2114 char const * const celltag = havetable ? "mtd" : "mrow";
2115 // FIXME There does not seem to be wide support at the moment
2116 // for mlabeledtr, so we have to use just mtr for now.
2117 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2118 char const * const rowtag = "mtr";
2119 for (row_type row = 0; row < nrows(); ++row) {
2122 for (col_type col = 0; col < ncols(); ++col) {
2124 << cell(index(row, col))
2130 docstring const & num = numbers_[row];
2132 os << '(' << num << ')';
2139 os << ETag("mtable");
2143 void InsetMathHull::mathAsLatex(WriteStream & os) const
2145 MathEnsurer ensurer(os, false);
2146 bool havenumbers = haveNumbers();
2147 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2150 os << cell(index(0, 0));
2154 os << "<table class='mathtable'>";
2155 for (row_type row = 0; row < nrows(); ++row) {
2157 for (col_type col = 0; col < ncols(); ++col) {
2158 os << "<td class='math'>";
2159 os << cell(index(row, col));
2164 docstring const & num = numbers_[row];
2166 os << '(' << num << ')';
2175 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2177 BufferParams::MathOutput const mathtype =
2178 buffer().masterBuffer()->params().html_math_output;
2180 bool success = false;
2182 // we output all the labels just at the beginning of the equation.
2183 // this should be fine.
2184 for (size_t i = 0; i != label_.size(); ++i) {
2185 InsetLabel const * const il = label_[i];
2191 // FIXME Eventually we would like to do this inset by inset.
2192 if (mathtype == BufferParams::MathML) {
2193 odocstringstream os;
2198 } catch (MathExportException const &) {}
2200 if (getType() == hullSimple)
2201 xs << html::StartTag("math",
2202 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2204 xs << html::StartTag("math",
2205 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2206 xs << XHTMLStream::ESCAPE_NONE
2208 << html::EndTag("math");
2210 } else if (mathtype == BufferParams::HTML) {
2211 odocstringstream os;
2216 } catch (MathExportException const &) {}
2218 string const tag = (getType() == hullSimple) ? "span" : "div";
2219 xs << html::StartTag(tag, "class='formula'", true)
2220 << XHTMLStream::ESCAPE_NONE
2222 << html::EndTag(tag);
2226 // what we actually want is this:
2228 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2230 // || mathtype == BufferParams::Images
2232 // but what follows is equivalent, since we'll enter only if either (a) we
2233 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2234 // aren't doing LaTeX, in which case we are doing Images.
2235 if (!success && mathtype != BufferParams::LaTeX) {
2236 graphics::PreviewImage const * pimage = 0;
2238 loadPreview(docit_);
2239 pimage = preview_->getPreviewImage(buffer());
2240 // FIXME Do we always have png?
2243 if (pimage || op.dryrun) {
2244 string const filename = pimage ? pimage->filename().onlyFileName()
2245 : "previewimage.png";
2247 // if we are not in the master buffer, then we need to see that the
2248 // generated image is copied there; otherwise, preview fails.
2249 Buffer const * mbuf = buffer().masterBuffer();
2250 if (mbuf != &buffer()) {
2251 string mbtmp = mbuf->temppath();
2252 FileName const mbufimg(support::addName(mbtmp, filename));
2253 pimage->filename().copyTo(mbufimg);
2255 // add the file to the list of files to be exported
2256 op.exportdata->addExternalFile("xhtml", pimage->filename());
2259 string const tag = (getType() == hullSimple) ? "span" : "div";
2261 << html::StartTag(tag)
2262 << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2263 << html::EndTag(tag)
2269 // so we'll pass this test if we've failed everything else, or
2270 // if mathtype was LaTeX, since we won't have entered any of the
2272 if (!success /* || mathtype != BufferParams::LaTeX */) {
2273 // Unfortunately, we cannot use latexString() because we do not want
2274 // $...$ or whatever.
2275 odocstringstream ls;
2276 WriteStream wi(ls, false, true, WriteStream::wsPreview);
2277 ModeSpecifier specifier(wi, MATH_MODE);
2279 docstring const latex = ls.str();
2281 // class='math' allows for use of jsMath
2282 // http://www.math.union.edu/~dpvc/jsMath/
2284 // probably should allow for some kind of customization here
2285 string const tag = (getType() == hullSimple) ? "span" : "div";
2286 xs << html::StartTag(tag, "class='math'")
2288 << html::EndTag(tag)
2295 void InsetMathHull::toString(odocstream & os) const
2297 odocstringstream ods;
2298 plaintext(ods, OutputParams(0));
2303 void InsetMathHull::forOutliner(docstring & os, size_t) const
2305 odocstringstream ods;
2313 string InsetMathHull::contextMenuName() const
2315 return "context-math";
2319 void InsetMathHull::recordLocation(DocIterator const & di)