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"
43 #include "frontends/Painter.h"
45 #include "support/lassert.h"
46 #include "support/debug.h"
47 #include "support/gettext.h"
48 #include "support/lstrings.h"
53 using namespace lyx::support;
57 using cap::grabAndEraseSelection;
61 int getCols(HullType type)
78 // returns position of first relation operator in the array
79 // used for "intelligent splitting"
80 size_t firstRelOp(MathData const & ar)
82 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
84 return it - ar.begin();
89 char const * star(bool numbered)
91 return numbered ? "" : "*";
95 } // end anon namespace
98 HullType hullType(docstring const & s)
100 if (s == "none") return hullNone;
101 if (s == "simple") return hullSimple;
102 if (s == "equation") return hullEquation;
103 if (s == "eqnarray") return hullEqnArray;
104 if (s == "align") return hullAlign;
105 if (s == "alignat") return hullAlignAt;
106 if (s == "xalignat") return hullXAlignAt;
107 if (s == "xxalignat") return hullXXAlignAt;
108 if (s == "multline") return hullMultline;
109 if (s == "gather") return hullGather;
110 if (s == "flalign") return hullFlAlign;
111 if (s == "regexp") return hullRegexp;
112 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
117 docstring hullName(HullType type)
120 case hullNone: return from_ascii("none");
121 case hullSimple: return from_ascii("simple");
122 case hullEquation: return from_ascii("equation");
123 case hullEqnArray: return from_ascii("eqnarray");
124 case hullAlign: return from_ascii("align");
125 case hullAlignAt: return from_ascii("alignat");
126 case hullXAlignAt: return from_ascii("xalignat");
127 case hullXXAlignAt: return from_ascii("xxalignat");
128 case hullMultline: return from_ascii("multline");
129 case hullGather: return from_ascii("gather");
130 case hullFlAlign: return from_ascii("flalign");
131 case hullRegexp: return from_ascii("regexp");
133 lyxerr << "unknown hull type '" << type << "'" << endl;
134 return from_ascii("none");
138 static InsetLabel * dummy_pointer = 0;
140 InsetMathHull::InsetMathHull(Buffer * buf)
141 : InsetMathGrid(buf, 1, 1), type_(hullNone), nonum_(1, false),
142 label_(1, dummy_pointer), preview_(new RenderPreview(this))
144 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
145 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
146 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
147 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
154 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
155 : InsetMathGrid(buf, getCols(type), 1), type_(type), nonum_(1, false),
156 label_(1, dummy_pointer), preview_(new RenderPreview(this))
164 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
170 InsetMathHull::~InsetMathHull()
172 for (size_t i = 0; i < label_.size(); ++i)
177 Inset * InsetMathHull::clone() const
179 return new InsetMathHull(*this);
183 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
187 InsetMathGrid::operator=(other);
189 nonum_ = other.nonum_;
190 buffer_ = other.buffer_;
191 for (size_t i = 0; i < label_.size(); ++i)
193 label_ = other.label_;
194 for (size_t i = 0; i != label_.size(); ++i) {
196 label_[i] = new InsetLabel(*label_[i]);
198 preview_.reset(new RenderPreview(*other.preview_, this));
204 void InsetMathHull::setBuffer(Buffer & buffer)
206 InsetMathGrid::setBuffer(buffer);
208 for (size_t i = 0; i != label_.size(); ++i) {
210 label_[i]->setBuffer(buffer);
215 void InsetMathHull::updateLabels(ParIterator const & it, bool out)
218 //FIXME: buffer_ should be set at creation for this inset! Problem is
219 // This inset is created at too many places (see Parser::parse1() in
223 for (size_t i = 0; i != label_.size(); ++i) {
225 label_[i]->updateLabels(it, out);
230 void InsetMathHull::addToToc(DocIterator const & pit)
233 //FIXME: buffer_ should be set at creation for this inset! Problem is
234 // This inset is created at too many places (see Parser::parse1() in
239 Toc & toc = buffer().tocBackend().toc("equation");
241 for (row_type row = 0; row != nrows(); ++row) {
245 label_[row]->addToToc(pit);
246 toc.push_back(TocItem(pit, 0, nicelabel(row)));
251 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
257 return InsetMathNest::editXY(cur, x, y);
261 InsetMath::mode_type InsetMathHull::currentMode() const
263 if (type_ == hullNone)
264 return UNDECIDED_MODE;
265 // definitely math mode ...
270 bool InsetMathHull::idxFirst(Cursor & cur) const
278 bool InsetMathHull::idxLast(Cursor & cur) const
280 cur.idx() = nargs() - 1;
281 cur.pos() = cur.lastpos();
286 char InsetMathHull::defaultColAlign(col_type col)
288 if (type_ == hullEqnArray)
290 if (type_ == hullGather)
292 if (type_ >= hullAlign)
293 return "rl"[col & 1];
298 int InsetMathHull::defaultColSpace(col_type col)
300 if (type_ == hullAlign || type_ == hullAlignAt)
302 if (type_ == hullXAlignAt)
303 return (col & 1) ? 20 : 0;
304 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
305 return (col & 1) ? 40 : 0;
310 docstring InsetMathHull::standardFont() const
312 return from_ascii(type_ == hullNone ? "lyxnochange" : "mathnormal");
316 bool InsetMathHull::previewState(BufferView * bv) const
318 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
319 graphics::PreviewImage const * pimage =
320 preview_->getPreviewImage(bv->buffer());
321 return pimage && pimage->image();
327 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
329 if (previewState(mi.base.bv)) {
330 preview_->metrics(mi, dim);
331 // insert a one pixel gap in front of the formula
334 dim.des += displayMargin();
335 // Cache the inset dimension.
336 setDimCache(mi, dim);
340 FontSetChanger dummy1(mi.base, standardFont());
341 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
343 // let the cells adjust themselves
344 InsetMathGrid::metrics(mi, dim);
347 dim.asc += displayMargin();
348 dim.des += displayMargin();
351 if (numberedType()) {
352 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
354 for (row_type row = 0; row < nrows(); ++row)
355 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
361 // make it at least as high as the current font
364 math_font_max_dim(mi.base.font, asc, des);
365 dim.asc = max(dim.asc, asc);
366 dim.des = max(dim.des, des);
367 // Cache the inset dimension.
368 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
369 setDimCache(mi, dim);
373 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
375 if (previewState(pi.base.bv))
376 return Color_background;
381 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
383 Dimension const dim = dimension(*pi.base.bv);
384 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
385 dim.asc + dim.des - 1, pi.backgroundColor(this));
389 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
391 use_preview_ = previewState(pi.base.bv);
394 // one pixel gap in front
395 preview_->draw(pi, x + 1, y);
396 setPosCache(pi, x, y);
400 FontSetChanger dummy1(pi.base, standardFont());
401 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
402 InsetMathGrid::draw(pi, x + 1, y);
404 if (numberedType()) {
405 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
406 for (row_type row = 0; row < nrows(); ++row) {
407 int const yy = y + rowinfo_[row].offset_;
408 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
409 docstring const nl = nicelabel(row);
413 setPosCache(pi, x, y);
417 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
420 InsetMathGrid::metricsT(mi, dim);
423 WriteStream wi(os, false, true, WriteStream::wsDefault);
425 dim.wid = os.str().size();
432 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
435 InsetMathGrid::drawT(pain, x, y);
438 WriteStream wi(os, false, true, WriteStream::wsDefault);
440 pain.draw(x, y, os.str().c_str());
445 static docstring latexString(InsetMathHull const & inset)
448 // This has to be static, because a preview snippet or a math
449 // macro containing math in text mode (such as $\text{$\phi$}$ or
450 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
451 // first time as a whole, and the second time only the inner math.
452 // In this last case inset.buffer() would be invalid.
453 static Encoding const * encoding = 0;
454 if (inset.isBufferValid())
455 encoding = &(inset.buffer().params().encoding());
456 WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
462 void InsetMathHull::initUnicodeMath() const
464 // Trigger classification of the unicode symbols in this inset
465 docstring const dummy = latexString(*this);
469 void InsetMathHull::addPreview(DocIterator const & inset_pos,
470 graphics::PreviewLoader & /*ploader*/) const
472 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
473 preparePreview(inset_pos);
478 void InsetMathHull::preparePreview(DocIterator const & pos) const
480 Buffer const * buffer = pos.buffer();
482 // collect macros at this position
484 buffer->listMacroNames(macros);
485 MacroNameSet::iterator it = macros.begin();
486 MacroNameSet::iterator end = macros.end();
487 odocstringstream macro_preamble;
488 for (; it != end; ++it) {
489 MacroData const * data = buffer->getMacro(*it, pos, true);
491 data->write(macro_preamble, true);
492 macro_preamble << endl;
496 docstring const snippet = macro_preamble.str() + latexString(*this);
497 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
498 preview_->addPreview(snippet, *buffer);
502 void InsetMathHull::reloadPreview(DocIterator const & pos) const
505 preview_->startLoading(*pos.buffer());
509 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
511 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
513 cur.updateFlags(Update::Force);
519 docstring InsetMathHull::label(row_type row) const
521 LASSERT(row < nrows(), /**/);
522 if (InsetLabel * il = label_[row])
523 return il->screenLabel();
528 void InsetMathHull::label(row_type row, docstring const & label)
530 //lyxerr << "setting label '" << label << "' for row " << row << endl;
534 label_[row] = dummy_pointer;
535 // We need an update of the Buffer reference cache.
536 // This is achieved by updateLabels().
538 buffer().updateLabels();
541 label_[row]->updateCommand(label);
543 label_[row]->setParam("name", label);
547 InsetCommandParams p(LABEL_CODE);
549 label_[row] = new InsetLabel(buffer_, p);
551 label_[row]->setBuffer(buffer());
555 void InsetMathHull::numbered(row_type row, bool num)
558 if (nonum_[row] && label_[row]) {
562 // The buffer is set at the end of readInset.
563 // When parsing the inset, buffer_ is 0.
566 // We need an update of the Buffer reference cache.
567 // This is achieved by updateLabels().
568 buffer().updateLabels();
573 bool InsetMathHull::numbered(row_type row) const
579 bool InsetMathHull::ams() const
581 return type_ == hullAlign
582 || type_ == hullFlAlign
583 || type_ == hullMultline
584 || type_ == hullGather
585 || type_ == hullAlignAt
586 || type_ == hullXAlignAt
587 || type_ == hullXXAlignAt;
591 Inset::DisplayType InsetMathHull::display() const
593 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
598 bool InsetMathHull::numberedType() const
600 if (type_ == hullNone)
602 if (type_ == hullSimple)
604 if (type_ == hullXXAlignAt)
606 if (type_ == hullRegexp)
608 for (row_type row = 0; row < nrows(); ++row)
615 void InsetMathHull::validate(LaTeXFeatures & features) const
618 features.require("amsmath");
620 // Validation is necessary only if not using AMS math.
621 // To be safe, we will always run mathedvalidate.
622 //if (features.amsstyle)
625 //features.binom = true;
627 InsetMathGrid::validate(features);
631 void InsetMathHull::header_write(WriteStream & os) const
633 bool n = numberedType();
647 os << "\\begin{equation" << star(n) << "}\n";
657 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
662 os << "\\begin{" << hullName(type_) << star(n) << '}'
663 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
667 os << "\\begin{" << hullName(type_) << '}'
668 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
676 os << "\\begin{unknown" << star(n) << '}';
682 void InsetMathHull::footer_write(WriteStream & os) const
684 bool n = numberedType();
697 os << "\\end{equation" << star(n) << "}\n";
709 os << "\\end{" << hullName(type_) << star(n) << "}\n";
713 os << "\\end{" << hullName(type_) << "}\n";
721 os << "\\end{unknown" << star(n) << '}';
727 bool InsetMathHull::rowChangeOK() const
730 type_ == hullEqnArray || type_ == hullAlign ||
731 type_ == hullFlAlign || type_ == hullAlignAt ||
732 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
733 type_ == hullGather || type_ == hullMultline;
737 bool InsetMathHull::colChangeOK() const
740 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
741 type_ == hullXAlignAt || type_ == hullXXAlignAt;
745 void InsetMathHull::addRow(row_type row)
750 bool numbered = numberedType();
752 if (type_ == hullMultline) {
753 if (row + 1 == nrows()) {
760 nonum_.insert(nonum_.begin() + row + 1, !numbered);
761 label_.insert(label_.begin() + row + 1, dummy_pointer);
764 InsetMathGrid::addRow(row);
768 void InsetMathHull::swapRow(row_type row)
772 if (row + 1 == nrows())
774 // gcc implements the standard std::vector<bool> which is *not* a container:
775 // http://www.gotw.ca/publications/N1185.pdf
776 // As a results, it doesn't like this:
777 // swap(nonum_[row], nonum_[row + 1]);
778 // so we do it manually:
779 bool const b = nonum_[row];
780 nonum_[row] = nonum_[row + 1];
782 swap(label_[row], label_[row + 1]);
783 InsetMathGrid::swapRow(row);
787 void InsetMathHull::delRow(row_type row)
789 if (nrows() <= 1 || !rowChangeOK())
791 if (row + 1 == nrows() && type_ == hullMultline) {
792 bool const b = nonum_[row - 1];
793 nonum_[row - 1] = nonum_[row];
795 swap(label_[row - 1], label_[row]);
796 InsetMathGrid::delRow(row);
799 InsetMathGrid::delRow(row);
800 // The last dummy row has no number info nor a label.
801 // Test nrows() + 1 because we have already erased the row.
802 if (row == nrows() + 1)
804 nonum_.erase(nonum_.begin() + row);
806 label_.erase(label_.begin() + row);
810 void InsetMathHull::addCol(col_type col)
814 InsetMathGrid::addCol(col);
818 void InsetMathHull::delCol(col_type col)
820 if (ncols() <= 1 || !colChangeOK())
822 InsetMathGrid::delCol(col);
826 docstring InsetMathHull::nicelabel(row_type row) const
831 return from_ascii("(#)");
832 return '(' + label_[row]->screenLabel() + from_ascii(", #)");
836 void InsetMathHull::glueall()
839 for (idx_type i = 0; i < nargs(); ++i)
841 *this = InsetMathHull(buffer_, hullSimple);
847 void InsetMathHull::splitTo2Cols()
849 LASSERT(ncols() == 1, /**/);
850 InsetMathGrid::addCol(1);
851 for (row_type row = 0; row < nrows(); ++row) {
852 idx_type const i = 2 * row;
853 pos_type pos = firstRelOp(cell(i));
854 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
855 cell(i).erase(pos, cell(i).size());
860 void InsetMathHull::splitTo3Cols()
862 LASSERT(ncols() < 3, /**/);
865 InsetMathGrid::addCol(2);
866 for (row_type row = 0; row < nrows(); ++row) {
867 idx_type const i = 3 * row + 1;
868 if (cell(i).size()) {
869 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
870 cell(i).erase(1, cell(i).size());
876 void InsetMathHull::changeCols(col_type cols)
880 else if (ncols() < cols) {
886 while (ncols() < cols)
887 InsetMathGrid::addCol(ncols());
893 for (row_type row = 0; row < nrows(); ++row) {
894 idx_type const i = row * ncols();
895 for (col_type col = cols; col < ncols(); ++col) {
896 cell(i + cols - 1).append(cell(i + col));
900 while (ncols() > cols) {
901 InsetMathGrid::delCol(ncols() - 1);
906 HullType InsetMathHull::getType() const
912 void InsetMathHull::setType(HullType type)
919 void InsetMathHull::mutate(HullType newtype)
921 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
923 // we try to move along the chain
924 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
926 // +-------------------------------------+
927 // we use eqnarray as intermediate type for mutations that are not
928 // directly supported because it handles labels and numbering for
931 if (newtype == type_) {
935 else if (newtype < hullNone) {
940 else if (type_ == hullNone) {
946 else if (type_ == hullSimple) {
947 if (newtype == hullNone) {
951 setType(hullEquation);
957 else if (type_ == hullEquation) {
958 if (newtype < type_) {
962 } else if (newtype == hullEqnArray) {
963 // split it "nicely" on the first relop
965 setType(hullEqnArray);
966 } else if (newtype == hullMultline || newtype == hullGather) {
976 else if (type_ == hullEqnArray) {
977 if (newtype < type_) {
978 // set correct (no)numbering
980 for (row_type row = 0; row < nrows(); ++row) {
987 // set first non-empty label
988 for (row_type row = 0; row < nrows(); ++row) {
990 label_[0] = label_[row];
997 } else { // align & Co.
1004 else if (type_ == hullAlign || type_ == hullAlignAt ||
1005 type_ == hullXAlignAt || type_ == hullFlAlign) {
1006 if (newtype < hullAlign) {
1008 setType(hullEqnArray);
1010 } else if (newtype == hullGather || newtype == hullMultline) {
1013 } else if (newtype == hullXXAlignAt) {
1014 for (row_type row = 0; row < nrows(); ++row)
1015 numbered(row, false);
1022 else if (type_ == hullXXAlignAt) {
1023 for (row_type row = 0; row < nrows(); ++row)
1024 numbered(row, false);
1025 if (newtype < hullAlign) {
1027 setType(hullEqnArray);
1029 } else if (newtype == hullGather || newtype == hullMultline) {
1037 else if (type_ == hullMultline || type_ == hullGather) {
1038 if (newtype == hullGather || newtype == hullMultline)
1040 else if (newtype == hullAlign || newtype == hullFlAlign ||
1041 newtype == hullAlignAt || newtype == hullXAlignAt) {
1044 } else if (newtype == hullXXAlignAt) {
1046 for (row_type row = 0; row < nrows(); ++row)
1047 numbered(row, false);
1051 setType(hullEqnArray);
1057 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1058 << "' to '" << to_utf8(hullName(newtype))
1059 << "' not implemented" << endl;
1064 docstring InsetMathHull::eolString(row_type row, bool fragile) const
1067 if (numberedType()) {
1068 if (label_[row] && !nonum_[row])
1069 res += "\\label{" + label_[row]->getParam("name") + '}';
1070 if (nonum_[row] && (type_ != hullMultline))
1071 res += "\\nonumber ";
1073 return res + InsetMathGrid::eolString(row, fragile);
1077 void InsetMathHull::write(WriteStream & os) const
1079 ModeSpecifier specifier(os, MATH_MODE);
1081 InsetMathGrid::write(os);
1086 void InsetMathHull::normalize(NormalStream & os) const
1088 os << "[formula " << hullName(type_) << ' ';
1089 InsetMathGrid::normalize(os);
1094 void InsetMathHull::mathmlize(MathStream & os) const
1096 InsetMathGrid::mathmlize(os);
1100 void InsetMathHull::infoize(odocstream & os) const
1102 os << "Type: " << hullName(type_);
1106 void InsetMathHull::check() const
1108 LASSERT(nonum_.size() == nrows(), /**/);
1109 LASSERT(label_.size() == nrows(), /**/);
1113 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1117 idocstringstream iss(func.argument());
1118 iss >> dlang >> extra;
1120 extra = from_ascii("noextra");
1121 string const lang = to_ascii(dlang);
1123 // FIXME: temporarily disabled
1124 //if (cur.selection()) {
1127 // lyxerr << "use selection: " << ar << endl;
1128 // insert(pipeThroughExtern(lang, extra, ar));
1133 eq.push_back(MathAtom(new InsetMathChar('=')));
1135 // go to first item in line
1136 cur.idx() -= cur.idx() % ncols();
1139 if (getType() == hullSimple) {
1140 size_type pos = cur.cell().find_last(eq);
1142 if (cur.inMathed() && cur.selection()) {
1143 asArray(grabAndEraseSelection(cur), ar);
1144 } else if (pos == cur.cell().size()) {
1146 lyxerr << "use whole cell: " << ar << endl;
1148 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1149 lyxerr << "use partial cell form pos: " << pos << endl;
1151 cur.cell().append(eq);
1152 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1153 cur.pos() = cur.lastpos();
1157 if (getType() == hullEquation) {
1158 lyxerr << "use equation inset" << endl;
1159 mutate(hullEqnArray);
1160 MathData & ar = cur.cell();
1161 lyxerr << "use cell: " << ar << endl;
1165 cur.cell() = pipeThroughExtern(lang, extra, ar);
1166 // move to end of line
1167 cur.pos() = cur.lastpos();
1172 lyxerr << "use eqnarray" << endl;
1173 cur.idx() += 2 - cur.idx() % ncols();
1175 MathData ar = cur.cell();
1176 lyxerr << "use cell: " << ar << endl;
1177 // FIXME: temporarily disabled
1183 cur.cell() = pipeThroughExtern(lang, extra, ar);
1184 cur.pos() = cur.lastpos();
1189 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1191 //lyxerr << "action: " << cmd.action << endl;
1192 switch (cmd.action) {
1194 case LFUN_FINISHED_BACKWARD:
1195 case LFUN_FINISHED_FORWARD:
1196 case LFUN_FINISHED_RIGHT:
1197 case LFUN_FINISHED_LEFT:
1198 //lyxerr << "action: " << cmd.action << endl;
1199 InsetMathGrid::doDispatch(cur, cmd);
1203 case LFUN_BREAK_PARAGRAPH:
1204 // just swallow this
1207 case LFUN_NEWLINE_INSERT:
1208 // some magic for the common case
1209 if (type_ == hullSimple || type_ == hullEquation) {
1210 cur.recordUndoInset();
1212 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1213 mutate(align ? hullAlign : hullEqnArray);
1214 cur.idx() = nrows() * ncols() - 1;
1215 cur.pos() = cur.lastpos();
1217 InsetMathGrid::doDispatch(cur, cmd);
1220 case LFUN_MATH_NUMBER_TOGGLE: {
1221 //lyxerr << "toggling all numbers" << endl;
1222 cur.recordUndoInset();
1223 bool old = numberedType();
1224 if (type_ == hullMultline)
1225 numbered(nrows() - 1, !old);
1227 for (row_type row = 0; row < nrows(); ++row)
1228 numbered(row, !old);
1230 cur.message(old ? _("No number") : _("Number"));
1234 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1235 cur.recordUndoInset();
1236 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1237 bool old = numbered(r);
1238 cur.message(old ? _("No number") : _("Number"));
1243 case LFUN_LABEL_INSERT: {
1244 cur.recordUndoInset();
1245 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1246 docstring old_label = label(r);
1247 docstring const default_label = from_ascii(
1248 (lyxrc.label_init_length >= 0) ? "eq:" : "");
1249 if (old_label.empty())
1250 old_label = default_label;
1252 InsetCommandParams p(LABEL_CODE);
1253 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1254 string const data = InsetCommand::params2string("label", p);
1256 if (cmd.argument().empty())
1257 cur.bv().showDialog("label", data);
1259 FuncRequest fr(LFUN_INSET_INSERT, data);
1265 case LFUN_LABEL_COPY_AS_REF: {
1267 if (cmd.argument().empty() && &cur.inset() == this)
1268 // if there is no argument and we're inside math, we retrieve
1269 // the row number from the cursor position.
1270 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1272 // if there is an argument, find the corresponding label, else
1273 // check whether there is at least one label.
1274 for (row = 0; row != nrows(); ++row)
1275 if (!nonum_[row] && label_[row]
1276 && (cmd.argument().empty() || label(row) == cmd.argument()))
1283 InsetCommandParams p(REF_CODE, "ref");
1284 p["reference"] = label(row);
1285 cap::clearSelection();
1286 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1290 case LFUN_WORD_DELETE_FORWARD:
1291 case LFUN_CHAR_DELETE_FORWARD:
1292 if (col(cur.idx()) + 1 == ncols()
1293 && cur.pos() == cur.lastpos()
1294 && !cur.selection()) {
1295 if (!label(row(cur.idx())).empty()) {
1296 cur.recordUndoInset();
1297 label(row(cur.idx()), docstring());
1298 } else if (numbered(row(cur.idx()))) {
1299 cur.recordUndoInset();
1300 numbered(row(cur.idx()), false);
1302 InsetMathGrid::doDispatch(cur, cmd);
1306 InsetMathGrid::doDispatch(cur, cmd);
1311 case LFUN_INSET_INSERT: {
1312 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1313 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1314 string const name = cmd.getArg(0);
1315 if (name == "label") {
1316 InsetCommandParams p(LABEL_CODE);
1317 InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1318 docstring str = p["name"];
1319 cur.recordUndoInset();
1320 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1324 docstring old = label(r);
1327 // The label will take care of the reference update.
1331 // Newly created inset so initialize it.
1332 label_[r]->initView();
1337 InsetMathGrid::doDispatch(cur, cmd);
1341 case LFUN_MATH_EXTERN:
1342 cur.recordUndoInset();
1346 case LFUN_MATH_MUTATE: {
1347 cur.recordUndoInset();
1348 row_type row = cur.row();
1349 col_type col = cur.col();
1350 mutate(hullType(cmd.argument()));
1351 cur.idx() = row * ncols() + col;
1352 if (cur.idx() > cur.lastidx()) {
1353 cur.idx() = cur.lastidx();
1354 cur.pos() = cur.lastpos();
1356 if (cur.pos() > cur.lastpos())
1357 cur.pos() = cur.lastpos();
1359 // FIXME: find some more clever handling of the selection,
1360 // i.e. preserve it.
1361 cur.clearSelection();
1362 //cur.dispatched(FINISHED);
1366 case LFUN_MATH_DISPLAY: {
1367 cur.recordUndoInset();
1368 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1370 cur.pos() = cur.lastpos();
1371 //cur.dispatched(FINISHED);
1376 InsetMathGrid::doDispatch(cur, cmd);
1382 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1383 FuncStatus & status) const
1385 switch (cmd.action) {
1386 case LFUN_FINISHED_BACKWARD:
1387 case LFUN_FINISHED_FORWARD:
1388 case LFUN_FINISHED_RIGHT:
1389 case LFUN_FINISHED_LEFT:
1392 case LFUN_NEWLINE_INSERT:
1393 case LFUN_MATH_EXTERN:
1394 case LFUN_MATH_DISPLAY:
1396 status.setEnabled(true);
1399 case LFUN_MATH_MUTATE: {
1400 HullType ht = hullType(cmd.argument());
1401 status.setOnOff(type_ == ht);
1402 status.setEnabled(true);
1406 case LFUN_MATH_NUMBER_TOGGLE:
1407 // FIXME: what is the right test, this or the one of
1409 status.setEnabled(display());
1410 status.setOnOff(numberedType());
1413 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1414 // FIXME: what is the right test, this or the one of
1416 bool const enable = (type_ == hullMultline)
1417 ? (nrows() - 1 == cur.row())
1418 : display() != Inline && nrows() > 1;
1419 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1420 status.setEnabled(enable);
1421 status.setOnOff(enable && numbered(r));
1425 case LFUN_LABEL_INSERT:
1426 status.setEnabled(type_ != hullSimple);
1429 case LFUN_LABEL_COPY_AS_REF: {
1430 bool enabled = false;
1432 if (cmd.argument().empty() && &cur.inset() == this) {
1433 // if there is no argument and we're inside math, we retrieve
1434 // the row number from the cursor position.
1435 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1436 enabled = numberedType() && label_[row] && !nonum_[row];
1438 // if there is an argument, find the corresponding label, else
1439 // check whether there is at least one label.
1440 for (row_type row = 0; row != nrows(); ++row) {
1441 if (!nonum_[row] && label_[row] &&
1442 (cmd.argument().empty() || label(row) == cmd.argument())) {
1448 status.setEnabled(enabled);
1452 case LFUN_INSET_INSERT:
1453 if (cmd.getArg(0) == "label") {
1454 status.setEnabled(type_ != hullSimple);
1457 return InsetMathGrid::getStatus(cur, cmd, status);
1459 case LFUN_TABULAR_FEATURE: {
1460 istringstream is(to_utf8(cmd.argument()));
1464 && (s == "append-row"
1465 || s == "delete-row"
1466 || s == "copy-row")) {
1467 status.message(bformat(
1468 from_utf8(N_("Can't change number of rows in '%1$s'")),
1470 status.setEnabled(false);
1474 && (s == "append-column"
1475 || s == "delete-column"
1476 || s == "copy-column")) {
1477 status.message(bformat(
1478 from_utf8(N_("Can't change number of columns in '%1$s'")),
1480 status.setEnabled(false);
1483 if ((type_ == hullSimple
1484 || type_ == hullEquation
1485 || type_ == hullNone) &&
1486 (s == "add-hline-above" || s == "add-hline-below")) {
1487 status.message(bformat(
1488 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1490 status.setEnabled(false);
1493 if (s == "add-vline-left" || s == "add-vline-right") {
1494 status.message(bformat(
1495 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1497 status.setEnabled(false);
1500 if (s == "valign-top" || s == "valign-middle"
1501 || s == "valign-bottom" || s == "align-left"
1502 || s == "align-center" || s == "align-right") {
1503 status.setEnabled(false);
1506 return InsetMathGrid::getStatus(cur, cmd, status);
1510 return InsetMathGrid::getStatus(cur, cmd, status);
1513 // This cannot really happen, but inserted to shut-up gcc
1514 return InsetMathGrid::getStatus(cur, cmd, status);
1518 /////////////////////////////////////////////////////////////////////
1522 // simply scrap this function if you want
1523 void InsetMathHull::mutateToText()
1526 // translate to latex
1528 latex(os, false, false);
1529 string str = os.str();
1532 Text * lt = view_->cursor().innerText();
1533 string::const_iterator cit = str.begin();
1534 string::const_iterator end = str.end();
1535 for (; cit != end; ++cit)
1536 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1539 //dispatch(LFUN_ESCAPE);
1544 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1545 docstring const & font)
1547 // this whole function is a hack and won't work for incremental font
1550 if (cur.inset().asInsetMath()->name() == font)
1551 cur.handleFont(to_utf8(font));
1553 cur.handleNest(createInsetMath(font, cur.buffer()));
1559 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1564 font.fromString(to_utf8(arg), b);
1565 if (font.fontInfo().color() != Color_inherit) {
1566 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1567 cur.handleNest(at, 0);
1572 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1575 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1576 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1577 enter_front ? idxFirst(cur) : idxLast(cur);
1578 // The inset formula dimension is not necessarily the same as the
1579 // one of the instant preview image, so we have to indicate to the
1580 // BufferView that a metrics update is needed.
1581 cur.updateFlags(Update::Force);
1585 void InsetMathHull::revealCodes(Cursor & cur) const
1587 if (!cur.inMathed())
1589 odocstringstream os;
1591 cur.message(os.str());
1593 // write something to the minibuffer
1594 // translate to latex
1598 string str = os.str();
1600 string::size_type pos = 0;
1602 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1605 else if (*it == '\0') {
1607 pos = it - str.begin();
1613 res = res.substr(pos - 30);
1614 if (res.size() > 60)
1615 res = res.substr(0, 60);
1621 /////////////////////////////////////////////////////////////////////
1625 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1628 // FIXME: completely broken
1629 static InsetMathHull * lastformula = 0;
1630 static CursorBase current = DocIterator(ibegin(nucleus()));
1632 static string laststr;
1634 if (lastformula != this || laststr != str) {
1635 //lyxerr << "reset lastformula to " << this << endl;
1638 current = ibegin(nucleus());
1640 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1644 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1646 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1647 CursorSlice & top = it.back();
1648 MathData const & a = top.asInsetMath()->cell(top.idx_);
1649 if (a.matchpart(ar, top.pos_)) {
1650 bv->cursor().setSelection(it, ar.size());
1652 top.pos_ += ar.size();
1658 //lyxerr << "not found!" << endl;
1665 void InsetMathHull::write(ostream & os) const
1667 odocstringstream oss;
1668 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1671 os << to_utf8(oss.str());
1675 void InsetMathHull::read(Lexer & lex)
1678 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1679 operator=(*at->asHullInset());
1683 bool InsetMathHull::readQuiet(Lexer & lex)
1686 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1688 operator=(*at->asHullInset());
1693 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1695 if (0 && display()) {
1699 TextPainter tpain(dim.width(), dim.height());
1700 drawT(tpain, 0, dim.ascent());
1702 // reset metrics cache to "real" values
1704 return tpain.textheight();
1706 odocstringstream oss;
1707 Encoding const * const enc = encodings.fromLyXName("utf8");
1708 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1710 if (type_ == hullRegexp)
1714 docstring const str = oss.str();
1721 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1726 if (getType() == hullSimple)
1727 name = from_ascii("inlineequation");
1729 name = from_ascii("informalequation");
1731 docstring bname = name;
1732 if (!label(0).empty())
1733 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1735 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1737 odocstringstream ls;
1738 if (runparams.flavor == OutputParams::XML) {
1739 ms << MTag("alt role='tex' ");
1740 // Workaround for db2latex: db2latex always includes equations with
1741 // \ensuremath{} or \begin{display}\end{display}
1742 // so we strip LyX' math environment
1743 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1744 InsetMathGrid::write(wi);
1745 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1750 InsetMathGrid::mathmlize(ms);
1753 ms << MTag("alt role='tex'");
1754 res = latex(ls, runparams);
1755 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1759 ms << from_ascii("<graphic fileref=\"eqn/");
1760 if (!label(0).empty())
1761 ms << sgml::cleanID(buffer(), runparams, label(0));
1763 ms << sgml::uniqueID(from_ascii("anon"));
1765 if (runparams.flavor == OutputParams::XML)
1766 ms << from_ascii("\"/>");
1768 ms << from_ascii("\">");
1770 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1772 return ms.line() + res;
1776 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const &) const
1778 if (getType() == hullSimple)
1779 xs << StartTag("math", "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1781 xs << StartTag("math",
1782 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1783 MathStream ms(xs.os());
1784 InsetMathGrid::mathmlize(ms);
1785 xs << EndTag("math");
1790 void InsetMathHull::tocString(odocstream & os) const
1792 plaintext(os, OutputParams(0));
1796 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1798 return from_ascii("context-math");