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"
25 #include "CutAndPaste.h"
27 #include "FuncRequest.h"
28 #include "FuncStatus.h"
29 #include "LaTeXFeatures.h"
31 #include "MacroTable.h"
32 #include "output_xhtml.h"
34 #include "TextPainter.h"
35 #include "TocBackend.h"
37 #include "insets/InsetLabel.h"
38 #include "insets/InsetRef.h"
39 #include "insets/RenderPreview.h"
41 #include "graphics/PreviewImage.h"
42 #include "graphics/PreviewLoader.h"
44 #include "frontends/Painter.h"
46 #include "support/lassert.h"
47 #include "support/debug.h"
48 #include "support/gettext.h"
49 #include "support/lstrings.h"
54 using namespace lyx::support;
58 using cap::grabAndEraseSelection;
62 int getCols(HullType type)
79 // returns position of first relation operator in the array
80 // used for "intelligent splitting"
81 size_t firstRelOp(MathData const & ar)
83 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
85 return it - ar.begin();
90 char const * star(bool numbered)
92 return numbered ? "" : "*";
96 } // end anon namespace
99 HullType hullType(docstring const & s)
101 if (s == "none") return hullNone;
102 if (s == "simple") return hullSimple;
103 if (s == "equation") return hullEquation;
104 if (s == "eqnarray") return hullEqnArray;
105 if (s == "align") return hullAlign;
106 if (s == "alignat") return hullAlignAt;
107 if (s == "xalignat") return hullXAlignAt;
108 if (s == "xxalignat") return hullXXAlignAt;
109 if (s == "multline") return hullMultline;
110 if (s == "gather") return hullGather;
111 if (s == "flalign") return hullFlAlign;
112 if (s == "regexp") return hullRegexp;
113 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
118 docstring hullName(HullType type)
121 case hullNone: return from_ascii("none");
122 case hullSimple: return from_ascii("simple");
123 case hullEquation: return from_ascii("equation");
124 case hullEqnArray: return from_ascii("eqnarray");
125 case hullAlign: return from_ascii("align");
126 case hullAlignAt: return from_ascii("alignat");
127 case hullXAlignAt: return from_ascii("xalignat");
128 case hullXXAlignAt: return from_ascii("xxalignat");
129 case hullMultline: return from_ascii("multline");
130 case hullGather: return from_ascii("gather");
131 case hullFlAlign: return from_ascii("flalign");
132 case hullRegexp: return from_ascii("regexp");
134 lyxerr << "unknown hull type '" << type << "'" << endl;
135 return from_ascii("none");
139 static InsetLabel * dummy_pointer = 0;
141 InsetMathHull::InsetMathHull(Buffer * buf)
142 : InsetMathGrid(buf, 1, 1), type_(hullNone), nonum_(1, false),
143 label_(1, dummy_pointer), preview_(new RenderPreview(this))
145 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
146 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
147 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
148 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
155 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
156 : InsetMathGrid(buf, getCols(type), 1), type_(type), nonum_(1, false),
157 label_(1, dummy_pointer), preview_(new RenderPreview(this))
165 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
171 InsetMathHull::~InsetMathHull()
173 for (size_t i = 0; i < label_.size(); ++i)
178 Inset * InsetMathHull::clone() const
180 return new InsetMathHull(*this);
184 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
188 InsetMathGrid::operator=(other);
190 nonum_ = other.nonum_;
191 buffer_ = other.buffer_;
192 for (size_t i = 0; i < label_.size(); ++i)
194 label_ = other.label_;
195 for (size_t i = 0; i != label_.size(); ++i) {
197 label_[i] = new InsetLabel(*label_[i]);
199 preview_.reset(new RenderPreview(*other.preview_, this));
205 void InsetMathHull::setBuffer(Buffer & buffer)
207 InsetMathGrid::setBuffer(buffer);
209 for (size_t i = 0; i != label_.size(); ++i) {
211 label_[i]->setBuffer(buffer);
216 void InsetMathHull::updateLabels(ParIterator const & it, UpdateType utype)
219 //FIXME: buffer_ should be set at creation for this inset! Problem is
220 // This inset is created at too many places (see Parser::parse1() in
224 for (size_t i = 0; i != label_.size(); ++i) {
226 label_[i]->updateLabels(it, utype);
229 InsetMathGrid::updateLabels(it, utype);
233 void InsetMathHull::addToToc(DocIterator const & pit)
236 //FIXME: buffer_ should be set at creation for this inset! Problem is
237 // This inset is created at too many places (see Parser::parse1() in
242 Toc & toc = buffer().tocBackend().toc("equation");
244 for (row_type row = 0; row != nrows(); ++row) {
248 label_[row]->addToToc(pit);
249 toc.push_back(TocItem(pit, 0, nicelabel(row)));
254 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
260 return InsetMathNest::editXY(cur, x, y);
264 InsetMath::mode_type InsetMathHull::currentMode() const
266 if (type_ == hullNone)
267 return UNDECIDED_MODE;
268 // definitely math mode ...
273 bool InsetMathHull::idxFirst(Cursor & cur) const
281 bool InsetMathHull::idxLast(Cursor & cur) const
283 cur.idx() = nargs() - 1;
284 cur.pos() = cur.lastpos();
289 char InsetMathHull::defaultColAlign(col_type col)
291 if (type_ == hullEqnArray)
293 if (type_ == hullGather)
295 if (type_ >= hullAlign)
296 return "rl"[col & 1];
301 int InsetMathHull::defaultColSpace(col_type col)
303 if (type_ == hullAlign || type_ == hullAlignAt)
305 if (type_ == hullXAlignAt)
306 return (col & 1) ? 20 : 0;
307 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
308 return (col & 1) ? 40 : 0;
313 docstring InsetMathHull::standardFont() const
315 const char *font_name;
318 font_name = "texttt";
321 font_name = "lyxnochange";
324 font_name = "mathnormal";
326 return from_ascii(font_name);
330 bool InsetMathHull::previewState(BufferView * bv) const
332 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
333 graphics::PreviewImage const * pimage =
334 preview_->getPreviewImage(bv->buffer());
335 return pimage && pimage->image();
341 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
343 if (previewState(mi.base.bv)) {
344 preview_->metrics(mi, dim);
345 // insert a one pixel gap in front of the formula
348 dim.des += displayMargin();
349 // Cache the inset dimension.
350 setDimCache(mi, dim);
354 FontSetChanger dummy1(mi.base, standardFont());
355 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
357 // let the cells adjust themselves
358 InsetMathGrid::metrics(mi, dim);
361 dim.asc += displayMargin();
362 dim.des += displayMargin();
365 if (numberedType()) {
366 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
368 for (row_type row = 0; row < nrows(); ++row)
369 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
375 // make it at least as high as the current font
378 math_font_max_dim(mi.base.font, asc, des);
379 dim.asc = max(dim.asc, asc);
380 dim.des = max(dim.des, des);
381 // Cache the inset dimension.
382 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
383 setDimCache(mi, dim);
387 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
389 if (previewState(pi.base.bv))
390 return graphics::PreviewLoader::backgroundColor();
395 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
397 Dimension const dim = dimension(*pi.base.bv);
398 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
399 dim.asc + dim.des - 1, pi.backgroundColor(this));
403 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
405 use_preview_ = previewState(pi.base.bv);
407 if (type_ == hullRegexp) {
408 Dimension const dim = dimension(*pi.base.bv);
409 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
410 dim.width() - 2, dim.height() - 2, Color_regexpframe);
413 // one pixel gap in front
414 preview_->draw(pi, x + 1, y);
415 setPosCache(pi, x, y);
419 FontSetChanger dummy1(pi.base, standardFont());
420 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
421 InsetMathGrid::draw(pi, x + 1, y);
423 if (numberedType()) {
424 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
425 for (row_type row = 0; row < nrows(); ++row) {
426 int const yy = y + rowinfo_[row].offset_;
427 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
428 docstring const nl = nicelabel(row);
432 setPosCache(pi, x, y);
436 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
439 InsetMathGrid::metricsT(mi, dim);
442 WriteStream wi(os, false, true, WriteStream::wsDefault);
444 dim.wid = os.str().size();
451 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
454 InsetMathGrid::drawT(pain, x, y);
457 WriteStream wi(os, false, true, WriteStream::wsDefault);
459 pain.draw(x, y, os.str().c_str());
464 static docstring latexString(InsetMathHull const & inset)
467 // This has to be static, because a preview snippet or a math
468 // macro containing math in text mode (such as $\text{$\phi$}$ or
469 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
470 // first time as a whole, and the second time only the inner math.
471 // In this last case inset.buffer() would be invalid.
472 static Encoding const * encoding = 0;
473 if (inset.isBufferValid())
474 encoding = &(inset.buffer().params().encoding());
475 WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
481 void InsetMathHull::initUnicodeMath() const
483 // Trigger classification of the unicode symbols in this inset
484 docstring const dummy = latexString(*this);
488 void InsetMathHull::addPreview(DocIterator const & inset_pos,
489 graphics::PreviewLoader & /*ploader*/) const
491 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
492 preparePreview(inset_pos);
497 void InsetMathHull::preparePreview(DocIterator const & pos) const
499 Buffer const * buffer = pos.buffer();
501 // collect macros at this position
503 buffer->listMacroNames(macros);
504 MacroNameSet::iterator it = macros.begin();
505 MacroNameSet::iterator end = macros.end();
506 odocstringstream macro_preamble;
507 for (; it != end; ++it) {
508 MacroData const * data = buffer->getMacro(*it, pos, true);
510 data->write(macro_preamble, true);
511 macro_preamble << endl;
515 docstring const snippet = macro_preamble.str() + latexString(*this);
516 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
517 preview_->addPreview(snippet, *buffer);
521 void InsetMathHull::reloadPreview(DocIterator const & pos) const
524 preview_->startLoading(*pos.buffer());
528 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
530 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
532 cur.updateFlags(Update::Force);
538 docstring InsetMathHull::label(row_type row) const
540 LASSERT(row < nrows(), /**/);
541 if (InsetLabel * il = label_[row])
542 return il->screenLabel();
547 void InsetMathHull::label(row_type row, docstring const & label)
549 //lyxerr << "setting label '" << label << "' for row " << row << endl;
553 label_[row] = dummy_pointer;
554 // We need an update of the Buffer reference cache.
555 // This is achieved by updateLabels().
557 buffer().updateLabels();
560 label_[row]->updateCommand(label);
562 label_[row]->setParam("name", label);
566 InsetCommandParams p(LABEL_CODE);
568 label_[row] = new InsetLabel(buffer_, p);
570 label_[row]->setBuffer(buffer());
574 void InsetMathHull::numbered(row_type row, bool num)
577 if (nonum_[row] && label_[row]) {
581 // The buffer is set at the end of readInset.
582 // When parsing the inset, buffer_ is 0.
585 // We need an update of the Buffer reference cache.
586 // This is achieved by updateLabels().
587 buffer().updateLabels();
592 bool InsetMathHull::numbered(row_type row) const
598 bool InsetMathHull::ams() const
600 return type_ == hullAlign
601 || type_ == hullFlAlign
602 || type_ == hullMultline
603 || type_ == hullGather
604 || type_ == hullAlignAt
605 || type_ == hullXAlignAt
606 || type_ == hullXXAlignAt;
610 Inset::DisplayType InsetMathHull::display() const
612 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
617 bool InsetMathHull::numberedType() const
619 if (type_ == hullNone)
621 if (type_ == hullSimple)
623 if (type_ == hullXXAlignAt)
625 if (type_ == hullRegexp)
627 for (row_type row = 0; row < nrows(); ++row)
634 void InsetMathHull::validate(LaTeXFeatures & features) const
637 features.require("amsmath");
639 if (type_ == hullRegexp)
640 features.addPreambleSnippet(
641 "\\newcommand{\\regexp}[1]{\\fbox{\\texttt{#1}}}");
643 // Validation is necessary only if not using AMS math.
644 // To be safe, we will always run mathedvalidate.
645 //if (features.amsstyle)
648 //features.binom = true;
650 InsetMathGrid::validate(features);
654 void InsetMathHull::header_write(WriteStream & os) const
656 bool n = numberedType();
670 os << "\\begin{equation" << star(n) << "}\n";
680 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
685 os << "\\begin{" << hullName(type_) << star(n) << '}'
686 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
690 os << "\\begin{" << hullName(type_) << '}'
691 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
699 os << "\\begin{unknown" << star(n) << '}';
705 void InsetMathHull::footer_write(WriteStream & os) const
707 bool n = numberedType();
720 os << "\\end{equation" << star(n) << "}\n";
732 os << "\\end{" << hullName(type_) << star(n) << "}\n";
736 os << "\\end{" << hullName(type_) << "}\n";
744 os << "\\end{unknown" << star(n) << '}';
750 bool InsetMathHull::rowChangeOK() const
753 type_ == hullEqnArray || type_ == hullAlign ||
754 type_ == hullFlAlign || type_ == hullAlignAt ||
755 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
756 type_ == hullGather || type_ == hullMultline;
760 bool InsetMathHull::colChangeOK() const
763 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
764 type_ == hullXAlignAt || type_ == hullXXAlignAt;
768 void InsetMathHull::addRow(row_type row)
773 bool numbered = numberedType();
775 if (type_ == hullMultline) {
776 if (row + 1 == nrows()) {
783 nonum_.insert(nonum_.begin() + row + 1, !numbered);
784 label_.insert(label_.begin() + row + 1, dummy_pointer);
787 InsetMathGrid::addRow(row);
791 void InsetMathHull::swapRow(row_type row)
795 if (row + 1 == nrows())
797 // gcc implements the standard std::vector<bool> which is *not* a container:
798 // http://www.gotw.ca/publications/N1185.pdf
799 // As a results, it doesn't like this:
800 // swap(nonum_[row], nonum_[row + 1]);
801 // so we do it manually:
802 bool const b = nonum_[row];
803 nonum_[row] = nonum_[row + 1];
805 swap(label_[row], label_[row + 1]);
806 InsetMathGrid::swapRow(row);
810 void InsetMathHull::delRow(row_type row)
812 if (nrows() <= 1 || !rowChangeOK())
814 if (row + 1 == nrows() && type_ == hullMultline) {
815 bool const b = nonum_[row - 1];
816 nonum_[row - 1] = nonum_[row];
818 swap(label_[row - 1], label_[row]);
819 InsetMathGrid::delRow(row);
822 InsetMathGrid::delRow(row);
823 // The last dummy row has no number info nor a label.
824 // Test nrows() + 1 because we have already erased the row.
825 if (row == nrows() + 1)
827 nonum_.erase(nonum_.begin() + row);
829 label_.erase(label_.begin() + row);
833 void InsetMathHull::addCol(col_type col)
837 InsetMathGrid::addCol(col);
841 void InsetMathHull::delCol(col_type col)
843 if (ncols() <= 1 || !colChangeOK())
845 InsetMathGrid::delCol(col);
849 docstring InsetMathHull::nicelabel(row_type row) const
854 return from_ascii("(#)");
855 return '(' + label_[row]->screenLabel() + from_ascii(", #)");
859 void InsetMathHull::glueall()
862 for (idx_type i = 0; i < nargs(); ++i)
864 *this = InsetMathHull(buffer_, hullSimple);
870 void InsetMathHull::splitTo2Cols()
872 LASSERT(ncols() == 1, /**/);
873 InsetMathGrid::addCol(1);
874 for (row_type row = 0; row < nrows(); ++row) {
875 idx_type const i = 2 * row;
876 pos_type pos = firstRelOp(cell(i));
877 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
878 cell(i).erase(pos, cell(i).size());
883 void InsetMathHull::splitTo3Cols()
885 LASSERT(ncols() < 3, /**/);
888 InsetMathGrid::addCol(2);
889 for (row_type row = 0; row < nrows(); ++row) {
890 idx_type const i = 3 * row + 1;
891 if (cell(i).size()) {
892 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
893 cell(i).erase(1, cell(i).size());
899 void InsetMathHull::changeCols(col_type cols)
903 else if (ncols() < cols) {
909 while (ncols() < cols)
910 InsetMathGrid::addCol(ncols());
916 for (row_type row = 0; row < nrows(); ++row) {
917 idx_type const i = row * ncols();
918 for (col_type col = cols; col < ncols(); ++col) {
919 cell(i + cols - 1).append(cell(i + col));
923 while (ncols() > cols) {
924 InsetMathGrid::delCol(ncols() - 1);
929 HullType InsetMathHull::getType() const
935 void InsetMathHull::setType(HullType type)
942 void InsetMathHull::mutate(HullType newtype)
944 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
946 // we try to move along the chain
947 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
949 // +-------------------------------------+
950 // we use eqnarray as intermediate type for mutations that are not
951 // directly supported because it handles labels and numbering for
954 if (newtype == type_) {
958 else if (newtype < hullNone) {
963 else if (type_ == hullNone) {
969 else if (type_ == hullSimple) {
970 if (newtype == hullNone) {
974 setType(hullEquation);
980 else if (type_ == hullEquation) {
981 if (newtype < type_) {
985 } else if (newtype == hullEqnArray) {
986 // split it "nicely" on the first relop
988 setType(hullEqnArray);
989 } else if (newtype == hullMultline || newtype == hullGather) {
999 else if (type_ == hullEqnArray) {
1000 if (newtype < type_) {
1001 // set correct (no)numbering
1003 for (row_type row = 0; row < nrows(); ++row) {
1010 // set first non-empty label
1011 for (row_type row = 0; row < nrows(); ++row) {
1013 label_[0] = label_[row];
1020 } else { // align & Co.
1027 else if (type_ == hullAlign || type_ == hullAlignAt ||
1028 type_ == hullXAlignAt || type_ == hullFlAlign) {
1029 if (newtype < hullAlign) {
1031 setType(hullEqnArray);
1033 } else if (newtype == hullGather || newtype == hullMultline) {
1036 } else if (newtype == hullXXAlignAt) {
1037 for (row_type row = 0; row < nrows(); ++row)
1038 numbered(row, false);
1045 else if (type_ == hullXXAlignAt) {
1046 for (row_type row = 0; row < nrows(); ++row)
1047 numbered(row, false);
1048 if (newtype < hullAlign) {
1050 setType(hullEqnArray);
1052 } else if (newtype == hullGather || newtype == hullMultline) {
1060 else if (type_ == hullMultline || type_ == hullGather) {
1061 if (newtype == hullGather || newtype == hullMultline)
1063 else if (newtype == hullAlign || newtype == hullFlAlign ||
1064 newtype == hullAlignAt || newtype == hullXAlignAt) {
1067 } else if (newtype == hullXXAlignAt) {
1069 for (row_type row = 0; row < nrows(); ++row)
1070 numbered(row, false);
1074 setType(hullEqnArray);
1080 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1081 << "' to '" << to_utf8(hullName(newtype))
1082 << "' not implemented" << endl;
1087 docstring InsetMathHull::eolString(row_type row, bool fragile) const
1090 if (numberedType()) {
1091 if (label_[row] && !nonum_[row])
1093 escape(label_[row]->getParam("name")) + '}';
1094 if (nonum_[row] && (type_ != hullMultline))
1095 res += "\\nonumber ";
1097 return res + InsetMathGrid::eolString(row, fragile);
1101 void InsetMathHull::write(WriteStream & os) const
1103 ModeSpecifier specifier(os, MATH_MODE);
1105 InsetMathGrid::write(os);
1110 void InsetMathHull::normalize(NormalStream & os) const
1112 os << "[formula " << hullName(type_) << ' ';
1113 InsetMathGrid::normalize(os);
1118 void InsetMathHull::mathmlize(MathStream & os) const
1120 InsetMathGrid::mathmlize(os);
1124 void InsetMathHull::infoize(odocstream & os) const
1126 os << "Type: " << hullName(type_);
1130 void InsetMathHull::check() const
1132 LASSERT(nonum_.size() == nrows(), /**/);
1133 LASSERT(label_.size() == nrows(), /**/);
1137 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1141 idocstringstream iss(func.argument());
1142 iss >> dlang >> extra;
1144 extra = from_ascii("noextra");
1145 string const lang = to_ascii(dlang);
1147 // FIXME: temporarily disabled
1148 //if (cur.selection()) {
1151 // lyxerr << "use selection: " << ar << endl;
1152 // insert(pipeThroughExtern(lang, extra, ar));
1157 eq.push_back(MathAtom(new InsetMathChar('=')));
1159 // go to first item in line
1160 cur.idx() -= cur.idx() % ncols();
1163 if (getType() == hullSimple) {
1164 size_type pos = cur.cell().find_last(eq);
1166 if (cur.inMathed() && cur.selection()) {
1167 asArray(grabAndEraseSelection(cur), ar);
1168 } else if (pos == cur.cell().size()) {
1170 lyxerr << "use whole cell: " << ar << endl;
1172 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1173 lyxerr << "use partial cell form pos: " << pos << endl;
1175 cur.cell().append(eq);
1176 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1177 cur.pos() = cur.lastpos();
1181 if (getType() == hullEquation) {
1182 lyxerr << "use equation inset" << endl;
1183 mutate(hullEqnArray);
1184 MathData & ar = cur.cell();
1185 lyxerr << "use cell: " << ar << endl;
1189 cur.cell() = pipeThroughExtern(lang, extra, ar);
1190 // move to end of line
1191 cur.pos() = cur.lastpos();
1196 lyxerr << "use eqnarray" << endl;
1197 cur.idx() += 2 - cur.idx() % ncols();
1199 MathData ar = cur.cell();
1200 lyxerr << "use cell: " << ar << endl;
1201 // FIXME: temporarily disabled
1207 cur.cell() = pipeThroughExtern(lang, extra, ar);
1208 cur.pos() = cur.lastpos();
1213 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1215 //lyxerr << "action: " << cmd.action << endl;
1216 switch (cmd.action) {
1218 case LFUN_FINISHED_BACKWARD:
1219 case LFUN_FINISHED_FORWARD:
1220 case LFUN_FINISHED_RIGHT:
1221 case LFUN_FINISHED_LEFT:
1222 //lyxerr << "action: " << cmd.action << endl;
1223 InsetMathGrid::doDispatch(cur, cmd);
1227 case LFUN_BREAK_PARAGRAPH:
1228 // just swallow this
1231 case LFUN_NEWLINE_INSERT:
1232 // some magic for the common case
1233 if (type_ == hullSimple || type_ == hullEquation) {
1234 cur.recordUndoInset();
1236 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1237 mutate(align ? hullAlign : hullEqnArray);
1238 cur.idx() = nrows() * ncols() - 1;
1239 cur.pos() = cur.lastpos();
1241 InsetMathGrid::doDispatch(cur, cmd);
1244 case LFUN_MATH_NUMBER_TOGGLE: {
1245 //lyxerr << "toggling all numbers" << endl;
1246 cur.recordUndoInset();
1247 bool old = numberedType();
1248 if (type_ == hullMultline)
1249 numbered(nrows() - 1, !old);
1251 for (row_type row = 0; row < nrows(); ++row)
1252 numbered(row, !old);
1254 cur.message(old ? _("No number") : _("Number"));
1258 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1259 cur.recordUndoInset();
1260 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1261 bool old = numbered(r);
1262 cur.message(old ? _("No number") : _("Number"));
1267 case LFUN_LABEL_INSERT: {
1268 cur.recordUndoInset();
1269 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1270 docstring old_label = label(r);
1271 docstring const default_label = from_ascii(
1272 (lyxrc.label_init_length >= 0) ? "eq:" : "");
1273 if (old_label.empty())
1274 old_label = default_label;
1276 InsetCommandParams p(LABEL_CODE);
1277 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1278 string const data = InsetCommand::params2string("label", p);
1280 if (cmd.argument().empty())
1281 cur.bv().showDialog("label", data);
1283 FuncRequest fr(LFUN_INSET_INSERT, data);
1289 case LFUN_LABEL_COPY_AS_REF: {
1291 if (cmd.argument().empty() && &cur.inset() == this)
1292 // if there is no argument and we're inside math, we retrieve
1293 // the row number from the cursor position.
1294 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1296 // if there is an argument, find the corresponding label, else
1297 // check whether there is at least one label.
1298 for (row = 0; row != nrows(); ++row)
1299 if (!nonum_[row] && label_[row]
1300 && (cmd.argument().empty() || label(row) == cmd.argument()))
1307 InsetCommandParams p(REF_CODE, "ref");
1308 p["reference"] = label(row);
1309 cap::clearSelection();
1310 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1314 case LFUN_WORD_DELETE_FORWARD:
1315 case LFUN_CHAR_DELETE_FORWARD:
1316 if (col(cur.idx()) + 1 == ncols()
1317 && cur.pos() == cur.lastpos()
1318 && !cur.selection()) {
1319 if (!label(row(cur.idx())).empty()) {
1320 cur.recordUndoInset();
1321 label(row(cur.idx()), docstring());
1322 } else if (numbered(row(cur.idx()))) {
1323 cur.recordUndoInset();
1324 numbered(row(cur.idx()), false);
1326 InsetMathGrid::doDispatch(cur, cmd);
1330 InsetMathGrid::doDispatch(cur, cmd);
1335 case LFUN_INSET_INSERT: {
1336 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1337 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1338 string const name = cmd.getArg(0);
1339 if (name == "label") {
1340 InsetCommandParams p(LABEL_CODE);
1341 InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1342 docstring str = p["name"];
1343 cur.recordUndoInset();
1344 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1348 docstring old = label(r);
1351 // The label will take care of the reference update.
1355 // Newly created inset so initialize it.
1356 label_[r]->initView();
1361 InsetMathGrid::doDispatch(cur, cmd);
1365 case LFUN_MATH_EXTERN:
1366 cur.recordUndoInset();
1370 case LFUN_MATH_MUTATE: {
1371 cur.recordUndoInset();
1372 row_type row = cur.row();
1373 col_type col = cur.col();
1374 mutate(hullType(cmd.argument()));
1375 cur.idx() = row * ncols() + col;
1376 if (cur.idx() > cur.lastidx()) {
1377 cur.idx() = cur.lastidx();
1378 cur.pos() = cur.lastpos();
1380 if (cur.pos() > cur.lastpos())
1381 cur.pos() = cur.lastpos();
1383 // FIXME: find some more clever handling of the selection,
1384 // i.e. preserve it.
1385 cur.clearSelection();
1386 //cur.dispatched(FINISHED);
1390 case LFUN_MATH_DISPLAY: {
1391 cur.recordUndoInset();
1392 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1394 cur.pos() = cur.lastpos();
1395 //cur.dispatched(FINISHED);
1400 InsetMathGrid::doDispatch(cur, cmd);
1406 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1407 FuncStatus & status) const
1409 switch (cmd.action) {
1410 case LFUN_FINISHED_BACKWARD:
1411 case LFUN_FINISHED_FORWARD:
1412 case LFUN_FINISHED_RIGHT:
1413 case LFUN_FINISHED_LEFT:
1416 case LFUN_NEWLINE_INSERT:
1417 case LFUN_MATH_EXTERN:
1418 case LFUN_MATH_DISPLAY:
1420 status.setEnabled(true);
1423 case LFUN_MATH_MUTATE: {
1424 HullType ht = hullType(cmd.argument());
1425 status.setOnOff(type_ == ht);
1426 status.setEnabled(true);
1430 case LFUN_MATH_NUMBER_TOGGLE:
1431 // FIXME: what is the right test, this or the one of
1433 status.setEnabled(display());
1434 status.setOnOff(numberedType());
1437 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1438 // FIXME: what is the right test, this or the one of
1440 bool const enable = (type_ == hullMultline)
1441 ? (nrows() - 1 == cur.row())
1442 : display() != Inline && nrows() > 1;
1443 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1444 status.setEnabled(enable);
1445 status.setOnOff(enable && numbered(r));
1449 case LFUN_LABEL_INSERT:
1450 status.setEnabled(type_ != hullSimple);
1453 case LFUN_LABEL_COPY_AS_REF: {
1454 bool enabled = false;
1456 if (cmd.argument().empty() && &cur.inset() == this) {
1457 // if there is no argument and we're inside math, we retrieve
1458 // the row number from the cursor position.
1459 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1460 enabled = numberedType() && label_[row] && !nonum_[row];
1462 // if there is an argument, find the corresponding label, else
1463 // check whether there is at least one label.
1464 for (row_type row = 0; row != nrows(); ++row) {
1465 if (!nonum_[row] && label_[row] &&
1466 (cmd.argument().empty() || label(row) == cmd.argument())) {
1472 status.setEnabled(enabled);
1476 case LFUN_INSET_INSERT:
1477 if (cmd.getArg(0) == "label") {
1478 status.setEnabled(type_ != hullSimple);
1481 return InsetMathGrid::getStatus(cur, cmd, status);
1483 case LFUN_TABULAR_FEATURE: {
1484 istringstream is(to_utf8(cmd.argument()));
1488 && (s == "append-row"
1489 || s == "delete-row"
1490 || s == "copy-row")) {
1491 status.message(bformat(
1492 from_utf8(N_("Can't change number of rows in '%1$s'")),
1494 status.setEnabled(false);
1498 && (s == "append-column"
1499 || s == "delete-column"
1500 || s == "copy-column")) {
1501 status.message(bformat(
1502 from_utf8(N_("Can't change number of columns in '%1$s'")),
1504 status.setEnabled(false);
1507 if ((type_ == hullSimple
1508 || type_ == hullEquation
1509 || type_ == hullNone) &&
1510 (s == "add-hline-above" || s == "add-hline-below")) {
1511 status.message(bformat(
1512 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1514 status.setEnabled(false);
1517 if (s == "add-vline-left" || s == "add-vline-right") {
1518 status.message(bformat(
1519 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1521 status.setEnabled(false);
1524 if (s == "valign-top" || s == "valign-middle"
1525 || s == "valign-bottom" || s == "align-left"
1526 || s == "align-center" || s == "align-right") {
1527 status.setEnabled(false);
1530 return InsetMathGrid::getStatus(cur, cmd, status);
1534 return InsetMathGrid::getStatus(cur, cmd, status);
1537 // This cannot really happen, but inserted to shut-up gcc
1538 return InsetMathGrid::getStatus(cur, cmd, status);
1542 /////////////////////////////////////////////////////////////////////
1546 // simply scrap this function if you want
1547 void InsetMathHull::mutateToText()
1550 // translate to latex
1552 latex(os, false, false);
1553 string str = os.str();
1556 Text * lt = view_->cursor().innerText();
1557 string::const_iterator cit = str.begin();
1558 string::const_iterator end = str.end();
1559 for (; cit != end; ++cit)
1560 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1563 //dispatch(LFUN_ESCAPE);
1568 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1569 docstring const & font)
1571 // this whole function is a hack and won't work for incremental font
1574 if (cur.inset().asInsetMath()->name() == font)
1575 cur.handleFont(to_utf8(font));
1577 cur.handleNest(createInsetMath(font, cur.buffer()));
1583 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1588 font.fromString(to_utf8(arg), b);
1589 if (font.fontInfo().color() != Color_inherit) {
1590 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1591 cur.handleNest(at, 0);
1596 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1599 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1600 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1601 enter_front ? idxFirst(cur) : idxLast(cur);
1602 // The inset formula dimension is not necessarily the same as the
1603 // one of the instant preview image, so we have to indicate to the
1604 // BufferView that a metrics update is needed.
1605 cur.updateFlags(Update::Force);
1609 void InsetMathHull::revealCodes(Cursor & cur) const
1611 if (!cur.inMathed())
1613 odocstringstream os;
1615 cur.message(os.str());
1617 // write something to the minibuffer
1618 // translate to latex
1622 string str = os.str();
1624 string::size_type pos = 0;
1626 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1629 else if (*it == '\0') {
1631 pos = it - str.begin();
1637 res = res.substr(pos - 30);
1638 if (res.size() > 60)
1639 res = res.substr(0, 60);
1645 /////////////////////////////////////////////////////////////////////
1649 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1652 // FIXME: completely broken
1653 static InsetMathHull * lastformula = 0;
1654 static CursorBase current = DocIterator(ibegin(nucleus()));
1656 static string laststr;
1658 if (lastformula != this || laststr != str) {
1659 //lyxerr << "reset lastformula to " << this << endl;
1662 current = ibegin(nucleus());
1664 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1668 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1670 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1671 CursorSlice & top = it.back();
1672 MathData const & a = top.asInsetMath()->cell(top.idx_);
1673 if (a.matchpart(ar, top.pos_)) {
1674 bv->cursor().setSelection(it, ar.size());
1676 top.pos_ += ar.size();
1682 //lyxerr << "not found!" << endl;
1689 void InsetMathHull::write(ostream & os) const
1691 odocstringstream oss;
1692 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1695 os << to_utf8(oss.str());
1699 void InsetMathHull::read(Lexer & lex)
1702 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1703 operator=(*at->asHullInset());
1707 bool InsetMathHull::readQuiet(Lexer & lex)
1710 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1712 operator=(*at->asHullInset());
1717 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1719 if (0 && display()) {
1723 TextPainter tpain(dim.width(), dim.height());
1724 drawT(tpain, 0, dim.ascent());
1726 // reset metrics cache to "real" values
1728 return tpain.textheight();
1730 odocstringstream oss;
1731 Encoding const * const enc = encodings.fromLyXName("utf8");
1732 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1734 if (type_ == hullRegexp)
1738 docstring const str = oss.str();
1745 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1750 if (getType() == hullSimple)
1751 name = from_ascii("inlineequation");
1753 name = from_ascii("informalequation");
1755 docstring bname = name;
1756 if (!label(0).empty())
1757 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1759 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1761 odocstringstream ls;
1762 if (runparams.flavor == OutputParams::XML) {
1763 ms << MTag("alt role='tex' ");
1764 // Workaround for db2latex: db2latex always includes equations with
1765 // \ensuremath{} or \begin{display}\end{display}
1766 // so we strip LyX' math environment
1767 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1768 InsetMathGrid::write(wi);
1769 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1774 InsetMathGrid::mathmlize(ms);
1777 ms << MTag("alt role='tex'");
1778 res = latex(ls, runparams);
1779 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1783 ms << from_ascii("<graphic fileref=\"eqn/");
1784 if (!label(0).empty())
1785 ms << sgml::cleanID(buffer(), runparams, label(0));
1787 ms << sgml::uniqueID(from_ascii("anon"));
1789 if (runparams.flavor == OutputParams::XML)
1790 ms << from_ascii("\"/>");
1792 ms << from_ascii("\">");
1794 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1796 return ms.line() + res;
1800 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const &) const
1802 if (getType() == hullSimple)
1803 xs << html::StartTag("math", "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1805 xs << html::StartTag("math",
1806 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1807 MathStream ms(xs.os());
1808 InsetMathGrid::mathmlize(ms);
1809 xs << html::EndTag("math");
1814 void InsetMathHull::tocString(odocstream & os) const
1816 plaintext(os, OutputParams(0));
1820 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1822 return from_ascii("context-math");