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"
31 #include "LaTeXFeatures.h"
33 #include "MacroTable.h"
34 #include "output_xhtml.h"
36 #include "TextPainter.h"
37 #include "TocBackend.h"
39 #include "insets/InsetLabel.h"
40 #include "insets/InsetRef.h"
41 #include "insets/RenderPreview.h"
43 #include "graphics/PreviewImage.h"
44 #include "graphics/PreviewLoader.h"
46 #include "frontends/Painter.h"
48 #include "support/lassert.h"
49 #include "support/debug.h"
50 #include "support/gettext.h"
51 #include "support/lstrings.h"
56 using namespace lyx::support;
60 using cap::grabAndEraseSelection;
64 int getCols(HullType type)
81 // returns position of first relation operator in the array
82 // used for "intelligent splitting"
83 size_t firstRelOp(MathData const & ar)
85 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
87 return it - ar.begin();
92 char const * star(bool numbered)
94 return numbered ? "" : "*";
98 } // end anon namespace
101 HullType hullType(docstring const & s)
103 if (s == "none") return hullNone;
104 if (s == "simple") return hullSimple;
105 if (s == "equation") return hullEquation;
106 if (s == "eqnarray") return hullEqnArray;
107 if (s == "align") return hullAlign;
108 if (s == "alignat") return hullAlignAt;
109 if (s == "xalignat") return hullXAlignAt;
110 if (s == "xxalignat") return hullXXAlignAt;
111 if (s == "multline") return hullMultline;
112 if (s == "gather") return hullGather;
113 if (s == "flalign") return hullFlAlign;
114 if (s == "regexp") return hullRegexp;
115 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
120 docstring hullName(HullType type)
123 case hullNone: return from_ascii("none");
124 case hullSimple: return from_ascii("simple");
125 case hullEquation: return from_ascii("equation");
126 case hullEqnArray: return from_ascii("eqnarray");
127 case hullAlign: return from_ascii("align");
128 case hullAlignAt: return from_ascii("alignat");
129 case hullXAlignAt: return from_ascii("xalignat");
130 case hullXXAlignAt: return from_ascii("xxalignat");
131 case hullMultline: return from_ascii("multline");
132 case hullGather: return from_ascii("gather");
133 case hullFlAlign: return from_ascii("flalign");
134 case hullRegexp: return from_ascii("regexp");
136 lyxerr << "unknown hull type '" << type << "'" << endl;
137 return from_ascii("none");
141 static InsetLabel * dummy_pointer = 0;
143 InsetMathHull::InsetMathHull(Buffer * buf)
144 : InsetMathGrid(buf, 1, 1), type_(hullNone), nonum_(1, false),
145 label_(1, dummy_pointer), preview_(new RenderPreview(this))
147 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
148 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
149 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
150 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
157 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
158 : InsetMathGrid(buf, getCols(type), 1), type_(type), nonum_(1, false),
159 label_(1, dummy_pointer), preview_(new RenderPreview(this))
167 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
173 InsetMathHull::~InsetMathHull()
175 for (size_t i = 0; i < label_.size(); ++i)
180 Inset * InsetMathHull::clone() const
182 return new InsetMathHull(*this);
186 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
190 InsetMathGrid::operator=(other);
192 nonum_ = other.nonum_;
193 buffer_ = other.buffer_;
194 for (size_t i = 0; i < label_.size(); ++i)
196 label_ = other.label_;
197 for (size_t i = 0; i != label_.size(); ++i) {
199 label_[i] = new InsetLabel(*label_[i]);
201 preview_.reset(new RenderPreview(*other.preview_, this));
207 void InsetMathHull::setBuffer(Buffer & buffer)
209 InsetMathGrid::setBuffer(buffer);
211 for (size_t i = 0; i != label_.size(); ++i) {
213 label_[i]->setBuffer(buffer);
218 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
221 //FIXME: buffer_ should be set at creation for this inset! Problem is
222 // This inset is created at too many places (see Parser::parse1() in
226 for (size_t i = 0; i != label_.size(); ++i) {
228 label_[i]->updateBuffer(it, utype);
231 InsetMathGrid::updateBuffer(it, utype);
235 void InsetMathHull::addToToc(DocIterator const & pit)
238 //FIXME: buffer_ should be set at creation for this inset! Problem is
239 // This inset is created at too many places (see Parser::parse1() in
244 Toc & toc = buffer().tocBackend().toc("equation");
246 for (row_type row = 0; row != nrows(); ++row) {
250 label_[row]->addToToc(pit);
251 toc.push_back(TocItem(pit, 0, nicelabel(row)));
256 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
262 return InsetMathNest::editXY(cur, x, y);
266 InsetMath::mode_type InsetMathHull::currentMode() const
268 if (type_ == hullNone)
269 return UNDECIDED_MODE;
270 // definitely math mode ...
275 bool InsetMathHull::idxFirst(Cursor & cur) const
283 bool InsetMathHull::idxLast(Cursor & cur) const
285 cur.idx() = nargs() - 1;
286 cur.pos() = cur.lastpos();
291 char InsetMathHull::defaultColAlign(col_type col)
293 if (type_ == hullEqnArray)
295 if (type_ == hullGather)
297 if (type_ >= hullAlign)
298 return "rl"[col & 1];
303 int InsetMathHull::defaultColSpace(col_type col)
305 if (type_ == hullAlign || type_ == hullAlignAt)
307 if (type_ == hullXAlignAt)
308 return (col & 1) ? 20 : 0;
309 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
310 return (col & 1) ? 40 : 0;
315 docstring InsetMathHull::standardFont() const
320 font_name = from_ascii("texttt");
323 font_name = from_ascii("lyxnochange");
326 font_name = from_ascii("mathnormal");
332 docstring InsetMathHull::standardColor() const
337 color = from_ascii("foreground");
340 color = from_ascii("foreground");
343 color = from_ascii("math");
349 bool InsetMathHull::previewState(BufferView * bv) const
351 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
352 graphics::PreviewImage const * pimage =
353 preview_->getPreviewImage(bv->buffer());
354 return pimage && pimage->image();
360 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
362 if (previewState(mi.base.bv)) {
363 preview_->metrics(mi, dim);
364 // insert a one pixel gap in front of the formula
367 dim.des += displayMargin();
368 // Cache the inset dimension.
369 setDimCache(mi, dim);
373 FontSetChanger dummy1(mi.base, standardFont());
374 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
376 // let the cells adjust themselves
377 InsetMathGrid::metrics(mi, dim);
380 dim.asc += displayMargin();
381 dim.des += displayMargin();
384 if (numberedType()) {
385 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
387 for (row_type row = 0; row < nrows(); ++row)
388 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
394 // make it at least as high as the current font
397 math_font_max_dim(mi.base.font, asc, des);
398 dim.asc = max(dim.asc, asc);
399 dim.des = max(dim.des, des);
400 // Cache the inset dimension.
401 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
402 setDimCache(mi, dim);
406 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
408 if (previewState(pi.base.bv))
409 return graphics::PreviewLoader::backgroundColor();
414 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
416 Dimension const dim = dimension(*pi.base.bv);
417 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
418 dim.asc + dim.des - 1, pi.backgroundColor(this));
422 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
424 use_preview_ = previewState(pi.base.bv);
426 if (type_ == hullRegexp) {
427 Dimension const dim = dimension(*pi.base.bv);
428 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
429 dim.width() - 2, dim.height() - 2, Color_regexpframe);
432 // one pixel gap in front
433 preview_->draw(pi, x + 1, y);
434 setPosCache(pi, x, y);
438 bool const really_change_color = pi.base.font.color() == Color_none;
439 ColorChanger dummy0(pi.base.font, standardColor(), really_change_color);
440 FontSetChanger dummy1(pi.base, standardFont());
441 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
443 InsetMathGrid::draw(pi, x + 1, y);
445 if (numberedType()) {
446 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
447 for (row_type row = 0; row < nrows(); ++row) {
448 int const yy = y + rowinfo_[row].offset_;
449 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
450 docstring const nl = nicelabel(row);
454 setPosCache(pi, x, y);
458 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
461 InsetMathGrid::metricsT(mi, dim);
464 WriteStream wi(os, false, true, WriteStream::wsDefault);
466 dim.wid = os.str().size();
473 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
476 InsetMathGrid::drawT(pain, x, y);
479 WriteStream wi(os, false, true, WriteStream::wsDefault);
481 pain.draw(x, y, os.str().c_str());
486 static docstring latexString(InsetMathHull const & inset)
489 // This has to be static, because a preview snippet or a math
490 // macro containing math in text mode (such as $\text{$\phi$}$ or
491 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
492 // first time as a whole, and the second time only the inner math.
493 // In this last case inset.buffer() would be invalid.
494 static Encoding const * encoding = 0;
495 if (inset.isBufferValid())
496 encoding = &(inset.buffer().params().encoding());
497 WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
503 void InsetMathHull::initUnicodeMath() const
505 // Trigger classification of the unicode symbols in this inset
506 docstring const dummy = latexString(*this);
510 void InsetMathHull::addPreview(DocIterator const & inset_pos,
511 graphics::PreviewLoader & /*ploader*/) const
513 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
514 preparePreview(inset_pos);
519 void InsetMathHull::preparePreview(DocIterator const & pos) const
521 Buffer const * buffer = pos.buffer();
523 // collect macros at this position
525 buffer->listMacroNames(macros);
526 MacroNameSet::iterator it = macros.begin();
527 MacroNameSet::iterator end = macros.end();
528 odocstringstream macro_preamble;
529 for (; it != end; ++it) {
530 MacroData const * data = buffer->getMacro(*it, pos, true);
532 data->write(macro_preamble, true);
533 macro_preamble << endl;
537 docstring const snippet = macro_preamble.str() + latexString(*this);
538 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
539 preview_->addPreview(snippet, *buffer);
543 void InsetMathHull::reloadPreview(DocIterator const & pos, bool wait) const
546 preview_->startLoading(*pos.buffer(), wait);
550 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
552 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
554 cur.screenUpdateFlags(Update::Force);
560 docstring InsetMathHull::label(row_type row) const
562 LASSERT(row < nrows(), /**/);
563 if (InsetLabel * il = label_[row])
564 return il->screenLabel();
569 void InsetMathHull::label(row_type row, docstring const & label)
571 //lyxerr << "setting label '" << label << "' for row " << row << endl;
575 label_[row] = dummy_pointer;
578 label_[row]->updateCommand(label);
580 label_[row]->setParam("name", label);
584 InsetCommandParams p(LABEL_CODE);
586 label_[row] = new InsetLabel(buffer_, p);
588 label_[row]->setBuffer(buffer());
592 void InsetMathHull::numbered(row_type row, bool num)
595 if (nonum_[row] && label_[row]) {
602 bool InsetMathHull::numbered(row_type row) const
608 bool InsetMathHull::ams() const
610 return type_ == hullAlign
611 || type_ == hullFlAlign
612 || type_ == hullMultline
613 || type_ == hullGather
614 || type_ == hullAlignAt
615 || type_ == hullXAlignAt
616 || type_ == hullXXAlignAt;
620 Inset::DisplayType InsetMathHull::display() const
622 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
627 bool InsetMathHull::numberedType() const
629 if (type_ == hullNone)
631 if (type_ == hullSimple)
633 if (type_ == hullXXAlignAt)
635 if (type_ == hullRegexp)
637 for (row_type row = 0; row < nrows(); ++row)
644 void InsetMathHull::validate(LaTeXFeatures & features) const
646 if (features.runparams().isLaTeX()) {
648 features.require("amsmath");
650 if (type_ == hullRegexp) {
651 features.require("color");
652 string frcol = lcolor.getLaTeXName(Color_regexpframe);
653 string bgcol = "white";
654 features.addPreambleSnippet(
655 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
656 + frcol + string("}{")
657 + bgcol + string("}{\\texttt{#1}}}"));
660 // Validation is necessary only if not using AMS math.
661 // To be safe, we will always run mathedvalidate.
662 //if (features.amsstyle)
665 //features.binom = true;
666 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
667 // it would be better to do this elsewhere, but we can't validate in
668 // InsetMathMatrix and we have no way, outside MathExtern, to know if
669 // we even have any matrices.
670 features.addPreambleSnippet("<style type=\"text/css\">\n"
671 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
672 "table.matrix td{padding: 0.25px;}\n"
673 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
674 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}\n"
677 InsetMathGrid::validate(features);
681 void InsetMathHull::header_write(WriteStream & os) const
683 bool n = numberedType();
697 os << "\\begin{equation" << star(n) << "}\n";
707 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
712 os << "\\begin{" << hullName(type_) << star(n) << '}'
713 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
717 os << "\\begin{" << hullName(type_) << '}'
718 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
726 os << "\\begin{unknown" << star(n) << '}';
732 void InsetMathHull::footer_write(WriteStream & os) const
734 bool n = numberedType();
747 os << "\\end{equation" << star(n) << "}\n";
759 os << "\\end{" << hullName(type_) << star(n) << "}\n";
763 os << "\\end{" << hullName(type_) << "}\n";
771 os << "\\end{unknown" << star(n) << '}';
777 bool InsetMathHull::rowChangeOK() const
780 type_ == hullEqnArray || type_ == hullAlign ||
781 type_ == hullFlAlign || type_ == hullAlignAt ||
782 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
783 type_ == hullGather || type_ == hullMultline;
787 bool InsetMathHull::colChangeOK() const
790 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
791 type_ == hullXAlignAt || type_ == hullXXAlignAt;
795 void InsetMathHull::addRow(row_type row)
800 bool numbered = numberedType();
802 if (type_ == hullMultline) {
803 if (row + 1 == nrows()) {
810 nonum_.insert(nonum_.begin() + row + 1, !numbered);
811 label_.insert(label_.begin() + row + 1, dummy_pointer);
814 InsetMathGrid::addRow(row);
818 void InsetMathHull::swapRow(row_type row)
822 if (row + 1 == nrows())
824 // gcc implements the standard std::vector<bool> which is *not* a container:
825 // http://www.gotw.ca/publications/N1185.pdf
826 // As a results, it doesn't like this:
827 // swap(nonum_[row], nonum_[row + 1]);
828 // so we do it manually:
829 bool const b = nonum_[row];
830 nonum_[row] = nonum_[row + 1];
832 swap(label_[row], label_[row + 1]);
833 InsetMathGrid::swapRow(row);
837 void InsetMathHull::delRow(row_type row)
839 if (nrows() <= 1 || !rowChangeOK())
841 if (row + 1 == nrows() && type_ == hullMultline) {
842 bool const b = nonum_[row - 1];
843 nonum_[row - 1] = nonum_[row];
845 swap(label_[row - 1], label_[row]);
846 InsetMathGrid::delRow(row);
849 InsetMathGrid::delRow(row);
850 // The last dummy row has no number info nor a label.
851 // Test nrows() + 1 because we have already erased the row.
852 if (row == nrows() + 1)
854 nonum_.erase(nonum_.begin() + row);
856 label_.erase(label_.begin() + row);
860 void InsetMathHull::addCol(col_type col)
864 InsetMathGrid::addCol(col);
868 void InsetMathHull::delCol(col_type col)
870 if (ncols() <= 1 || !colChangeOK())
872 InsetMathGrid::delCol(col);
876 docstring InsetMathHull::nicelabel(row_type row) const
881 return from_ascii("(#)");
882 return '(' + label_[row]->screenLabel() + from_ascii(", #)");
886 void InsetMathHull::glueall()
889 for (idx_type i = 0; i < nargs(); ++i)
891 *this = InsetMathHull(buffer_, hullSimple);
897 void InsetMathHull::splitTo2Cols()
899 LASSERT(ncols() == 1, /**/);
900 InsetMathGrid::addCol(1);
901 for (row_type row = 0; row < nrows(); ++row) {
902 idx_type const i = 2 * row;
903 pos_type pos = firstRelOp(cell(i));
904 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
905 cell(i).erase(pos, cell(i).size());
910 void InsetMathHull::splitTo3Cols()
912 LASSERT(ncols() < 3, /**/);
915 InsetMathGrid::addCol(2);
916 for (row_type row = 0; row < nrows(); ++row) {
917 idx_type const i = 3 * row + 1;
918 if (cell(i).size()) {
919 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
920 cell(i).erase(1, cell(i).size());
926 void InsetMathHull::changeCols(col_type cols)
930 else if (ncols() < cols) {
936 while (ncols() < cols)
937 InsetMathGrid::addCol(ncols());
943 for (row_type row = 0; row < nrows(); ++row) {
944 idx_type const i = row * ncols();
945 for (col_type col = cols; col < ncols(); ++col) {
946 cell(i + cols - 1).append(cell(i + col));
950 while (ncols() > cols) {
951 InsetMathGrid::delCol(ncols() - 1);
956 HullType InsetMathHull::getType() const
962 void InsetMathHull::setType(HullType type)
969 void InsetMathHull::mutate(HullType newtype)
971 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
973 // we try to move along the chain
974 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
976 // +-------------------------------------+
977 // we use eqnarray as intermediate type for mutations that are not
978 // directly supported because it handles labels and numbering for
981 if (newtype == type_) {
985 else if (newtype < hullNone) {
990 else if (type_ == hullNone) {
996 else if (type_ == hullSimple) {
997 if (newtype == hullNone) {
1001 setType(hullEquation);
1007 else if (type_ == hullEquation) {
1008 if (newtype < type_) {
1009 setType(hullSimple);
1012 } else if (newtype == hullEqnArray) {
1013 // split it "nicely" on the first relop
1015 setType(hullEqnArray);
1016 } else if (newtype == hullMultline || newtype == hullGather) {
1019 // split it "nicely"
1026 else if (type_ == hullEqnArray) {
1027 if (newtype < type_) {
1028 // set correct (no)numbering
1030 for (row_type row = 0; row < nrows(); ++row) {
1037 // set first non-empty label
1038 for (row_type row = 0; row < nrows(); ++row) {
1040 label_[0] = label_[row];
1047 } else { // align & Co.
1054 else if (type_ == hullAlign || type_ == hullAlignAt ||
1055 type_ == hullXAlignAt || type_ == hullFlAlign) {
1056 if (newtype < hullAlign) {
1058 setType(hullEqnArray);
1060 } else if (newtype == hullGather || newtype == hullMultline) {
1063 } else if (newtype == hullXXAlignAt) {
1064 for (row_type row = 0; row < nrows(); ++row)
1065 numbered(row, false);
1072 else if (type_ == hullXXAlignAt) {
1073 for (row_type row = 0; row < nrows(); ++row)
1074 numbered(row, false);
1075 if (newtype < hullAlign) {
1077 setType(hullEqnArray);
1079 } else if (newtype == hullGather || newtype == hullMultline) {
1087 else if (type_ == hullMultline || type_ == hullGather) {
1088 if (newtype == hullGather || newtype == hullMultline)
1090 else if (newtype == hullAlign || newtype == hullFlAlign ||
1091 newtype == hullAlignAt || newtype == hullXAlignAt) {
1094 } else if (newtype == hullXXAlignAt) {
1096 for (row_type row = 0; row < nrows(); ++row)
1097 numbered(row, false);
1101 setType(hullEqnArray);
1107 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1108 << "' to '" << to_utf8(hullName(newtype))
1109 << "' not implemented" << endl;
1114 docstring InsetMathHull::eolString(row_type row, bool fragile, bool last_eoln) const
1117 if (numberedType()) {
1118 if (label_[row] && !nonum_[row])
1120 escape(label_[row]->getParam("name")) + '}';
1121 if (nonum_[row] && (type_ != hullMultline))
1122 res += "\\nonumber ";
1124 // Never add \\ on the last empty line of eqnarray and friends
1126 return res + InsetMathGrid::eolString(row, fragile, last_eoln);
1130 void InsetMathHull::write(WriteStream & os) const
1132 ModeSpecifier specifier(os, MATH_MODE);
1134 InsetMathGrid::write(os);
1139 void InsetMathHull::normalize(NormalStream & os) const
1141 os << "[formula " << hullName(type_) << ' ';
1142 InsetMathGrid::normalize(os);
1147 void InsetMathHull::mathmlize(MathStream & os) const
1149 InsetMathGrid::mathmlize(os);
1153 void InsetMathHull::infoize(odocstream & os) const
1155 os << "Type: " << hullName(type_);
1159 void InsetMathHull::check() const
1161 LASSERT(nonum_.size() == nrows(), /**/);
1162 LASSERT(label_.size() == nrows(), /**/);
1166 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1170 idocstringstream iss(func.argument());
1171 iss >> dlang >> extra;
1173 extra = from_ascii("noextra");
1174 string const lang = to_ascii(dlang);
1176 // FIXME: temporarily disabled
1177 //if (cur.selection()) {
1180 // lyxerr << "use selection: " << ar << endl;
1181 // insert(pipeThroughExtern(lang, extra, ar));
1186 eq.push_back(MathAtom(new InsetMathChar('=')));
1188 // go to first item in line
1189 cur.idx() -= cur.idx() % ncols();
1192 if (getType() == hullSimple) {
1193 size_type pos = cur.cell().find_last(eq);
1195 if (cur.inMathed() && cur.selection()) {
1196 asArray(grabAndEraseSelection(cur), ar);
1197 } else if (pos == cur.cell().size()) {
1199 lyxerr << "use whole cell: " << ar << endl;
1201 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1202 lyxerr << "use partial cell form pos: " << pos << endl;
1204 cur.cell().append(eq);
1205 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1206 cur.pos() = cur.lastpos();
1210 if (getType() == hullEquation) {
1211 lyxerr << "use equation inset" << endl;
1212 mutate(hullEqnArray);
1213 MathData & ar = cur.cell();
1214 lyxerr << "use cell: " << ar << endl;
1218 cur.cell() = pipeThroughExtern(lang, extra, ar);
1219 // move to end of line
1220 cur.pos() = cur.lastpos();
1225 lyxerr << "use eqnarray" << endl;
1226 cur.idx() += 2 - cur.idx() % ncols();
1228 MathData ar = cur.cell();
1229 lyxerr << "use cell: " << ar << endl;
1230 // FIXME: temporarily disabled
1236 cur.cell() = pipeThroughExtern(lang, extra, ar);
1237 cur.pos() = cur.lastpos();
1242 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1244 //lyxerr << "action: " << cmd.action() << endl;
1245 switch (cmd.action()) {
1247 case LFUN_FINISHED_BACKWARD:
1248 case LFUN_FINISHED_FORWARD:
1249 case LFUN_FINISHED_RIGHT:
1250 case LFUN_FINISHED_LEFT:
1251 //lyxerr << "action: " << cmd.action() << endl;
1252 InsetMathGrid::doDispatch(cur, cmd);
1256 case LFUN_BREAK_PARAGRAPH:
1257 // just swallow this
1260 case LFUN_NEWLINE_INSERT:
1261 // some magic for the common case
1262 if (type_ == hullSimple || type_ == hullEquation) {
1263 cur.recordUndoInset();
1265 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1266 mutate(align ? hullAlign : hullEqnArray);
1267 // mutate() may change labels and such.
1268 cur.forceBufferUpdate();
1269 cur.idx() = nrows() * ncols() - 1;
1270 cur.pos() = cur.lastpos();
1272 InsetMathGrid::doDispatch(cur, cmd);
1275 case LFUN_MATH_NUMBER_TOGGLE: {
1276 //lyxerr << "toggling all numbers" << endl;
1277 cur.recordUndoInset();
1278 bool old = numberedType();
1279 if (type_ == hullMultline)
1280 numbered(nrows() - 1, !old);
1282 for (row_type row = 0; row < nrows(); ++row)
1283 numbered(row, !old);
1285 cur.message(old ? _("No number") : _("Number"));
1286 cur.forceBufferUpdate();
1290 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1291 cur.recordUndoInset();
1292 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1293 bool old = numbered(r);
1294 cur.message(old ? _("No number") : _("Number"));
1296 cur.forceBufferUpdate();
1300 case LFUN_LABEL_INSERT: {
1301 cur.recordUndoInset();
1302 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1303 docstring old_label = label(r);
1305 // Allow customization of this separator
1306 docstring const default_label = from_ascii("eq:");
1307 if (old_label.empty())
1308 old_label = default_label;
1310 InsetCommandParams p(LABEL_CODE);
1311 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1312 string const data = InsetCommand::params2string("label", p);
1314 if (cmd.argument().empty())
1315 cur.bv().showDialog("label", data);
1317 FuncRequest fr(LFUN_INSET_INSERT, data);
1323 case LFUN_LABEL_COPY_AS_REF: {
1325 if (cmd.argument().empty() && &cur.inset() == this)
1326 // if there is no argument and we're inside math, we retrieve
1327 // the row number from the cursor position.
1328 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1330 // if there is an argument, find the corresponding label, else
1331 // check whether there is at least one label.
1332 for (row = 0; row != nrows(); ++row)
1333 if (!nonum_[row] && label_[row]
1334 && (cmd.argument().empty() || label(row) == cmd.argument()))
1341 InsetCommandParams p(REF_CODE, "ref");
1342 p["reference"] = label(row);
1343 cap::clearSelection();
1344 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1348 case LFUN_WORD_DELETE_FORWARD:
1349 case LFUN_CHAR_DELETE_FORWARD:
1350 if (col(cur.idx()) + 1 == ncols()
1351 && cur.pos() == cur.lastpos()
1352 && !cur.selection()) {
1353 if (!label(row(cur.idx())).empty()) {
1354 cur.recordUndoInset();
1355 label(row(cur.idx()), docstring());
1356 } else if (numbered(row(cur.idx()))) {
1357 cur.recordUndoInset();
1358 numbered(row(cur.idx()), false);
1359 cur.forceBufferUpdate();
1361 InsetMathGrid::doDispatch(cur, cmd);
1365 InsetMathGrid::doDispatch(cur, cmd);
1370 case LFUN_INSET_INSERT: {
1371 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1372 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1373 string const name = cmd.getArg(0);
1374 if (name == "label") {
1375 InsetCommandParams p(LABEL_CODE);
1376 InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1377 docstring str = p["name"];
1378 cur.recordUndoInset();
1379 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1383 docstring old = label(r);
1386 // The label will take care of the reference update.
1390 // Newly created inset so initialize it.
1391 label_[r]->initView();
1394 cur.forceBufferUpdate();
1397 InsetMathGrid::doDispatch(cur, cmd);
1401 case LFUN_MATH_EXTERN:
1402 cur.recordUndoInset();
1406 case LFUN_MATH_MUTATE: {
1407 cur.recordUndoInset();
1408 row_type row = cur.row();
1409 col_type col = cur.col();
1410 mutate(hullType(cmd.argument()));
1411 cur.idx() = row * ncols() + col;
1412 if (cur.idx() > cur.lastidx()) {
1413 cur.idx() = cur.lastidx();
1414 cur.pos() = cur.lastpos();
1416 if (cur.pos() > cur.lastpos())
1417 cur.pos() = cur.lastpos();
1419 cur.forceBufferUpdate();
1420 // FIXME: find some more clever handling of the selection,
1421 // i.e. preserve it.
1422 cur.clearSelection();
1423 //cur.dispatched(FINISHED);
1427 case LFUN_MATH_DISPLAY: {
1428 cur.recordUndoInset();
1429 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1431 cur.pos() = cur.lastpos();
1432 //cur.dispatched(FINISHED);
1437 InsetMathGrid::doDispatch(cur, cmd);
1443 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1444 FuncStatus & status) const
1446 switch (cmd.action()) {
1447 case LFUN_FINISHED_BACKWARD:
1448 case LFUN_FINISHED_FORWARD:
1449 case LFUN_FINISHED_RIGHT:
1450 case LFUN_FINISHED_LEFT:
1453 case LFUN_NEWLINE_INSERT:
1454 case LFUN_MATH_EXTERN:
1455 case LFUN_MATH_DISPLAY:
1457 status.setEnabled(true);
1460 case LFUN_MATH_MUTATE: {
1461 HullType ht = hullType(cmd.argument());
1462 status.setOnOff(type_ == ht);
1463 status.setEnabled(true);
1467 case LFUN_MATH_NUMBER_TOGGLE:
1468 // FIXME: what is the right test, this or the one of
1470 status.setEnabled(display() != Inline);
1471 status.setOnOff(numberedType());
1474 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1475 // FIXME: what is the right test, this or the one of
1477 bool const enable = (type_ == hullMultline)
1478 ? (nrows() - 1 == cur.row())
1479 : display() != Inline && nrows() > 1;
1480 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1481 status.setEnabled(enable);
1482 status.setOnOff(enable && numbered(r));
1486 case LFUN_LABEL_INSERT:
1487 status.setEnabled(type_ != hullSimple);
1490 case LFUN_LABEL_COPY_AS_REF: {
1491 bool enabled = false;
1493 if (cmd.argument().empty() && &cur.inset() == this) {
1494 // if there is no argument and we're inside math, we retrieve
1495 // the row number from the cursor position.
1496 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1497 enabled = numberedType() && label_[row] && !nonum_[row];
1499 // if there is an argument, find the corresponding label, else
1500 // check whether there is at least one label.
1501 for (row_type row = 0; row != nrows(); ++row) {
1502 if (!nonum_[row] && label_[row] &&
1503 (cmd.argument().empty() || label(row) == cmd.argument())) {
1509 status.setEnabled(enabled);
1513 case LFUN_INSET_INSERT:
1514 if (cmd.getArg(0) == "label") {
1515 status.setEnabled(type_ != hullSimple);
1518 return InsetMathGrid::getStatus(cur, cmd, status);
1520 case LFUN_INSET_MODIFY: {
1521 istringstream is(to_utf8(cmd.argument()));
1525 return InsetMathGrid::getStatus(cur, cmd, status);
1528 && (s == "append-row"
1529 || s == "delete-row"
1530 || s == "copy-row")) {
1531 status.message(bformat(
1532 from_utf8(N_("Can't change number of rows in '%1$s'")),
1534 status.setEnabled(false);
1538 && (s == "append-column"
1539 || s == "delete-column"
1540 || s == "copy-column")) {
1541 status.message(bformat(
1542 from_utf8(N_("Can't change number of columns in '%1$s'")),
1544 status.setEnabled(false);
1547 if ((type_ == hullSimple
1548 || type_ == hullEquation
1549 || type_ == hullNone) &&
1550 (s == "add-hline-above" || s == "add-hline-below")) {
1551 status.message(bformat(
1552 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1554 status.setEnabled(false);
1557 if (s == "add-vline-left" || s == "add-vline-right") {
1558 status.message(bformat(
1559 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1561 status.setEnabled(false);
1564 if (s == "valign-top" || s == "valign-middle"
1565 || s == "valign-bottom" || s == "align-left"
1566 || s == "align-center" || s == "align-right") {
1567 status.setEnabled(false);
1570 return InsetMathGrid::getStatus(cur, cmd, status);
1574 return InsetMathGrid::getStatus(cur, cmd, status);
1577 // This cannot really happen, but inserted to shut-up gcc
1578 return InsetMathGrid::getStatus(cur, cmd, status);
1582 /////////////////////////////////////////////////////////////////////
1586 // simply scrap this function if you want
1587 void InsetMathHull::mutateToText()
1590 // translate to latex
1592 latex(os, false, false);
1593 string str = os.str();
1596 Text * lt = view_->cursor().innerText();
1597 string::const_iterator cit = str.begin();
1598 string::const_iterator end = str.end();
1599 for (; cit != end; ++cit)
1600 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1603 //dispatch(LFUN_ESCAPE);
1608 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1609 docstring const & font)
1611 // this whole function is a hack and won't work for incremental font
1614 if (cur.inset().asInsetMath()->name() == font)
1615 cur.handleFont(to_utf8(font));
1617 cur.handleNest(createInsetMath(font, cur.buffer()));
1623 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1628 font.fromString(to_utf8(arg), b);
1629 if (font.fontInfo().color() != Color_inherit) {
1630 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1631 cur.handleNest(at, 0);
1636 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1639 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1640 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1641 enter_front ? idxFirst(cur) : idxLast(cur);
1642 // The inset formula dimension is not necessarily the same as the
1643 // one of the instant preview image, so we have to indicate to the
1644 // BufferView that a metrics update is needed.
1645 cur.screenUpdateFlags(Update::Force);
1649 void InsetMathHull::revealCodes(Cursor & cur) const
1651 if (!cur.inMathed())
1653 odocstringstream os;
1655 cur.message(os.str());
1657 // write something to the minibuffer
1658 // translate to latex
1662 string str = os.str();
1664 string::size_type pos = 0;
1666 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1669 else if (*it == '\0') {
1671 pos = it - str.begin();
1677 res = res.substr(pos - 30);
1678 if (res.size() > 60)
1679 res = res.substr(0, 60);
1685 /////////////////////////////////////////////////////////////////////
1689 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1692 // FIXME: completely broken
1693 static InsetMathHull * lastformula = 0;
1694 static CursorBase current = DocIterator(ibegin(nucleus()));
1696 static string laststr;
1698 if (lastformula != this || laststr != str) {
1699 //lyxerr << "reset lastformula to " << this << endl;
1702 current = ibegin(nucleus());
1704 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1708 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1710 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1711 CursorSlice & top = it.back();
1712 MathData const & a = top.asInsetMath()->cell(top.idx_);
1713 if (a.matchpart(ar, top.pos_)) {
1714 bv->cursor().setSelection(it, ar.size());
1716 top.pos_ += ar.size();
1722 //lyxerr << "not found!" << endl;
1729 void InsetMathHull::write(ostream & os) const
1731 odocstringstream oss;
1732 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1735 os << to_utf8(oss.str());
1739 void InsetMathHull::read(Lexer & lex)
1742 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1743 operator=(*at->asHullInset());
1747 bool InsetMathHull::readQuiet(Lexer & lex)
1750 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1752 operator=(*at->asHullInset());
1757 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1759 // disables ASCII-art for export of equations. See #2275.
1760 if (0 && display()) {
1764 TextPainter tpain(dim.width(), dim.height());
1765 drawT(tpain, 0, dim.ascent());
1767 // reset metrics cache to "real" values
1769 return tpain.textheight();
1771 odocstringstream oss;
1772 Encoding const * const enc = encodings.fromLyXName("utf8");
1773 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1775 if (type_ == hullRegexp)
1779 docstring const str = oss.str();
1786 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1791 if (getType() == hullSimple)
1792 name = from_ascii("inlineequation");
1794 name = from_ascii("informalequation");
1796 docstring bname = name;
1797 if (!label(0).empty())
1798 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1800 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1802 odocstringstream ls;
1803 if (runparams.flavor == OutputParams::XML) {
1804 ms << MTag("alt role='tex' ");
1805 // Workaround for db2latex: db2latex always includes equations with
1806 // \ensuremath{} or \begin{display}\end{display}
1807 // so we strip LyX' math environment
1808 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1809 InsetMathGrid::write(wi);
1810 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1815 InsetMathGrid::mathmlize(ms);
1818 ms << MTag("alt role='tex'");
1819 res = latex(ls, runparams);
1820 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1824 ms << from_ascii("<graphic fileref=\"eqn/");
1825 if (!label(0).empty())
1826 ms << sgml::cleanID(buffer(), runparams, label(0));
1828 ms << sgml::uniqueID(from_ascii("anon"));
1830 if (runparams.flavor == OutputParams::XML)
1831 ms << from_ascii("\"/>");
1833 ms << from_ascii("\">");
1835 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1837 return ms.line() + res;
1841 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
1843 BufferParams::MathOutput mathtype = buffer().params().html_math_output;
1845 // FIXME Eventually we would like to do this inset by inset.
1847 case BufferParams::MathML: {
1848 if (getType() == hullSimple)
1849 xs << html::StartTag("math",
1850 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1852 xs << html::StartTag("math",
1853 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1854 MathStream ms(xs.os());
1855 InsetMathGrid::mathmlize(ms);
1856 xs << html::EndTag("math");
1859 case BufferParams::HTML: {
1860 string const tag = (getType() == hullSimple) ? "span" : "div";
1861 xs << html::StartTag(tag, "class='formula'", true);
1862 HtmlStream ms(xs.os());
1863 InsetMathGrid::htmlize(ms);
1864 xs << html::EndTag(tag);
1867 case BufferParams::Images: {
1868 reloadPreview(docit_, true);
1869 graphics::PreviewImage const * pimage = preview_->getPreviewImage(buffer());
1871 // FIXME Do we always have png?
1872 string const tag = (getType() == hullSimple) ? "span" : "div";
1873 FileName const & mathimg = pimage->filename();
1874 xs << html::StartTag(tag);
1875 xs << html::CompTag("img", "src=\"" + mathimg.onlyFileName() + "\"");
1876 xs << html::EndTag(tag);
1878 // add the file to the list of files to be exported
1879 op.exportdata->addExternalFile("xhtml", mathimg);
1882 LYXERR0("Unable to generate image. Falling through to LaTeX output.");
1884 case BufferParams::LaTeX: {
1885 string const tag = (getType() == hullSimple) ? "span" : "div";
1886 // FIXME Need to allow customization of wrapping tags here....
1887 docstring const latex = latexString(*this);
1888 xs << html::StartTag(tag) << latex << html::EndTag(tag);
1896 void InsetMathHull::tocString(odocstream & os) const
1898 plaintext(os, OutputParams(0));
1902 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1904 return from_ascii("context-math");
1908 void InsetMathHull::recordLocation(DocIterator const & di)