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"
28 #include "FuncRequest.h"
29 #include "FuncStatus.h"
30 #include "LaTeXFeatures.h"
32 #include "MacroTable.h"
33 #include "output_xhtml.h"
35 #include "TextPainter.h"
36 #include "TocBackend.h"
38 #include "insets/InsetLabel.h"
39 #include "insets/InsetRef.h"
40 #include "insets/RenderPreview.h"
42 #include "graphics/PreviewImage.h"
43 #include "graphics/PreviewLoader.h"
45 #include "frontends/Painter.h"
47 #include "support/lassert.h"
48 #include "support/debug.h"
49 #include "support/gettext.h"
50 #include "support/lstrings.h"
55 using namespace lyx::support;
59 using cap::grabAndEraseSelection;
63 int getCols(HullType type)
80 // returns position of first relation operator in the array
81 // used for "intelligent splitting"
82 size_t firstRelOp(MathData const & ar)
84 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
86 return it - ar.begin();
91 char const * star(bool numbered)
93 return numbered ? "" : "*";
97 } // end anon namespace
100 HullType hullType(docstring const & s)
102 if (s == "none") return hullNone;
103 if (s == "simple") return hullSimple;
104 if (s == "equation") return hullEquation;
105 if (s == "eqnarray") return hullEqnArray;
106 if (s == "align") return hullAlign;
107 if (s == "alignat") return hullAlignAt;
108 if (s == "xalignat") return hullXAlignAt;
109 if (s == "xxalignat") return hullXXAlignAt;
110 if (s == "multline") return hullMultline;
111 if (s == "gather") return hullGather;
112 if (s == "flalign") return hullFlAlign;
113 if (s == "regexp") return hullRegexp;
114 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
119 docstring hullName(HullType type)
122 case hullNone: return from_ascii("none");
123 case hullSimple: return from_ascii("simple");
124 case hullEquation: return from_ascii("equation");
125 case hullEqnArray: return from_ascii("eqnarray");
126 case hullAlign: return from_ascii("align");
127 case hullAlignAt: return from_ascii("alignat");
128 case hullXAlignAt: return from_ascii("xalignat");
129 case hullXXAlignAt: return from_ascii("xxalignat");
130 case hullMultline: return from_ascii("multline");
131 case hullGather: return from_ascii("gather");
132 case hullFlAlign: return from_ascii("flalign");
133 case hullRegexp: return from_ascii("regexp");
135 lyxerr << "unknown hull type '" << type << "'" << endl;
136 return from_ascii("none");
140 static InsetLabel * dummy_pointer = 0;
142 InsetMathHull::InsetMathHull(Buffer * buf)
143 : InsetMathGrid(buf, 1, 1), type_(hullNone), nonum_(1, false),
144 label_(1, dummy_pointer), preview_(new RenderPreview(this))
146 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
147 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
148 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
149 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
156 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
157 : InsetMathGrid(buf, getCols(type), 1), type_(type), nonum_(1, false),
158 label_(1, dummy_pointer), preview_(new RenderPreview(this))
166 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
172 InsetMathHull::~InsetMathHull()
174 for (size_t i = 0; i < label_.size(); ++i)
179 Inset * InsetMathHull::clone() const
181 return new InsetMathHull(*this);
185 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
189 InsetMathGrid::operator=(other);
191 nonum_ = other.nonum_;
192 buffer_ = other.buffer_;
193 for (size_t i = 0; i < label_.size(); ++i)
195 label_ = other.label_;
196 for (size_t i = 0; i != label_.size(); ++i) {
198 label_[i] = new InsetLabel(*label_[i]);
200 preview_.reset(new RenderPreview(*other.preview_, this));
206 void InsetMathHull::setBuffer(Buffer & buffer)
208 InsetMathGrid::setBuffer(buffer);
210 for (size_t i = 0; i != label_.size(); ++i) {
212 label_[i]->setBuffer(buffer);
217 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
220 //FIXME: buffer_ should be set at creation for this inset! Problem is
221 // This inset is created at too many places (see Parser::parse1() in
225 for (size_t i = 0; i != label_.size(); ++i) {
227 label_[i]->updateBuffer(it, utype);
230 InsetMathGrid::updateBuffer(it, utype);
234 void InsetMathHull::addToToc(DocIterator const & pit)
237 //FIXME: buffer_ should be set at creation for this inset! Problem is
238 // This inset is created at too many places (see Parser::parse1() in
243 Toc & toc = buffer().tocBackend().toc("equation");
245 for (row_type row = 0; row != nrows(); ++row) {
249 label_[row]->addToToc(pit);
250 toc.push_back(TocItem(pit, 0, nicelabel(row)));
255 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
261 return InsetMathNest::editXY(cur, x, y);
265 InsetMath::mode_type InsetMathHull::currentMode() const
267 if (type_ == hullNone)
268 return UNDECIDED_MODE;
269 // definitely math mode ...
274 bool InsetMathHull::idxFirst(Cursor & cur) const
282 bool InsetMathHull::idxLast(Cursor & cur) const
284 cur.idx() = nargs() - 1;
285 cur.pos() = cur.lastpos();
290 char InsetMathHull::defaultColAlign(col_type col)
292 if (type_ == hullEqnArray)
294 if (type_ == hullGather)
296 if (type_ >= hullAlign)
297 return "rl"[col & 1];
302 int InsetMathHull::defaultColSpace(col_type col)
304 if (type_ == hullAlign || type_ == hullAlignAt)
306 if (type_ == hullXAlignAt)
307 return (col & 1) ? 20 : 0;
308 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
309 return (col & 1) ? 40 : 0;
314 docstring InsetMathHull::standardFont() const
319 font_name = from_ascii("texttt");
322 font_name = from_ascii("lyxnochange");
325 font_name = from_ascii("mathnormal");
331 bool InsetMathHull::previewState(BufferView * bv) const
333 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
334 graphics::PreviewImage const * pimage =
335 preview_->getPreviewImage(bv->buffer());
336 return pimage && pimage->image();
342 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
344 if (previewState(mi.base.bv)) {
345 preview_->metrics(mi, dim);
346 // insert a one pixel gap in front of the formula
349 dim.des += displayMargin();
350 // Cache the inset dimension.
351 setDimCache(mi, dim);
355 FontSetChanger dummy1(mi.base, standardFont());
356 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
358 // let the cells adjust themselves
359 InsetMathGrid::metrics(mi, dim);
362 dim.asc += displayMargin();
363 dim.des += displayMargin();
366 if (numberedType()) {
367 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
369 for (row_type row = 0; row < nrows(); ++row)
370 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
376 // make it at least as high as the current font
379 math_font_max_dim(mi.base.font, asc, des);
380 dim.asc = max(dim.asc, asc);
381 dim.des = max(dim.des, des);
382 // Cache the inset dimension.
383 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
384 setDimCache(mi, dim);
388 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
390 if (previewState(pi.base.bv))
391 return graphics::PreviewLoader::backgroundColor();
396 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
398 Dimension const dim = dimension(*pi.base.bv);
399 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
400 dim.asc + dim.des - 1, pi.backgroundColor(this));
404 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
406 use_preview_ = previewState(pi.base.bv);
408 if (type_ == hullRegexp) {
409 Dimension const dim = dimension(*pi.base.bv);
410 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
411 dim.width() - 2, dim.height() - 2, Color_regexpframe);
414 // one pixel gap in front
415 preview_->draw(pi, x + 1, y);
416 setPosCache(pi, x, y);
420 FontSetChanger dummy1(pi.base, standardFont());
421 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
422 InsetMathGrid::draw(pi, x + 1, y);
424 if (numberedType()) {
425 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
426 for (row_type row = 0; row < nrows(); ++row) {
427 int const yy = y + rowinfo_[row].offset_;
428 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
429 docstring const nl = nicelabel(row);
433 setPosCache(pi, x, y);
437 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
440 InsetMathGrid::metricsT(mi, dim);
443 WriteStream wi(os, false, true, WriteStream::wsDefault);
445 dim.wid = os.str().size();
452 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
455 InsetMathGrid::drawT(pain, x, y);
458 WriteStream wi(os, false, true, WriteStream::wsDefault);
460 pain.draw(x, y, os.str().c_str());
465 static docstring latexString(InsetMathHull const & inset)
468 // This has to be static, because a preview snippet or a math
469 // macro containing math in text mode (such as $\text{$\phi$}$ or
470 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
471 // first time as a whole, and the second time only the inner math.
472 // In this last case inset.buffer() would be invalid.
473 static Encoding const * encoding = 0;
474 if (inset.isBufferValid())
475 encoding = &(inset.buffer().params().encoding());
476 WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
482 void InsetMathHull::initUnicodeMath() const
484 // Trigger classification of the unicode symbols in this inset
485 docstring const dummy = latexString(*this);
489 void InsetMathHull::addPreview(DocIterator const & inset_pos,
490 graphics::PreviewLoader & /*ploader*/) const
492 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
493 preparePreview(inset_pos);
498 void InsetMathHull::preparePreview(DocIterator const & pos) const
500 Buffer const * buffer = pos.buffer();
502 // collect macros at this position
504 buffer->listMacroNames(macros);
505 MacroNameSet::iterator it = macros.begin();
506 MacroNameSet::iterator end = macros.end();
507 odocstringstream macro_preamble;
508 for (; it != end; ++it) {
509 MacroData const * data = buffer->getMacro(*it, pos, true);
511 data->write(macro_preamble, true);
512 macro_preamble << endl;
516 docstring const snippet = macro_preamble.str() + latexString(*this);
517 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
518 preview_->addPreview(snippet, *buffer);
522 void InsetMathHull::reloadPreview(DocIterator const & pos) const
525 preview_->startLoading(*pos.buffer());
529 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
531 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
533 cur.updateFlags(Update::Force);
539 docstring InsetMathHull::label(row_type row) const
541 LASSERT(row < nrows(), /**/);
542 if (InsetLabel * il = label_[row])
543 return il->screenLabel();
548 void InsetMathHull::label(row_type row, docstring const & label)
550 //lyxerr << "setting label '" << label << "' for row " << row << endl;
554 label_[row] = dummy_pointer;
555 // We need an update of the Buffer reference cache.
556 // This is achieved by updateBuffer().
558 buffer().updateBuffer();
561 label_[row]->updateCommand(label);
563 label_[row]->setParam("name", label);
567 InsetCommandParams p(LABEL_CODE);
569 label_[row] = new InsetLabel(buffer_, p);
571 label_[row]->setBuffer(buffer());
575 void InsetMathHull::numbered(row_type row, bool num)
578 if (nonum_[row] && label_[row]) {
582 // The buffer is set at the end of readInset.
583 // When parsing the inset, buffer_ is 0.
586 // We need an update of the Buffer reference cache.
587 // This is achieved by updateBuffer().
588 buffer().updateBuffer();
593 bool InsetMathHull::numbered(row_type row) const
599 bool InsetMathHull::ams() const
601 return type_ == hullAlign
602 || type_ == hullFlAlign
603 || type_ == hullMultline
604 || type_ == hullGather
605 || type_ == hullAlignAt
606 || type_ == hullXAlignAt
607 || type_ == hullXXAlignAt;
611 Inset::DisplayType InsetMathHull::display() const
613 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
618 bool InsetMathHull::numberedType() const
620 if (type_ == hullNone)
622 if (type_ == hullSimple)
624 if (type_ == hullXXAlignAt)
626 if (type_ == hullRegexp)
628 for (row_type row = 0; row < nrows(); ++row)
635 void InsetMathHull::validate(LaTeXFeatures & features) const
638 features.require("amsmath");
640 if (type_ == hullRegexp) {
641 features.require("color");
642 string frcol = lcolor.getLaTeXName(Color_regexpframe);
643 string bgcol = "white";
644 features.addPreambleSnippet(
645 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
646 + frcol + string("}{")
647 + bgcol + string("}{\\texttt{#1}}}"));
650 // Validation is necessary only if not using AMS math.
651 // To be safe, we will always run mathedvalidate.
652 //if (features.amsstyle)
655 //features.binom = true;
657 InsetMathGrid::validate(features);
661 void InsetMathHull::header_write(WriteStream & os) const
663 bool n = numberedType();
677 os << "\\begin{equation" << star(n) << "}\n";
687 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
692 os << "\\begin{" << hullName(type_) << star(n) << '}'
693 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
697 os << "\\begin{" << hullName(type_) << '}'
698 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
706 os << "\\begin{unknown" << star(n) << '}';
712 void InsetMathHull::footer_write(WriteStream & os) const
714 bool n = numberedType();
727 os << "\\end{equation" << star(n) << "}\n";
739 os << "\\end{" << hullName(type_) << star(n) << "}\n";
743 os << "\\end{" << hullName(type_) << "}\n";
751 os << "\\end{unknown" << star(n) << '}';
757 bool InsetMathHull::rowChangeOK() const
760 type_ == hullEqnArray || type_ == hullAlign ||
761 type_ == hullFlAlign || type_ == hullAlignAt ||
762 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
763 type_ == hullGather || type_ == hullMultline;
767 bool InsetMathHull::colChangeOK() const
770 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
771 type_ == hullXAlignAt || type_ == hullXXAlignAt;
775 void InsetMathHull::addRow(row_type row)
780 bool numbered = numberedType();
782 if (type_ == hullMultline) {
783 if (row + 1 == nrows()) {
790 nonum_.insert(nonum_.begin() + row + 1, !numbered);
791 label_.insert(label_.begin() + row + 1, dummy_pointer);
794 InsetMathGrid::addRow(row);
798 void InsetMathHull::swapRow(row_type row)
802 if (row + 1 == nrows())
804 // gcc implements the standard std::vector<bool> which is *not* a container:
805 // http://www.gotw.ca/publications/N1185.pdf
806 // As a results, it doesn't like this:
807 // swap(nonum_[row], nonum_[row + 1]);
808 // so we do it manually:
809 bool const b = nonum_[row];
810 nonum_[row] = nonum_[row + 1];
812 swap(label_[row], label_[row + 1]);
813 InsetMathGrid::swapRow(row);
817 void InsetMathHull::delRow(row_type row)
819 if (nrows() <= 1 || !rowChangeOK())
821 if (row + 1 == nrows() && type_ == hullMultline) {
822 bool const b = nonum_[row - 1];
823 nonum_[row - 1] = nonum_[row];
825 swap(label_[row - 1], label_[row]);
826 InsetMathGrid::delRow(row);
829 InsetMathGrid::delRow(row);
830 // The last dummy row has no number info nor a label.
831 // Test nrows() + 1 because we have already erased the row.
832 if (row == nrows() + 1)
834 nonum_.erase(nonum_.begin() + row);
836 label_.erase(label_.begin() + row);
840 void InsetMathHull::addCol(col_type col)
844 InsetMathGrid::addCol(col);
848 void InsetMathHull::delCol(col_type col)
850 if (ncols() <= 1 || !colChangeOK())
852 InsetMathGrid::delCol(col);
856 docstring InsetMathHull::nicelabel(row_type row) const
861 return from_ascii("(#)");
862 return '(' + label_[row]->screenLabel() + from_ascii(", #)");
866 void InsetMathHull::glueall()
869 for (idx_type i = 0; i < nargs(); ++i)
871 *this = InsetMathHull(buffer_, hullSimple);
877 void InsetMathHull::splitTo2Cols()
879 LASSERT(ncols() == 1, /**/);
880 InsetMathGrid::addCol(1);
881 for (row_type row = 0; row < nrows(); ++row) {
882 idx_type const i = 2 * row;
883 pos_type pos = firstRelOp(cell(i));
884 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
885 cell(i).erase(pos, cell(i).size());
890 void InsetMathHull::splitTo3Cols()
892 LASSERT(ncols() < 3, /**/);
895 InsetMathGrid::addCol(2);
896 for (row_type row = 0; row < nrows(); ++row) {
897 idx_type const i = 3 * row + 1;
898 if (cell(i).size()) {
899 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
900 cell(i).erase(1, cell(i).size());
906 void InsetMathHull::changeCols(col_type cols)
910 else if (ncols() < cols) {
916 while (ncols() < cols)
917 InsetMathGrid::addCol(ncols());
923 for (row_type row = 0; row < nrows(); ++row) {
924 idx_type const i = row * ncols();
925 for (col_type col = cols; col < ncols(); ++col) {
926 cell(i + cols - 1).append(cell(i + col));
930 while (ncols() > cols) {
931 InsetMathGrid::delCol(ncols() - 1);
936 HullType InsetMathHull::getType() const
942 void InsetMathHull::setType(HullType type)
949 void InsetMathHull::mutate(HullType newtype)
951 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
953 // we try to move along the chain
954 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
956 // +-------------------------------------+
957 // we use eqnarray as intermediate type for mutations that are not
958 // directly supported because it handles labels and numbering for
961 if (newtype == type_) {
965 else if (newtype < hullNone) {
970 else if (type_ == hullNone) {
976 else if (type_ == hullSimple) {
977 if (newtype == hullNone) {
981 setType(hullEquation);
987 else if (type_ == hullEquation) {
988 if (newtype < type_) {
992 } else if (newtype == hullEqnArray) {
993 // split it "nicely" on the first relop
995 setType(hullEqnArray);
996 } else if (newtype == hullMultline || newtype == hullGather) {
1006 else if (type_ == hullEqnArray) {
1007 if (newtype < type_) {
1008 // set correct (no)numbering
1010 for (row_type row = 0; row < nrows(); ++row) {
1017 // set first non-empty label
1018 for (row_type row = 0; row < nrows(); ++row) {
1020 label_[0] = label_[row];
1027 } else { // align & Co.
1034 else if (type_ == hullAlign || type_ == hullAlignAt ||
1035 type_ == hullXAlignAt || type_ == hullFlAlign) {
1036 if (newtype < hullAlign) {
1038 setType(hullEqnArray);
1040 } else if (newtype == hullGather || newtype == hullMultline) {
1043 } else if (newtype == hullXXAlignAt) {
1044 for (row_type row = 0; row < nrows(); ++row)
1045 numbered(row, false);
1052 else if (type_ == hullXXAlignAt) {
1053 for (row_type row = 0; row < nrows(); ++row)
1054 numbered(row, false);
1055 if (newtype < hullAlign) {
1057 setType(hullEqnArray);
1059 } else if (newtype == hullGather || newtype == hullMultline) {
1067 else if (type_ == hullMultline || type_ == hullGather) {
1068 if (newtype == hullGather || newtype == hullMultline)
1070 else if (newtype == hullAlign || newtype == hullFlAlign ||
1071 newtype == hullAlignAt || newtype == hullXAlignAt) {
1074 } else if (newtype == hullXXAlignAt) {
1076 for (row_type row = 0; row < nrows(); ++row)
1077 numbered(row, false);
1081 setType(hullEqnArray);
1087 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1088 << "' to '" << to_utf8(hullName(newtype))
1089 << "' not implemented" << endl;
1094 docstring InsetMathHull::eolString(row_type row, bool fragile) const
1097 if (numberedType()) {
1098 if (label_[row] && !nonum_[row])
1100 escape(label_[row]->getParam("name")) + '}';
1101 if (nonum_[row] && (type_ != hullMultline))
1102 res += "\\nonumber ";
1104 return res + InsetMathGrid::eolString(row, fragile);
1108 void InsetMathHull::write(WriteStream & os) const
1110 ModeSpecifier specifier(os, MATH_MODE);
1112 InsetMathGrid::write(os);
1117 void InsetMathHull::normalize(NormalStream & os) const
1119 os << "[formula " << hullName(type_) << ' ';
1120 InsetMathGrid::normalize(os);
1125 void InsetMathHull::mathmlize(MathStream & os) const
1127 InsetMathGrid::mathmlize(os);
1131 void InsetMathHull::infoize(odocstream & os) const
1133 os << "Type: " << hullName(type_);
1137 void InsetMathHull::check() const
1139 LASSERT(nonum_.size() == nrows(), /**/);
1140 LASSERT(label_.size() == nrows(), /**/);
1144 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1148 idocstringstream iss(func.argument());
1149 iss >> dlang >> extra;
1151 extra = from_ascii("noextra");
1152 string const lang = to_ascii(dlang);
1154 // FIXME: temporarily disabled
1155 //if (cur.selection()) {
1158 // lyxerr << "use selection: " << ar << endl;
1159 // insert(pipeThroughExtern(lang, extra, ar));
1164 eq.push_back(MathAtom(new InsetMathChar('=')));
1166 // go to first item in line
1167 cur.idx() -= cur.idx() % ncols();
1170 if (getType() == hullSimple) {
1171 size_type pos = cur.cell().find_last(eq);
1173 if (cur.inMathed() && cur.selection()) {
1174 asArray(grabAndEraseSelection(cur), ar);
1175 } else if (pos == cur.cell().size()) {
1177 lyxerr << "use whole cell: " << ar << endl;
1179 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1180 lyxerr << "use partial cell form pos: " << pos << endl;
1182 cur.cell().append(eq);
1183 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1184 cur.pos() = cur.lastpos();
1188 if (getType() == hullEquation) {
1189 lyxerr << "use equation inset" << endl;
1190 mutate(hullEqnArray);
1191 MathData & ar = cur.cell();
1192 lyxerr << "use cell: " << ar << endl;
1196 cur.cell() = pipeThroughExtern(lang, extra, ar);
1197 // move to end of line
1198 cur.pos() = cur.lastpos();
1203 lyxerr << "use eqnarray" << endl;
1204 cur.idx() += 2 - cur.idx() % ncols();
1206 MathData ar = cur.cell();
1207 lyxerr << "use cell: " << ar << endl;
1208 // FIXME: temporarily disabled
1214 cur.cell() = pipeThroughExtern(lang, extra, ar);
1215 cur.pos() = cur.lastpos();
1220 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1222 //lyxerr << "action: " << cmd.action << endl;
1223 switch (cmd.action) {
1225 case LFUN_FINISHED_BACKWARD:
1226 case LFUN_FINISHED_FORWARD:
1227 case LFUN_FINISHED_RIGHT:
1228 case LFUN_FINISHED_LEFT:
1229 //lyxerr << "action: " << cmd.action << endl;
1230 InsetMathGrid::doDispatch(cur, cmd);
1234 case LFUN_BREAK_PARAGRAPH:
1235 // just swallow this
1238 case LFUN_NEWLINE_INSERT:
1239 // some magic for the common case
1240 if (type_ == hullSimple || type_ == hullEquation) {
1241 cur.recordUndoInset();
1243 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1244 mutate(align ? hullAlign : hullEqnArray);
1245 cur.idx() = nrows() * ncols() - 1;
1246 cur.pos() = cur.lastpos();
1248 InsetMathGrid::doDispatch(cur, cmd);
1251 case LFUN_MATH_NUMBER_TOGGLE: {
1252 //lyxerr << "toggling all numbers" << endl;
1253 cur.recordUndoInset();
1254 bool old = numberedType();
1255 if (type_ == hullMultline)
1256 numbered(nrows() - 1, !old);
1258 for (row_type row = 0; row < nrows(); ++row)
1259 numbered(row, !old);
1261 cur.message(old ? _("No number") : _("Number"));
1265 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1266 cur.recordUndoInset();
1267 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1268 bool old = numbered(r);
1269 cur.message(old ? _("No number") : _("Number"));
1274 case LFUN_LABEL_INSERT: {
1275 cur.recordUndoInset();
1276 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1277 docstring old_label = label(r);
1279 // Allow customization of this separator
1280 docstring const default_label = from_ascii("eq:");
1281 if (old_label.empty())
1282 old_label = default_label;
1284 InsetCommandParams p(LABEL_CODE);
1285 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1286 string const data = InsetCommand::params2string("label", p);
1288 if (cmd.argument().empty())
1289 cur.bv().showDialog("label", data);
1291 FuncRequest fr(LFUN_INSET_INSERT, data);
1297 case LFUN_LABEL_COPY_AS_REF: {
1299 if (cmd.argument().empty() && &cur.inset() == this)
1300 // if there is no argument and we're inside math, we retrieve
1301 // the row number from the cursor position.
1302 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1304 // if there is an argument, find the corresponding label, else
1305 // check whether there is at least one label.
1306 for (row = 0; row != nrows(); ++row)
1307 if (!nonum_[row] && label_[row]
1308 && (cmd.argument().empty() || label(row) == cmd.argument()))
1315 InsetCommandParams p(REF_CODE, "ref");
1316 p["reference"] = label(row);
1317 cap::clearSelection();
1318 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1322 case LFUN_WORD_DELETE_FORWARD:
1323 case LFUN_CHAR_DELETE_FORWARD:
1324 if (col(cur.idx()) + 1 == ncols()
1325 && cur.pos() == cur.lastpos()
1326 && !cur.selection()) {
1327 if (!label(row(cur.idx())).empty()) {
1328 cur.recordUndoInset();
1329 label(row(cur.idx()), docstring());
1330 } else if (numbered(row(cur.idx()))) {
1331 cur.recordUndoInset();
1332 numbered(row(cur.idx()), false);
1334 InsetMathGrid::doDispatch(cur, cmd);
1338 InsetMathGrid::doDispatch(cur, cmd);
1343 case LFUN_INSET_INSERT: {
1344 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1345 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1346 string const name = cmd.getArg(0);
1347 if (name == "label") {
1348 InsetCommandParams p(LABEL_CODE);
1349 InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1350 docstring str = p["name"];
1351 cur.recordUndoInset();
1352 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1356 docstring old = label(r);
1359 // The label will take care of the reference update.
1363 // Newly created inset so initialize it.
1364 label_[r]->initView();
1369 InsetMathGrid::doDispatch(cur, cmd);
1373 case LFUN_MATH_EXTERN:
1374 cur.recordUndoInset();
1378 case LFUN_MATH_MUTATE: {
1379 cur.recordUndoInset();
1380 row_type row = cur.row();
1381 col_type col = cur.col();
1382 mutate(hullType(cmd.argument()));
1383 cur.idx() = row * ncols() + col;
1384 if (cur.idx() > cur.lastidx()) {
1385 cur.idx() = cur.lastidx();
1386 cur.pos() = cur.lastpos();
1388 if (cur.pos() > cur.lastpos())
1389 cur.pos() = cur.lastpos();
1391 // FIXME: find some more clever handling of the selection,
1392 // i.e. preserve it.
1393 cur.clearSelection();
1394 //cur.dispatched(FINISHED);
1398 case LFUN_MATH_DISPLAY: {
1399 cur.recordUndoInset();
1400 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1402 cur.pos() = cur.lastpos();
1403 //cur.dispatched(FINISHED);
1408 InsetMathGrid::doDispatch(cur, cmd);
1414 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1415 FuncStatus & status) const
1417 switch (cmd.action) {
1418 case LFUN_FINISHED_BACKWARD:
1419 case LFUN_FINISHED_FORWARD:
1420 case LFUN_FINISHED_RIGHT:
1421 case LFUN_FINISHED_LEFT:
1424 case LFUN_NEWLINE_INSERT:
1425 case LFUN_MATH_EXTERN:
1426 case LFUN_MATH_DISPLAY:
1428 status.setEnabled(true);
1431 case LFUN_MATH_MUTATE: {
1432 HullType ht = hullType(cmd.argument());
1433 status.setOnOff(type_ == ht);
1434 status.setEnabled(true);
1438 case LFUN_MATH_NUMBER_TOGGLE:
1439 // FIXME: what is the right test, this or the one of
1441 status.setEnabled(display());
1442 status.setOnOff(numberedType());
1445 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1446 // FIXME: what is the right test, this or the one of
1448 bool const enable = (type_ == hullMultline)
1449 ? (nrows() - 1 == cur.row())
1450 : display() != Inline && nrows() > 1;
1451 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1452 status.setEnabled(enable);
1453 status.setOnOff(enable && numbered(r));
1457 case LFUN_LABEL_INSERT:
1458 status.setEnabled(type_ != hullSimple);
1461 case LFUN_LABEL_COPY_AS_REF: {
1462 bool enabled = false;
1464 if (cmd.argument().empty() && &cur.inset() == this) {
1465 // if there is no argument and we're inside math, we retrieve
1466 // the row number from the cursor position.
1467 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1468 enabled = numberedType() && label_[row] && !nonum_[row];
1470 // if there is an argument, find the corresponding label, else
1471 // check whether there is at least one label.
1472 for (row_type row = 0; row != nrows(); ++row) {
1473 if (!nonum_[row] && label_[row] &&
1474 (cmd.argument().empty() || label(row) == cmd.argument())) {
1480 status.setEnabled(enabled);
1484 case LFUN_INSET_INSERT:
1485 if (cmd.getArg(0) == "label") {
1486 status.setEnabled(type_ != hullSimple);
1489 return InsetMathGrid::getStatus(cur, cmd, status);
1491 case LFUN_INSET_MODIFY: {
1492 istringstream is(to_utf8(cmd.argument()));
1496 return InsetMathGrid::getStatus(cur, cmd, status);
1499 && (s == "append-row"
1500 || s == "delete-row"
1501 || s == "copy-row")) {
1502 status.message(bformat(
1503 from_utf8(N_("Can't change number of rows in '%1$s'")),
1505 status.setEnabled(false);
1509 && (s == "append-column"
1510 || s == "delete-column"
1511 || s == "copy-column")) {
1512 status.message(bformat(
1513 from_utf8(N_("Can't change number of columns in '%1$s'")),
1515 status.setEnabled(false);
1518 if ((type_ == hullSimple
1519 || type_ == hullEquation
1520 || type_ == hullNone) &&
1521 (s == "add-hline-above" || s == "add-hline-below")) {
1522 status.message(bformat(
1523 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1525 status.setEnabled(false);
1528 if (s == "add-vline-left" || s == "add-vline-right") {
1529 status.message(bformat(
1530 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1532 status.setEnabled(false);
1535 if (s == "valign-top" || s == "valign-middle"
1536 || s == "valign-bottom" || s == "align-left"
1537 || s == "align-center" || s == "align-right") {
1538 status.setEnabled(false);
1541 return InsetMathGrid::getStatus(cur, cmd, status);
1545 return InsetMathGrid::getStatus(cur, cmd, status);
1548 // This cannot really happen, but inserted to shut-up gcc
1549 return InsetMathGrid::getStatus(cur, cmd, status);
1553 /////////////////////////////////////////////////////////////////////
1557 // simply scrap this function if you want
1558 void InsetMathHull::mutateToText()
1561 // translate to latex
1563 latex(os, false, false);
1564 string str = os.str();
1567 Text * lt = view_->cursor().innerText();
1568 string::const_iterator cit = str.begin();
1569 string::const_iterator end = str.end();
1570 for (; cit != end; ++cit)
1571 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1574 //dispatch(LFUN_ESCAPE);
1579 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1580 docstring const & font)
1582 // this whole function is a hack and won't work for incremental font
1585 if (cur.inset().asInsetMath()->name() == font)
1586 cur.handleFont(to_utf8(font));
1588 cur.handleNest(createInsetMath(font, cur.buffer()));
1594 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1599 font.fromString(to_utf8(arg), b);
1600 if (font.fontInfo().color() != Color_inherit) {
1601 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1602 cur.handleNest(at, 0);
1607 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1610 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1611 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1612 enter_front ? idxFirst(cur) : idxLast(cur);
1613 // The inset formula dimension is not necessarily the same as the
1614 // one of the instant preview image, so we have to indicate to the
1615 // BufferView that a metrics update is needed.
1616 cur.updateFlags(Update::Force);
1620 void InsetMathHull::revealCodes(Cursor & cur) const
1622 if (!cur.inMathed())
1624 odocstringstream os;
1626 cur.message(os.str());
1628 // write something to the minibuffer
1629 // translate to latex
1633 string str = os.str();
1635 string::size_type pos = 0;
1637 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1640 else if (*it == '\0') {
1642 pos = it - str.begin();
1648 res = res.substr(pos - 30);
1649 if (res.size() > 60)
1650 res = res.substr(0, 60);
1656 /////////////////////////////////////////////////////////////////////
1660 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1663 // FIXME: completely broken
1664 static InsetMathHull * lastformula = 0;
1665 static CursorBase current = DocIterator(ibegin(nucleus()));
1667 static string laststr;
1669 if (lastformula != this || laststr != str) {
1670 //lyxerr << "reset lastformula to " << this << endl;
1673 current = ibegin(nucleus());
1675 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1679 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1681 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1682 CursorSlice & top = it.back();
1683 MathData const & a = top.asInsetMath()->cell(top.idx_);
1684 if (a.matchpart(ar, top.pos_)) {
1685 bv->cursor().setSelection(it, ar.size());
1687 top.pos_ += ar.size();
1693 //lyxerr << "not found!" << endl;
1700 void InsetMathHull::write(ostream & os) const
1702 odocstringstream oss;
1703 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1706 os << to_utf8(oss.str());
1710 void InsetMathHull::read(Lexer & lex)
1713 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1714 operator=(*at->asHullInset());
1718 bool InsetMathHull::readQuiet(Lexer & lex)
1721 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1723 operator=(*at->asHullInset());
1728 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1730 if (0 && display()) {
1734 TextPainter tpain(dim.width(), dim.height());
1735 drawT(tpain, 0, dim.ascent());
1737 // reset metrics cache to "real" values
1739 return tpain.textheight();
1741 odocstringstream oss;
1742 Encoding const * const enc = encodings.fromLyXName("utf8");
1743 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1745 if (type_ == hullRegexp)
1749 docstring const str = oss.str();
1756 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1761 if (getType() == hullSimple)
1762 name = from_ascii("inlineequation");
1764 name = from_ascii("informalequation");
1766 docstring bname = name;
1767 if (!label(0).empty())
1768 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1770 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1772 odocstringstream ls;
1773 if (runparams.flavor == OutputParams::XML) {
1774 ms << MTag("alt role='tex' ");
1775 // Workaround for db2latex: db2latex always includes equations with
1776 // \ensuremath{} or \begin{display}\end{display}
1777 // so we strip LyX' math environment
1778 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1779 InsetMathGrid::write(wi);
1780 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1785 InsetMathGrid::mathmlize(ms);
1788 ms << MTag("alt role='tex'");
1789 res = latex(ls, runparams);
1790 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1794 ms << from_ascii("<graphic fileref=\"eqn/");
1795 if (!label(0).empty())
1796 ms << sgml::cleanID(buffer(), runparams, label(0));
1798 ms << sgml::uniqueID(from_ascii("anon"));
1800 if (runparams.flavor == OutputParams::XML)
1801 ms << from_ascii("\"/>");
1803 ms << from_ascii("\">");
1805 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1807 return ms.line() + res;
1811 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const &) const
1813 if (getType() == hullSimple)
1814 xs << html::StartTag("math", "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1816 xs << html::StartTag("math",
1817 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1818 MathStream ms(xs.os());
1819 InsetMathGrid::mathmlize(ms);
1820 xs << html::EndTag("math");
1825 void InsetMathHull::tocString(odocstream & os) const
1827 plaintext(os, OutputParams(0));
1831 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1833 return from_ascii("context-math");