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 "InsetMathFrac.h"
18 #include "InsetMathGrid.h"
19 #include "InsetMathNest.h"
20 #include "InsetMathScript.h"
21 #include "MathExtern.h"
22 #include "MathFactory.h"
23 #include "MathStream.h"
24 #include "MathSupport.h"
27 #include "BufferParams.h"
28 #include "BufferView.h"
30 #include "CutAndPaste.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
36 #include "LaTeXFeatures.h"
38 #include "MacroTable.h"
39 #include "MathMacro.h"
40 #include "output_xhtml.h"
41 #include "Paragraph.h"
42 #include "ParIterator.h"
44 #include "TextClass.h"
45 #include "TextPainter.h"
46 #include "TocBackend.h"
48 #include "insets/InsetLabel.h"
49 #include "insets/InsetRef.h"
50 #include "insets/RenderPreview.h"
52 #include "graphics/GraphicsImage.h"
53 #include "graphics/PreviewImage.h"
54 #include "graphics/PreviewLoader.h"
56 #include "frontends/alert.h"
57 #include "frontends/Painter.h"
59 #include "support/convert.h"
60 #include "support/lassert.h"
61 #include "support/debug.h"
62 #include "support/filetools.h"
63 #include "support/gettext.h"
64 #include "support/lstrings.h"
69 using namespace lyx::support;
73 using cap::grabAndEraseSelection;
74 using cap::reduceSelectionToOneCell;
78 int getCols(HullType type)
95 // returns position of first relation operator in the array
96 // used for "intelligent splitting"
97 size_t firstRelOp(MathData const & ar)
99 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
100 if ((*it)->isRelOp())
101 return it - ar.begin();
106 char const * star(bool numbered)
108 return numbered ? "" : "*";
112 } // end anon namespace
115 HullType hullType(docstring const & s)
117 if (s == "none") return hullNone;
118 if (s == "simple") return hullSimple;
119 if (s == "equation") return hullEquation;
120 if (s == "eqnarray") return hullEqnArray;
121 if (s == "align") return hullAlign;
122 if (s == "alignat") return hullAlignAt;
123 if (s == "xalignat") return hullXAlignAt;
124 if (s == "xxalignat") return hullXXAlignAt;
125 if (s == "multline") return hullMultline;
126 if (s == "gather") return hullGather;
127 if (s == "flalign") return hullFlAlign;
128 if (s == "regexp") return hullRegexp;
129 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
134 docstring hullName(HullType type)
137 case hullNone: return from_ascii("none");
138 case hullSimple: return from_ascii("simple");
139 case hullEquation: return from_ascii("equation");
140 case hullEqnArray: return from_ascii("eqnarray");
141 case hullAlign: return from_ascii("align");
142 case hullAlignAt: return from_ascii("alignat");
143 case hullXAlignAt: return from_ascii("xalignat");
144 case hullXXAlignAt: return from_ascii("xxalignat");
145 case hullMultline: return from_ascii("multline");
146 case hullGather: return from_ascii("gather");
147 case hullFlAlign: return from_ascii("flalign");
148 case hullRegexp: return from_ascii("regexp");
150 lyxerr << "unknown hull type '" << type << "'" << endl;
151 return from_ascii("none");
155 static InsetLabel * dummy_pointer = 0;
157 InsetMathHull::InsetMathHull(Buffer * buf)
158 : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, NUMBER),
159 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
160 preview_(new RenderPreview(this)), use_preview_(false)
162 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
163 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
164 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
165 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
172 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
173 : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, NUMBER),
174 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
175 preview_(new RenderPreview(this)), use_preview_(false)
183 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
189 InsetMathHull::~InsetMathHull()
191 for (size_t i = 0; i < label_.size(); ++i)
196 Inset * InsetMathHull::clone() const
198 return new InsetMathHull(*this);
202 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
206 InsetMathGrid::operator=(other);
208 numbered_ = other.numbered_;
209 numbers_ = other.numbers_;
210 buffer_ = other.buffer_;
211 for (size_t i = 0; i < label_.size(); ++i)
213 label_ = other.label_;
214 for (size_t i = 0; i != label_.size(); ++i) {
216 label_[i] = new InsetLabel(*label_[i]);
218 preview_.reset(new RenderPreview(*other.preview_, this));
224 void InsetMathHull::setBuffer(Buffer & buffer)
226 InsetMathGrid::setBuffer(buffer);
228 for (size_t i = 0; i != label_.size(); ++i) {
230 label_[i]->setBuffer(buffer);
235 // FIXME This should really be controlled by the TOC level, or
236 // something of the sort.
238 const char * counters_to_save[] = {"section", "chapter"};
239 unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
243 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
246 //FIXME: buffer_ should be set at creation for this inset! Problem is
247 // This inset is created at too many places (see Parser::parse1() in
252 // if any of the equations are numbered, then we want to save the values
253 // of some of the counters.
255 BufferParams const & bp = buffer_->params();
256 string const & lang = it->getParLanguage(bp)->code();
258 buffer_->masterBuffer()->params().documentClass().counters();
260 // right now, we only need to do this at export time
261 if (utype == OutputUpdate) {
262 for (size_t i = 0; i < numcnts; ++i) {
263 docstring const cnt = from_ascii(counters_to_save[i]);
264 if (cnts.hasCounter(cnt))
265 counter_map[cnt] = cnts.value(cnt);
269 // this has to be done separately
270 docstring const eqstr = from_ascii("equation");
271 if (cnts.hasCounter(eqstr)) {
272 if (utype == OutputUpdate)
273 counter_map[eqstr] = cnts.value(eqstr);
274 for (size_t i = 0; i != label_.size(); ++i) {
276 cnts.step(eqstr, utype);
277 numbers_[i] = cnts.theCounter(eqstr, lang);
279 numbers_[i] = empty_docstring();
285 for (size_t i = 0; i != label_.size(); ++i) {
287 label_[i]->updateBuffer(it, utype);
290 InsetMathGrid::updateBuffer(it, utype);
294 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active) const
297 //FIXME: buffer_ should be set at creation for this inset! Problem is
298 // This inset is created at too many places (see Parser::parse1() in
303 Toc & toc = buffer().tocBackend().toc("equation");
305 for (row_type row = 0; row != nrows(); ++row) {
309 label_[row]->addToToc(pit, output_active);
310 toc.push_back(TocItem(pit, 0, nicelabel(row), output_active));
315 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
321 return InsetMathNest::editXY(cur, x, y);
325 InsetMath::mode_type InsetMathHull::currentMode() const
327 if (type_ == hullNone)
328 return UNDECIDED_MODE;
329 // definitely math mode ...
334 bool InsetMathHull::idxFirst(Cursor & cur) const
342 bool InsetMathHull::idxLast(Cursor & cur) const
344 cur.idx() = nargs() - 1;
345 cur.pos() = cur.lastpos();
350 char InsetMathHull::defaultColAlign(col_type col)
352 if (type_ == hullEqnArray)
354 if (type_ == hullMultline)
356 if (type_ == hullGather)
358 if (type_ >= hullAlign)
359 return "rl"[col & 1];
364 char InsetMathHull::displayColAlign(idx_type idx) const
366 if (type_ == hullMultline) {
367 row_type const r = row(idx);
370 if (r == nrows() - 1)
373 return InsetMathGrid::displayColAlign(idx);
377 int InsetMathHull::defaultColSpace(col_type col)
379 if (type_ == hullAlign || type_ == hullAlignAt)
381 if (type_ == hullXAlignAt)
382 return (col & 1) ? 20 : 0;
383 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
384 return (col & 1) ? 40 : 0;
389 docstring InsetMathHull::standardFont() const
394 font_name = from_ascii("texttt");
397 font_name = from_ascii("lyxnochange");
400 font_name = from_ascii("mathnormal");
406 ColorCode InsetMathHull::standardColor() const
412 color = Color_foreground;
421 bool InsetMathHull::previewState(const BufferView *const bv) const
423 if (!editing(bv) && RenderPreview::previewMath()
424 && type_ != hullRegexp)
426 graphics::PreviewImage const * pimage =
427 preview_->getPreviewImage(bv->buffer());
428 return pimage && pimage->image();
435 static const int ERROR_FRAME_WIDTH = 2;
438 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
440 if (previewState(mi.base.bv)) {
441 preview_->metrics(mi, dim);
442 if (previewTooSmall(dim)) {
443 // preview image is too small
444 dim.wid += 2 * ERROR_FRAME_WIDTH;
445 dim.asc += 2 * ERROR_FRAME_WIDTH;
447 // insert a one pixel gap in front of the formula
450 dim.des += displayMargin();
452 // Cache the inset dimension.
453 setDimCache(mi, dim);
457 FontSetChanger dummy1(mi.base, standardFont());
458 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
460 // let the cells adjust themselves
461 InsetMathGrid::metrics(mi, dim);
464 dim.asc += displayMargin();
465 dim.des += displayMargin();
468 if (numberedType()) {
469 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
471 for (row_type row = 0; row < nrows(); ++row)
472 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
478 if (type_ == hullRegexp)
480 // make it at least as high as the current font
483 math_font_max_dim(mi.base.font, asc, des);
484 dim.asc = max(dim.asc, asc);
485 dim.des = max(dim.des, des);
486 // Cache the inset dimension.
487 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
488 setDimCache(mi, dim);
492 bool InsetMathHull::previewTooSmall(Dimension const & dim) const
494 return dim.width() <= 10 && dim.height() <= 10;
498 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
500 BufferView const * const bv = pi.base.bv;
501 if (previewState(bv)) {
502 Dimension const dim = dimension(*pi.base.bv);
503 if (previewTooSmall(dim))
505 return graphics::PreviewLoader::backgroundColor();
511 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
513 Dimension const dim = dimension(*pi.base.bv);
514 if (previewTooSmall(dim)) {
515 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
516 dim.wid, dim.asc + dim.des, backgroundColor(pi));
519 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
520 dim.asc + dim.des - 1, pi.backgroundColor(this));
524 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
526 BufferView const * const bv = pi.base.bv;
527 use_preview_ = previewState(bv);
529 if (type_ == hullRegexp) {
530 Dimension const dim = dimension(*bv);
531 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
532 dim.width() - 2, dim.height() - 2, Color_regexpframe);
536 Dimension const dim = dimension(*bv);
537 if (previewTooSmall(dim)) {
538 // we have an extra frame
539 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
541 // one pixel gap in front
542 preview_->draw(pi, x + 1, y);
544 setPosCache(pi, x, y);
548 ColorCode color = pi.selected && lyxrc.use_system_colors
549 ? Color_selectiontext : standardColor();
550 bool const really_change_color = pi.base.font.color() == Color_none;
551 ColorChanger dummy0(pi.base.font, color, really_change_color);
552 FontSetChanger dummy1(pi.base, standardFont());
553 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
555 InsetMathGrid::draw(pi, x + 1, y);
557 if (numberedType()) {
558 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
559 for (row_type row = 0; row < nrows(); ++row) {
560 int const yy = y + rowinfo_[row].offset_;
561 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
562 docstring const nl = nicelabel(row);
566 setPosCache(pi, x, y);
570 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
573 InsetMathGrid::metricsT(mi, dim);
576 WriteStream wi(os, false, true, WriteStream::wsDefault);
578 dim.wid = os.str().size();
585 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
588 InsetMathGrid::drawT(pain, x, y);
591 WriteStream wi(os, false, true, WriteStream::wsDefault);
593 pain.draw(x, y, os.str().c_str());
598 static docstring latexString(InsetMathHull const & inset)
601 // This has to be static, because a preview snippet or a math
602 // macro containing math in text mode (such as $\text{$\phi$}$ or
603 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
604 // first time as a whole, and the second time only the inner math.
605 // In this last case inset.buffer() would be invalid.
606 static Encoding const * encoding = 0;
607 if (inset.isBufferValid())
608 encoding = &(inset.buffer().params().encoding());
609 WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
615 void InsetMathHull::initUnicodeMath() const
617 // Trigger classification of the unicode symbols in this inset
618 docstring const dummy = latexString(*this);
622 void InsetMathHull::addPreview(DocIterator const & inset_pos,
623 graphics::PreviewLoader & /*ploader*/) const
625 if (RenderPreview::previewMath()) {
626 preparePreview(inset_pos);
631 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
632 MacroNameSet & macros, MacroNameSet & defs) const
634 MacroNameSet::iterator const end = macros.end();
636 for (size_t i = 0; i < md.size(); ++i) {
637 MathMacro const * mi = md[i].nucleus()->asMacro();
638 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
639 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
640 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
641 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
643 // Make sure this is a macro defined in the document
644 // (as we also spot the macros in the symbols file)
645 // or that we have not already accounted for it.
646 docstring const name = mi->name();
647 if (macros.find(name) == end)
650 MathData ar(pos.buffer());
651 MacroData const * data =
652 pos.buffer()->getMacro(name, pos, true);
654 odocstringstream macro_def;
655 data->write(macro_def, true);
657 defs.insert(macro_def.str());
658 asArray(data->definition(), ar);
660 usedMacros(ar, pos, macros, defs);
662 if (!si->nuc().empty())
663 usedMacros(si->nuc(), pos, macros, defs);
665 usedMacros(si->down(), pos, macros, defs);
667 usedMacros(si->up(), pos, macros, defs);
668 } else if (fi || gi) {
669 idx_type nidx = fi ? fi->nargs() : gi->nargs();
670 for (idx_type idx = 0; idx < nidx; ++idx)
671 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
674 usedMacros(ni->cell(0), pos, macros, defs);
680 void InsetMathHull::preparePreview(DocIterator const & pos,
681 bool forexport) const
683 // there is no need to do all the macro stuff if we're not
684 // actually going to generate the preview.
685 if (!RenderPreview::previewMath() && !forexport)
688 Buffer const * buffer = pos.buffer();
690 // collect macros at this position
692 buffer->listMacroNames(macros);
694 // collect definitions only for the macros used in this inset
696 for (idx_type idx = 0; idx < nargs(); ++idx)
697 usedMacros(cell(idx), pos, macros, defs);
699 MacroNameSet::iterator it = defs.begin();
700 MacroNameSet::iterator end = defs.end();
701 docstring macro_preamble;
702 for (; it != end; ++it)
703 macro_preamble.append(*it);
706 if (forexport && haveNumbers()) {
707 docstring eqstr = from_ascii("equation");
708 CounterMap::const_iterator it = counter_map.find(eqstr);
709 if (it != counter_map.end()) {
710 int num = it->second;
712 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
713 '{' + convert<docstring>(num) + '}' + '\n';
715 for (size_t i = 0; i != numcnts; ++i) {
716 docstring cnt = from_ascii(counters_to_save[i]);
717 it = counter_map.find(cnt);
718 if (it == counter_map.end())
720 int num = it->second;
722 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
723 '{' + convert<docstring>(num) + '}';
726 docstring const snippet = macro_preamble + setcnt + latexString(*this);
727 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
728 preview_->addPreview(snippet, *buffer, forexport);
732 void InsetMathHull::reloadPreview(DocIterator const & pos) const
735 preview_->startLoading(*pos.buffer());
739 void InsetMathHull::loadPreview(DocIterator const & pos) const
741 bool const forexport = true;
742 preparePreview(pos, forexport);
743 preview_->startLoading(*pos.buffer(), forexport);
747 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
749 if (RenderPreview::previewMath()) {
751 cur.screenUpdateFlags(Update::Force);
757 docstring InsetMathHull::label(row_type row) const
759 LASSERT(row < nrows(), return docstring());
760 if (InsetLabel * il = label_[row])
761 return il->screenLabel();
766 void InsetMathHull::label(row_type row, docstring const & label)
768 //lyxerr << "setting label '" << label << "' for row " << row << endl;
772 label_[row] = dummy_pointer;
775 label_[row]->updateLabelAndRefs(label);
777 label_[row]->setParam("name", label);
781 InsetCommandParams p(LABEL_CODE);
783 label_[row] = new InsetLabel(buffer_, p);
785 label_[row]->setBuffer(buffer());
789 void InsetMathHull::numbered(row_type row, Numbered num)
791 numbered_[row] = num;
792 if (!numbered(row) && label_[row]) {
799 bool InsetMathHull::numbered(row_type row) const
801 return numbered_[row] == NUMBER;
805 bool InsetMathHull::ams() const
823 for (size_t row = 0; row < numbered_.size(); ++row)
824 if (numbered_[row] == NOTAG)
830 Inset::DisplayType InsetMathHull::display() const
832 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
837 bool InsetMathHull::numberedType() const
839 if (type_ == hullNone)
841 if (type_ == hullSimple)
843 if (type_ == hullXXAlignAt)
845 if (type_ == hullRegexp)
847 for (row_type row = 0; row < nrows(); ++row)
854 void InsetMathHull::validate(LaTeXFeatures & features) const
856 if (features.runparams().isLaTeX()) {
858 features.require("amsmath");
860 if (type_ == hullRegexp) {
861 features.require("color");
862 string frcol = lcolor.getLaTeXName(Color_regexpframe);
863 string bgcol = "white";
864 features.addPreambleSnippet(
865 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
866 + frcol + string("}{")
867 + bgcol + string("}{\\ensuremath{\\mathtt{#1}}}}"));
868 features.addPreambleSnippet(
869 string("\\newcommand{\\endregexp}{}"));
872 // Validation is necessary only if not using AMS math.
873 // To be safe, we will always run mathedvalidate.
874 //if (features.amsstyle)
877 //features.binom = true;
878 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
879 // it would be better to do this elsewhere, but we can't validate in
880 // InsetMathMatrix and we have no way, outside MathExtern, to know if
881 // we even have any matrices.
882 features.addCSSSnippet(
883 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
884 "table.matrix td{padding: 0.25px;}\n"
885 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
886 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
888 InsetMathGrid::validate(features);
892 void InsetMathHull::header_write(WriteStream & os) const
894 bool n = numberedType();
908 os << "\n\\begin{equation" << star(n) << "}\n";
918 os << "\n\\begin{" << hullName(type_) << star(n) << "}\n";
923 os << "\n\\begin{" << hullName(type_) << star(n) << '}'
924 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
928 os << "\n\\begin{" << hullName(type_) << '}'
929 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
937 os << "\n\\begin{unknown" << star(n) << "}\n";
943 void InsetMathHull::footer_write(WriteStream & os) const
945 bool n = numberedType();
958 os << "\n\\end{equation" << star(n) << "}\n";
970 os << "\n\\end{" << hullName(type_) << star(n) << "}\n";
974 os << "\n\\end{" << hullName(type_) << "}\n";
978 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
979 os << "\\endregexp{}}";
983 os << "\n\\end{unknown" << star(n) << "}\n";
989 bool InsetMathHull::rowChangeOK() const
992 type_ == hullEqnArray || type_ == hullAlign ||
993 type_ == hullFlAlign || type_ == hullAlignAt ||
994 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
995 type_ == hullGather || type_ == hullMultline;
999 bool InsetMathHull::colChangeOK() const
1002 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1003 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1007 void InsetMathHull::addRow(row_type row)
1012 bool numbered = numberedType();
1013 // Move the number and raw pointer, do not call label() (bug 7511)
1014 InsetLabel * label = dummy_pointer;
1015 docstring number = empty_docstring();
1016 if (type_ == hullMultline) {
1017 if (row + 1 == nrows()) {
1018 numbered_[row] = NONUMBER;
1019 swap(label, label_[row]);
1020 swap(number, numbers_[row]);
1025 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1026 numbers_.insert(numbers_.begin() + row + 1, number);
1027 label_.insert(label_.begin() + row + 1, label);
1028 InsetMathGrid::addRow(row);
1032 void InsetMathHull::swapRow(row_type row)
1036 if (row + 1 == nrows())
1038 swap(numbered_[row], numbered_[row + 1]);
1039 swap(numbers_[row], numbers_[row + 1]);
1040 swap(label_[row], label_[row + 1]);
1041 InsetMathGrid::swapRow(row);
1045 void InsetMathHull::delRow(row_type row)
1047 if (nrows() <= 1 || !rowChangeOK())
1049 if (row + 1 == nrows() && type_ == hullMultline) {
1050 swap(numbered_[row - 1], numbered_[row]);
1051 swap(numbers_[row - 1], numbers_[row]);
1052 swap(label_[row - 1], label_[row]);
1053 InsetMathGrid::delRow(row);
1056 InsetMathGrid::delRow(row);
1057 // The last dummy row has no number info nor a label.
1058 // Test nrows() + 1 because we have already erased the row.
1059 if (row == nrows() + 1)
1061 numbered_.erase(numbered_.begin() + row);
1062 numbers_.erase(numbers_.begin() + row);
1064 label_.erase(label_.begin() + row);
1068 void InsetMathHull::addCol(col_type col)
1072 InsetMathGrid::addCol(col);
1076 void InsetMathHull::delCol(col_type col)
1078 if (ncols() <= 1 || !colChangeOK())
1080 InsetMathGrid::delCol(col);
1084 docstring InsetMathHull::nicelabel(row_type row) const
1088 docstring const & val = numbers_[row];
1090 return '(' + val + ')';
1091 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1095 void InsetMathHull::glueall(HullType type)
1098 for (idx_type i = 0; i < nargs(); ++i)
1100 InsetLabel * label = 0;
1101 if (type == hullEquation) {
1102 // preserve first non-empty label
1103 for (row_type row = 0; row < nrows(); ++row) {
1105 label = label_[row];
1111 *this = InsetMathHull(buffer_, hullSimple);
1118 void InsetMathHull::splitTo2Cols()
1120 LASSERT(ncols() == 1, return);
1121 InsetMathGrid::addCol(1);
1122 for (row_type row = 0; row < nrows(); ++row) {
1123 idx_type const i = 2 * row;
1124 pos_type pos = firstRelOp(cell(i));
1125 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1126 cell(i).erase(pos, cell(i).size());
1131 void InsetMathHull::splitTo3Cols()
1133 LASSERT(ncols() < 3, return);
1136 InsetMathGrid::addCol(2);
1137 for (row_type row = 0; row < nrows(); ++row) {
1138 idx_type const i = 3 * row + 1;
1139 if (!cell(i).empty()) {
1140 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1141 cell(i).erase(1, cell(i).size());
1147 void InsetMathHull::changeCols(col_type cols)
1149 if (ncols() == cols)
1151 else if (ncols() < cols) {
1157 while (ncols() < cols)
1158 InsetMathGrid::addCol(ncols());
1164 for (row_type row = 0; row < nrows(); ++row) {
1165 idx_type const i = row * ncols();
1166 for (col_type col = cols; col < ncols(); ++col) {
1167 cell(i + cols - 1).append(cell(i + col));
1171 while (ncols() > cols) {
1172 InsetMathGrid::delCol(ncols() - 1);
1177 HullType InsetMathHull::getType() const
1183 void InsetMathHull::setType(HullType type)
1190 void InsetMathHull::mutate(HullType newtype)
1192 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1194 // we try to move along the chain
1195 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1197 // +-------------------------------------+
1198 // we use eqnarray as intermediate type for mutations that are not
1199 // directly supported because it handles labels and numbering for
1202 if (newtype == type_) {
1206 else if (newtype < hullNone) {
1211 else if (type_ == hullNone) {
1212 setType(hullSimple);
1217 else if (type_ == hullSimple) {
1218 if (newtype == hullNone) {
1222 setType(hullEquation);
1223 numbered(0, label_[0] ? true : false);
1228 else if (type_ == hullEquation) {
1229 if (newtype < type_) {
1230 setType(hullSimple);
1233 } else if (newtype == hullEqnArray) {
1234 // split it "nicely" on the first relop
1236 setType(hullEqnArray);
1237 } else if (newtype == hullMultline || newtype == hullGather) {
1240 // split it "nicely"
1247 else if (type_ == hullEqnArray) {
1248 if (newtype < type_) {
1251 } else { // align & Co.
1258 else if (type_ == hullAlign || type_ == hullAlignAt ||
1259 type_ == hullXAlignAt || type_ == hullFlAlign) {
1260 if (newtype < hullAlign) {
1262 setType(hullEqnArray);
1264 } else if (newtype == hullGather || newtype == hullMultline) {
1267 } else if (newtype == hullXXAlignAt) {
1268 for (row_type row = 0; row < nrows(); ++row)
1269 numbered(row, false);
1276 else if (type_ == hullXXAlignAt) {
1277 for (row_type row = 0; row < nrows(); ++row)
1278 numbered(row, false);
1279 if (newtype < hullAlign) {
1281 setType(hullEqnArray);
1283 } else if (newtype == hullGather || newtype == hullMultline) {
1291 else if (type_ == hullMultline || type_ == hullGather) {
1292 if (newtype == hullGather || newtype == hullMultline)
1294 else if (newtype == hullAlign || newtype == hullFlAlign ||
1295 newtype == hullAlignAt || newtype == hullXAlignAt) {
1298 } else if (newtype == hullXXAlignAt) {
1300 for (row_type row = 0; row < nrows(); ++row)
1301 numbered(row, false);
1305 setType(hullEqnArray);
1311 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1312 << "' to '" << to_utf8(hullName(newtype))
1313 << "' not implemented" << endl;
1318 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1319 bool last_eoln) const
1322 if (numberedType()) {
1323 if (label_[row] && numbered(row)) {
1324 docstring const name =
1325 latex ? escape(label_[row]->getParam("name"))
1326 : label_[row]->getParam("name");
1327 res += "\\label{" + name + '}';
1329 if (type_ != hullMultline) {
1330 if (numbered_[row] == NONUMBER)
1331 res += "\\nonumber ";
1332 else if (numbered_[row] == NOTAG)
1336 // Never add \\ on the last empty line of eqnarray and friends
1338 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1342 void InsetMathHull::write(WriteStream & os) const
1344 ModeSpecifier specifier(os, MATH_MODE);
1346 InsetMathGrid::write(os);
1351 void InsetMathHull::normalize(NormalStream & os) const
1353 os << "[formula " << hullName(type_) << ' ';
1354 InsetMathGrid::normalize(os);
1359 void InsetMathHull::infoize(odocstream & os) const
1361 os << bformat(_("Type: %1$s"), hullName(type_));
1365 void InsetMathHull::check() const
1367 LATTEST(numbered_.size() == nrows());
1368 LATTEST(numbers_.size() == nrows());
1369 LATTEST(label_.size() == nrows());
1373 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1377 idocstringstream iss(func.argument());
1378 iss >> dlang >> extra;
1380 extra = from_ascii("noextra");
1381 string const lang = to_ascii(dlang);
1383 // replace selection with result of computation
1384 if (reduceSelectionToOneCell(cur)) {
1386 asArray(grabAndEraseSelection(cur), ar);
1387 lyxerr << "use selection: " << ar << endl;
1388 cur.insert(pipeThroughExtern(lang, extra, ar));
1392 // only inline, display or eqnarray math is allowed
1393 if (getType() > hullEqnArray) {
1394 frontend::Alert::warning(_("Bad math environment"),
1395 _("Computation cannot be performed for AMS "
1396 "math environments.\nChange the math "
1397 "formula type and try again."));
1402 eq.push_back(MathAtom(new InsetMathChar('=')));
1404 // go to first item in line
1405 cur.idx() -= cur.idx() % ncols();
1408 if (getType() == hullSimple) {
1409 size_type pos = cur.cell().find_last(eq);
1411 if (pos == cur.cell().size()) {
1413 lyxerr << "use whole cell: " << ar << endl;
1415 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1416 lyxerr << "use partial cell form pos: " << pos << endl;
1418 cur.cell().append(eq);
1419 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1420 cur.pos() = cur.lastpos();
1424 if (getType() == hullEquation) {
1425 lyxerr << "use equation inset" << endl;
1426 mutate(hullEqnArray);
1427 MathData & ar = cur.cell();
1428 lyxerr << "use cell: " << ar << endl;
1432 cur.cell() = pipeThroughExtern(lang, extra, ar);
1433 // move to end of line
1434 cur.pos() = cur.lastpos();
1439 lyxerr << "use eqnarray" << endl;
1440 cur.idx() += 2 - cur.idx() % ncols();
1442 MathData ar = cur.cell();
1443 lyxerr << "use cell: " << ar << endl;
1444 // FIXME: temporarily disabled
1450 cur.cell() = pipeThroughExtern(lang, extra, ar);
1451 cur.pos() = cur.lastpos();
1456 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1458 //lyxerr << "action: " << cmd.action() << endl;
1459 switch (cmd.action()) {
1461 case LFUN_FINISHED_BACKWARD:
1462 case LFUN_FINISHED_FORWARD:
1463 case LFUN_FINISHED_RIGHT:
1464 case LFUN_FINISHED_LEFT:
1465 //lyxerr << "action: " << cmd.action() << endl;
1466 InsetMathGrid::doDispatch(cur, cmd);
1469 case LFUN_PARAGRAPH_BREAK:
1470 // just swallow this
1473 case LFUN_NEWLINE_INSERT:
1474 // some magic for the common case
1475 if (type_ == hullSimple || type_ == hullEquation) {
1476 cur.recordUndoInset();
1478 cur.bv().buffer().params().use_package("amsmath") == BufferParams::package_on;
1479 mutate(align ? hullAlign : hullEqnArray);
1480 // mutate() may change labels and such.
1481 cur.forceBufferUpdate();
1482 cur.idx() = nrows() * ncols() - 1;
1483 cur.pos() = cur.lastpos();
1485 InsetMathGrid::doDispatch(cur, cmd);
1488 case LFUN_MATH_NUMBER_TOGGLE: {
1489 //lyxerr << "toggling all numbers" << endl;
1490 cur.recordUndoInset();
1491 bool old = numberedType();
1492 if (type_ == hullMultline)
1493 numbered(nrows() - 1, !old);
1495 for (row_type row = 0; row < nrows(); ++row)
1496 numbered(row, !old);
1498 cur.message(old ? _("No number") : _("Number"));
1499 cur.forceBufferUpdate();
1503 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1504 cur.recordUndoInset();
1505 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1506 bool old = numbered(r);
1507 cur.message(old ? _("No number") : _("Number"));
1509 cur.forceBufferUpdate();
1513 case LFUN_LABEL_INSERT: {
1514 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1515 docstring old_label = label(r);
1516 docstring const default_label = from_ascii("eq:");
1517 if (old_label.empty())
1518 old_label = default_label;
1520 InsetCommandParams p(LABEL_CODE);
1521 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1522 string const data = InsetCommand::params2string(p);
1524 if (cmd.argument().empty())
1525 cur.bv().showDialog("label", data);
1527 FuncRequest fr(LFUN_INSET_INSERT, data);
1533 case LFUN_LABEL_COPY_AS_REFERENCE: {
1535 if (cmd.argument().empty() && &cur.inset() == this)
1536 // if there is no argument and we're inside math, we retrieve
1537 // the row number from the cursor position.
1538 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1540 // if there is an argument, find the corresponding label, else
1541 // check whether there is at least one label.
1542 for (row = 0; row != nrows(); ++row)
1543 if (numbered(row) && label_[row]
1544 && (cmd.argument().empty() || label(row) == cmd.argument()))
1551 InsetCommandParams p(REF_CODE, "ref");
1552 p["reference"] = label(row);
1553 cap::clearSelection();
1554 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1558 case LFUN_WORD_DELETE_FORWARD:
1559 case LFUN_CHAR_DELETE_FORWARD:
1560 if (col(cur.idx()) + 1 == ncols()
1561 && cur.pos() == cur.lastpos()
1562 && !cur.selection()) {
1563 if (!label(row(cur.idx())).empty()) {
1564 cur.recordUndoInset();
1565 label(row(cur.idx()), docstring());
1566 } else if (numbered(row(cur.idx()))) {
1567 cur.recordUndoInset();
1568 numbered(row(cur.idx()), false);
1569 cur.forceBufferUpdate();
1571 InsetMathGrid::doDispatch(cur, cmd);
1575 InsetMathGrid::doDispatch(cur, cmd);
1580 case LFUN_INSET_INSERT: {
1581 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1582 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1583 string const name = cmd.getArg(0);
1584 if (name == "label") {
1585 InsetCommandParams p(LABEL_CODE);
1586 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1587 docstring str = p["name"];
1588 cur.recordUndoInset();
1589 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1593 docstring old = label(r);
1596 // The label will take care of the reference update.
1600 // Newly created inset so initialize it.
1601 label_[r]->initView();
1604 cur.forceBufferUpdate();
1607 InsetMathGrid::doDispatch(cur, cmd);
1611 case LFUN_MATH_EXTERN:
1612 cur.recordUndoInset();
1616 case LFUN_MATH_MUTATE: {
1617 cur.recordUndoInset();
1618 row_type row = cur.row();
1619 col_type col = cur.col();
1620 mutate(hullType(cmd.argument()));
1621 cur.idx() = row * ncols() + col;
1622 if (cur.idx() > cur.lastidx()) {
1623 cur.idx() = cur.lastidx();
1624 cur.pos() = cur.lastpos();
1626 if (cur.pos() > cur.lastpos())
1627 cur.pos() = cur.lastpos();
1629 cur.forceBufferUpdate();
1630 // FIXME: find some more clever handling of the selection,
1631 // i.e. preserve it.
1632 cur.clearSelection();
1633 //cur.dispatched(FINISHED);
1637 case LFUN_MATH_DISPLAY: {
1638 cur.recordUndoInset();
1639 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1641 cur.pos() = cur.lastpos();
1642 //cur.dispatched(FINISHED);
1647 InsetMathGrid::doDispatch(cur, cmd);
1653 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1654 FuncStatus & status) const
1656 switch (cmd.action()) {
1657 case LFUN_FINISHED_BACKWARD:
1658 case LFUN_FINISHED_FORWARD:
1659 case LFUN_FINISHED_RIGHT:
1660 case LFUN_FINISHED_LEFT:
1663 case LFUN_NEWLINE_INSERT:
1664 case LFUN_MATH_EXTERN:
1666 status.setEnabled(true);
1669 // we never allow this in math, and we want to bind enter
1670 // to another actions in command-alternatives
1671 case LFUN_PARAGRAPH_BREAK:
1672 status.setEnabled(false);
1674 case LFUN_MATH_MUTATE: {
1675 HullType const ht = hullType(cmd.argument());
1676 status.setOnOff(type_ == ht);
1677 status.setEnabled(true);
1679 if (ht != hullSimple) {
1680 Cursor tmpcur = cur;
1681 while (!tmpcur.empty()) {
1682 InsetCode code = tmpcur.inset().lyxCode();
1683 if (code == BOX_CODE) {
1685 } else if (code == TABULAR_CODE) {
1686 FuncRequest tmpcmd(LFUN_MATH_DISPLAY);
1687 if (tmpcur.getStatus(tmpcmd, status) && !status.enabled())
1695 case LFUN_MATH_DISPLAY: {
1697 if (cur.depth() > 1) {
1698 Inset const & in = cur[cur.depth()-2].inset();
1699 if (in.lyxCode() == SCRIPT_CODE)
1700 enable = display() != Inline;
1702 status.setEnabled(enable);
1703 status.setOnOff(display() != Inline);
1707 case LFUN_MATH_NUMBER_TOGGLE:
1708 // FIXME: what is the right test, this or the one of
1710 status.setEnabled(display() != Inline);
1711 status.setOnOff(numberedType());
1714 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1715 // FIXME: what is the right test, this or the one of
1717 bool const enable = (type_ == hullMultline)
1718 ? (nrows() - 1 == cur.row())
1719 : display() != Inline;
1720 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1721 status.setEnabled(enable);
1722 status.setOnOff(enable && numbered(r));
1726 case LFUN_LABEL_INSERT:
1727 status.setEnabled(type_ != hullSimple);
1730 case LFUN_LABEL_COPY_AS_REFERENCE: {
1731 bool enabled = false;
1733 if (cmd.argument().empty() && &cur.inset() == this) {
1734 // if there is no argument and we're inside math, we retrieve
1735 // the row number from the cursor position.
1736 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1737 enabled = numberedType() && label_[row] && numbered(row);
1739 // if there is an argument, find the corresponding label, else
1740 // check whether there is at least one label.
1741 for (row_type row = 0; row != nrows(); ++row) {
1742 if (numbered(row) && label_[row] &&
1743 (cmd.argument().empty() || label(row) == cmd.argument())) {
1749 status.setEnabled(enabled);
1753 case LFUN_INSET_INSERT:
1754 if (cmd.getArg(0) == "label") {
1755 status.setEnabled(type_ != hullSimple);
1758 return InsetMathGrid::getStatus(cur, cmd, status);
1760 case LFUN_INSET_MODIFY: {
1761 istringstream is(to_utf8(cmd.argument()));
1765 return InsetMathGrid::getStatus(cur, cmd, status);
1768 && (s == "append-row"
1769 || s == "delete-row"
1770 || s == "copy-row")) {
1771 status.message(bformat(
1772 from_utf8(N_("Can't change number of rows in '%1$s'")),
1774 status.setEnabled(false);
1778 && (s == "append-column"
1779 || s == "delete-column"
1780 || s == "copy-column")) {
1781 status.message(bformat(
1782 from_utf8(N_("Can't change number of columns in '%1$s'")),
1784 status.setEnabled(false);
1787 if ((type_ == hullSimple
1788 || type_ == hullEquation
1789 || type_ == hullNone) &&
1790 (s == "add-hline-above" || s == "add-hline-below")) {
1791 status.message(bformat(
1792 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1794 status.setEnabled(false);
1797 if (s == "add-vline-left" || s == "add-vline-right") {
1798 status.message(bformat(
1799 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1801 status.setEnabled(false);
1804 if (s == "valign-top" || s == "valign-middle"
1805 || s == "valign-bottom" || s == "align-left"
1806 || s == "align-center" || s == "align-right") {
1807 status.setEnabled(false);
1810 return InsetMathGrid::getStatus(cur, cmd, status);
1814 return InsetMathGrid::getStatus(cur, cmd, status);
1817 // This cannot really happen, but inserted to shut-up gcc
1818 return InsetMathGrid::getStatus(cur, cmd, status);
1822 /////////////////////////////////////////////////////////////////////
1826 // simply scrap this function if you want
1827 void InsetMathHull::mutateToText()
1830 // translate to latex
1832 latex(os, false, false);
1833 string str = os.str();
1836 Text * lt = view_->cursor().innerText();
1837 string::const_iterator cit = str.begin();
1838 string::const_iterator end = str.end();
1839 for (; cit != end; ++cit)
1840 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1843 //dispatch(LFUN_ESCAPE);
1848 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1849 docstring const & font)
1851 // this whole function is a hack and won't work for incremental font
1854 if (cur.inset().asInsetMath()->name() == font)
1855 cur.handleFont(to_utf8(font));
1857 cur.handleNest(createInsetMath(font, cur.buffer()));
1863 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1868 font.fromString(to_utf8(arg), b);
1869 if (font.fontInfo().color() != Color_inherit) {
1870 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1871 cur.handleNest(at, 0);
1876 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1879 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1880 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1881 enter_front ? idxFirst(cur) : idxLast(cur);
1882 // The inset formula dimension is not necessarily the same as the
1883 // one of the instant preview image, so we have to indicate to the
1884 // BufferView that a metrics update is needed.
1885 cur.screenUpdateFlags(Update::Force);
1889 void InsetMathHull::revealCodes(Cursor & cur) const
1891 if (!cur.inMathed())
1893 odocstringstream os;
1895 cur.message(os.str());
1897 // write something to the minibuffer
1898 // translate to latex
1902 string str = os.str();
1904 string::size_type pos = 0;
1906 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1909 else if (*it == '\0') {
1911 pos = it - str.begin();
1917 res = res.substr(pos - 30);
1918 if (res.size() > 60)
1919 res = res.substr(0, 60);
1925 /////////////////////////////////////////////////////////////////////
1929 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1932 // FIXME: completely broken
1933 static InsetMathHull * lastformula = 0;
1934 static CursorBase current = DocIterator(ibegin(nucleus()));
1936 static string laststr;
1938 if (lastformula != this || laststr != str) {
1939 //lyxerr << "reset lastformula to " << this << endl;
1942 current = ibegin(nucleus());
1944 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1948 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1950 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1951 CursorSlice & top = it.back();
1952 MathData const & a = top.asInsetMath()->cell(top.idx_);
1953 if (a.matchpart(ar, top.pos_)) {
1954 bv->cursor().setSelection(it, ar.size());
1956 top.pos_ += ar.size();
1962 //lyxerr << "not found!" << endl;
1969 void InsetMathHull::write(ostream & os) const
1971 odocstringstream oss;
1972 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1975 os << to_utf8(oss.str());
1979 void InsetMathHull::read(Lexer & lex)
1982 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1983 operator=(*at->asHullInset());
1987 bool InsetMathHull::readQuiet(Lexer & lex)
1990 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1992 operator=(*at->asHullInset());
1997 int InsetMathHull::plaintext(odocstringstream & os,
1998 OutputParams const & op, size_t max_length) const
2000 // disables ASCII-art for export of equations. See #2275.
2001 if (0 && display()) {
2005 TextPainter tpain(dim.width(), dim.height());
2006 drawT(tpain, 0, dim.ascent());
2008 // reset metrics cache to "real" values
2010 return tpain.textheight();
2013 odocstringstream oss;
2014 Encoding const * const enc = encodings.fromLyXName("utf8");
2015 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
2018 if (type_ == hullRegexp)
2021 for (row_type r = 0; r < nrows(); ++r) {
2022 for (col_type c = 0; c < ncols(); ++c)
2023 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2024 // if it's for the TOC, we write just the first line
2025 // and do not include the newline.
2026 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2028 if (r < nrows() - 1)
2032 docstring const str = oss.str();
2038 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
2043 if (getType() == hullSimple)
2044 name = from_ascii("inlineequation");
2046 name = from_ascii("informalequation");
2048 docstring bname = name;
2049 if (!label(0).empty())
2050 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
2052 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
2054 odocstringstream ls;
2055 if (runparams.flavor == OutputParams::XML) {
2056 ms << MTag("alt role='tex' ");
2057 // Workaround for db2latex: db2latex always includes equations with
2058 // \ensuremath{} or \begin{display}\end{display}
2059 // so we strip LyX' math environment
2060 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
2061 InsetMathGrid::write(wi);
2062 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2067 InsetMathGrid::mathmlize(ms);
2072 otexstream ols(ls, texrow);
2073 ms << MTag("alt role='tex'");
2074 latex(ols, runparams);
2075 res = texrow.rows();
2076 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2080 ms << from_ascii("<graphic fileref=\"eqn/");
2081 if (!label(0).empty())
2082 ms << sgml::cleanID(buffer(), runparams, label(0));
2084 ms << sgml::uniqueID(from_ascii("anon"));
2086 if (runparams.flavor == OutputParams::XML)
2087 ms << from_ascii("\"/>");
2089 ms << from_ascii("\">");
2091 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2093 return ms.line() + res;
2097 bool InsetMathHull::haveNumbers() const
2099 bool havenumbers = false;
2100 // inline formulas are never numbered (bug 7351 part 3)
2101 if (getType() == hullSimple)
2103 for (size_t i = 0; i != numbered_.size(); ++i) {
2114 // We need to do something about alignment here.
2116 // This duplicates code from InsetMathGrid, but
2117 // we need access here to number information,
2118 // and we simply do not have that in InsetMathGrid.
2119 void InsetMathHull::htmlize(HtmlStream & os) const
2121 bool const havenumbers = haveNumbers();
2122 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2125 os << cell(index(0, 0));
2129 os << MTag("table", "class='mathtable'");
2130 for (row_type row = 0; row < nrows(); ++row) {
2132 for (col_type col = 0; col < ncols(); ++col) {
2134 os << cell(index(row, col));
2139 docstring const & num = numbers_[row];
2141 os << '(' << num << ')';
2146 os << ETag("table");
2150 // this duplicates code from InsetMathGrid, but
2151 // we need access here to number information,
2152 // and we simply do not have that in InsetMathGrid.
2153 void InsetMathHull::mathmlize(MathStream & os) const
2155 bool const havenumbers = haveNumbers();
2156 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2159 os << MTag("mtable");
2160 char const * const celltag = havetable ? "mtd" : "mrow";
2161 // FIXME There does not seem to be wide support at the moment
2162 // for mlabeledtr, so we have to use just mtr for now.
2163 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2164 char const * const rowtag = "mtr";
2165 for (row_type row = 0; row < nrows(); ++row) {
2168 for (col_type col = 0; col < ncols(); ++col) {
2170 << cell(index(row, col))
2176 docstring const & num = numbers_[row];
2178 os << '(' << num << ')';
2185 os << ETag("mtable");
2189 void InsetMathHull::mathAsLatex(WriteStream & os) const
2191 MathEnsurer ensurer(os, false);
2192 bool havenumbers = haveNumbers();
2193 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2196 os << cell(index(0, 0));
2200 os << "<table class='mathtable'>";
2201 for (row_type row = 0; row < nrows(); ++row) {
2203 for (col_type col = 0; col < ncols(); ++col) {
2204 os << "<td class='math'>";
2205 os << cell(index(row, col));
2210 docstring const & num = numbers_[row];
2212 os << '(' << num << ')';
2221 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2223 BufferParams::MathOutput const mathtype =
2224 buffer().masterBuffer()->params().html_math_output;
2226 bool success = false;
2228 // we output all the labels just at the beginning of the equation.
2229 // this should be fine.
2230 for (size_t i = 0; i != label_.size(); ++i) {
2231 InsetLabel const * const il = label_[i];
2237 // FIXME Eventually we would like to do this inset by inset.
2238 if (mathtype == BufferParams::MathML) {
2239 odocstringstream os;
2244 } catch (MathExportException const &) {}
2246 if (getType() == hullSimple)
2247 xs << html::StartTag("math",
2248 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2250 xs << html::StartTag("math",
2251 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2252 xs << XHTMLStream::ESCAPE_NONE
2254 << html::EndTag("math");
2256 } else if (mathtype == BufferParams::HTML) {
2257 odocstringstream os;
2262 } catch (MathExportException const &) {}
2264 string const tag = (getType() == hullSimple) ? "span" : "div";
2265 xs << html::StartTag(tag, "class='formula'", true)
2266 << XHTMLStream::ESCAPE_NONE
2268 << html::EndTag(tag);
2272 // what we actually want is this:
2274 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2276 // || mathtype == BufferParams::Images
2278 // but what follows is equivalent, since we'll enter only if either (a) we
2279 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2280 // aren't doing LaTeX, in which case we are doing Images.
2281 if (!success && mathtype != BufferParams::LaTeX) {
2282 graphics::PreviewImage const * pimage = 0;
2284 loadPreview(docit_);
2285 pimage = preview_->getPreviewImage(buffer());
2286 // FIXME Do we always have png?
2289 if (pimage || op.dryrun) {
2290 string const filename = pimage ? pimage->filename().onlyFileName()
2291 : "previewimage.png";
2293 // if we are not in the master buffer, then we need to see that the
2294 // generated image is copied there; otherwise, preview fails.
2295 Buffer const * mbuf = buffer().masterBuffer();
2296 if (mbuf != &buffer()) {
2297 string mbtmp = mbuf->temppath();
2298 FileName const mbufimg(support::addName(mbtmp, filename));
2299 pimage->filename().copyTo(mbufimg);
2301 // add the file to the list of files to be exported
2302 op.exportdata->addExternalFile("xhtml", pimage->filename());
2305 string const tag = (getType() == hullSimple) ? "span" : "div";
2307 << html::StartTag(tag)
2308 << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2309 << html::EndTag(tag)
2315 // so we'll pass this test if we've failed everything else, or
2316 // if mathtype was LaTeX, since we won't have entered any of the
2318 if (!success /* || mathtype != BufferParams::LaTeX */) {
2319 // Unfortunately, we cannot use latexString() because we do not want
2320 // $...$ or whatever.
2321 odocstringstream ls;
2322 WriteStream wi(ls, false, true, WriteStream::wsPreview);
2323 ModeSpecifier specifier(wi, MATH_MODE);
2325 docstring const latex = ls.str();
2327 // class='math' allows for use of jsMath
2328 // http://www.math.union.edu/~dpvc/jsMath/
2330 // probably should allow for some kind of customization here
2331 string const tag = (getType() == hullSimple) ? "span" : "div";
2332 xs << html::StartTag(tag, "class='math'")
2334 << html::EndTag(tag)
2341 void InsetMathHull::toString(odocstream & os) const
2343 odocstringstream ods;
2344 plaintext(ods, OutputParams(0));
2349 void InsetMathHull::forOutliner(docstring & os, size_t) const
2351 odocstringstream ods;
2359 string InsetMathHull::contextMenuName() const
2361 return "context-math";
2365 void InsetMathHull::recordLocation(DocIterator const & di)