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
637 if (features.runparams().isLaTeX()) {
639 features.require("amsmath");
641 if (type_ == hullRegexp) {
642 features.require("color");
643 string frcol = lcolor.getLaTeXName(Color_regexpframe);
644 string bgcol = "white";
645 features.addPreambleSnippet(
646 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
647 + frcol + string("}{")
648 + bgcol + string("}{\\texttt{#1}}}"));
651 // Validation is necessary only if not using AMS math.
652 // To be safe, we will always run mathedvalidate.
653 //if (features.amsstyle)
656 //features.binom = true;
657 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
658 // it would be better to do this elsewhere, but we can't validate in
659 // InsetMathMatrix and we have no way, outside MathExtern, to know if
660 // we even have any matrices.
661 features.addPreambleSnippet("<style type=\"text/css\">\n"
662 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
663 "table.matrix td{padding: 0.25px;}\n"
664 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
665 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}\n"
668 InsetMathGrid::validate(features);
672 void InsetMathHull::header_write(WriteStream & os) const
674 bool n = numberedType();
688 os << "\\begin{equation" << star(n) << "}\n";
698 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
703 os << "\\begin{" << hullName(type_) << star(n) << '}'
704 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
708 os << "\\begin{" << hullName(type_) << '}'
709 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
717 os << "\\begin{unknown" << star(n) << '}';
723 void InsetMathHull::footer_write(WriteStream & os) const
725 bool n = numberedType();
738 os << "\\end{equation" << star(n) << "}\n";
750 os << "\\end{" << hullName(type_) << star(n) << "}\n";
754 os << "\\end{" << hullName(type_) << "}\n";
762 os << "\\end{unknown" << star(n) << '}';
768 bool InsetMathHull::rowChangeOK() const
771 type_ == hullEqnArray || type_ == hullAlign ||
772 type_ == hullFlAlign || type_ == hullAlignAt ||
773 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
774 type_ == hullGather || type_ == hullMultline;
778 bool InsetMathHull::colChangeOK() const
781 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
782 type_ == hullXAlignAt || type_ == hullXXAlignAt;
786 void InsetMathHull::addRow(row_type row)
791 bool numbered = numberedType();
793 if (type_ == hullMultline) {
794 if (row + 1 == nrows()) {
801 nonum_.insert(nonum_.begin() + row + 1, !numbered);
802 label_.insert(label_.begin() + row + 1, dummy_pointer);
805 InsetMathGrid::addRow(row);
809 void InsetMathHull::swapRow(row_type row)
813 if (row + 1 == nrows())
815 // gcc implements the standard std::vector<bool> which is *not* a container:
816 // http://www.gotw.ca/publications/N1185.pdf
817 // As a results, it doesn't like this:
818 // swap(nonum_[row], nonum_[row + 1]);
819 // so we do it manually:
820 bool const b = nonum_[row];
821 nonum_[row] = nonum_[row + 1];
823 swap(label_[row], label_[row + 1]);
824 InsetMathGrid::swapRow(row);
828 void InsetMathHull::delRow(row_type row)
830 if (nrows() <= 1 || !rowChangeOK())
832 if (row + 1 == nrows() && type_ == hullMultline) {
833 bool const b = nonum_[row - 1];
834 nonum_[row - 1] = nonum_[row];
836 swap(label_[row - 1], label_[row]);
837 InsetMathGrid::delRow(row);
840 InsetMathGrid::delRow(row);
841 // The last dummy row has no number info nor a label.
842 // Test nrows() + 1 because we have already erased the row.
843 if (row == nrows() + 1)
845 nonum_.erase(nonum_.begin() + row);
847 label_.erase(label_.begin() + row);
851 void InsetMathHull::addCol(col_type col)
855 InsetMathGrid::addCol(col);
859 void InsetMathHull::delCol(col_type col)
861 if (ncols() <= 1 || !colChangeOK())
863 InsetMathGrid::delCol(col);
867 docstring InsetMathHull::nicelabel(row_type row) const
872 return from_ascii("(#)");
873 return '(' + label_[row]->screenLabel() + from_ascii(", #)");
877 void InsetMathHull::glueall()
880 for (idx_type i = 0; i < nargs(); ++i)
882 *this = InsetMathHull(buffer_, hullSimple);
888 void InsetMathHull::splitTo2Cols()
890 LASSERT(ncols() == 1, /**/);
891 InsetMathGrid::addCol(1);
892 for (row_type row = 0; row < nrows(); ++row) {
893 idx_type const i = 2 * row;
894 pos_type pos = firstRelOp(cell(i));
895 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
896 cell(i).erase(pos, cell(i).size());
901 void InsetMathHull::splitTo3Cols()
903 LASSERT(ncols() < 3, /**/);
906 InsetMathGrid::addCol(2);
907 for (row_type row = 0; row < nrows(); ++row) {
908 idx_type const i = 3 * row + 1;
909 if (cell(i).size()) {
910 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
911 cell(i).erase(1, cell(i).size());
917 void InsetMathHull::changeCols(col_type cols)
921 else if (ncols() < cols) {
927 while (ncols() < cols)
928 InsetMathGrid::addCol(ncols());
934 for (row_type row = 0; row < nrows(); ++row) {
935 idx_type const i = row * ncols();
936 for (col_type col = cols; col < ncols(); ++col) {
937 cell(i + cols - 1).append(cell(i + col));
941 while (ncols() > cols) {
942 InsetMathGrid::delCol(ncols() - 1);
947 HullType InsetMathHull::getType() const
953 void InsetMathHull::setType(HullType type)
960 void InsetMathHull::mutate(HullType newtype)
962 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
964 // we try to move along the chain
965 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
967 // +-------------------------------------+
968 // we use eqnarray as intermediate type for mutations that are not
969 // directly supported because it handles labels and numbering for
972 if (newtype == type_) {
976 else if (newtype < hullNone) {
981 else if (type_ == hullNone) {
987 else if (type_ == hullSimple) {
988 if (newtype == hullNone) {
992 setType(hullEquation);
998 else if (type_ == hullEquation) {
999 if (newtype < type_) {
1000 setType(hullSimple);
1003 } else if (newtype == hullEqnArray) {
1004 // split it "nicely" on the first relop
1006 setType(hullEqnArray);
1007 } else if (newtype == hullMultline || newtype == hullGather) {
1010 // split it "nicely"
1017 else if (type_ == hullEqnArray) {
1018 if (newtype < type_) {
1019 // set correct (no)numbering
1021 for (row_type row = 0; row < nrows(); ++row) {
1028 // set first non-empty label
1029 for (row_type row = 0; row < nrows(); ++row) {
1031 label_[0] = label_[row];
1038 } else { // align & Co.
1045 else if (type_ == hullAlign || type_ == hullAlignAt ||
1046 type_ == hullXAlignAt || type_ == hullFlAlign) {
1047 if (newtype < hullAlign) {
1049 setType(hullEqnArray);
1051 } else if (newtype == hullGather || newtype == hullMultline) {
1054 } else if (newtype == hullXXAlignAt) {
1055 for (row_type row = 0; row < nrows(); ++row)
1056 numbered(row, false);
1063 else if (type_ == hullXXAlignAt) {
1064 for (row_type row = 0; row < nrows(); ++row)
1065 numbered(row, false);
1066 if (newtype < hullAlign) {
1068 setType(hullEqnArray);
1070 } else if (newtype == hullGather || newtype == hullMultline) {
1078 else if (type_ == hullMultline || type_ == hullGather) {
1079 if (newtype == hullGather || newtype == hullMultline)
1081 else if (newtype == hullAlign || newtype == hullFlAlign ||
1082 newtype == hullAlignAt || newtype == hullXAlignAt) {
1085 } else if (newtype == hullXXAlignAt) {
1087 for (row_type row = 0; row < nrows(); ++row)
1088 numbered(row, false);
1092 setType(hullEqnArray);
1098 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1099 << "' to '" << to_utf8(hullName(newtype))
1100 << "' not implemented" << endl;
1105 docstring InsetMathHull::eolString(row_type row, bool fragile) const
1108 if (numberedType()) {
1109 if (label_[row] && !nonum_[row])
1111 escape(label_[row]->getParam("name")) + '}';
1112 if (nonum_[row] && (type_ != hullMultline))
1113 res += "\\nonumber ";
1115 return res + InsetMathGrid::eolString(row, fragile);
1119 void InsetMathHull::write(WriteStream & os) const
1121 ModeSpecifier specifier(os, MATH_MODE);
1123 InsetMathGrid::write(os);
1128 void InsetMathHull::normalize(NormalStream & os) const
1130 os << "[formula " << hullName(type_) << ' ';
1131 InsetMathGrid::normalize(os);
1136 void InsetMathHull::mathmlize(MathStream & os) const
1138 InsetMathGrid::mathmlize(os);
1142 void InsetMathHull::infoize(odocstream & os) const
1144 os << "Type: " << hullName(type_);
1148 void InsetMathHull::check() const
1150 LASSERT(nonum_.size() == nrows(), /**/);
1151 LASSERT(label_.size() == nrows(), /**/);
1155 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1159 idocstringstream iss(func.argument());
1160 iss >> dlang >> extra;
1162 extra = from_ascii("noextra");
1163 string const lang = to_ascii(dlang);
1165 // FIXME: temporarily disabled
1166 //if (cur.selection()) {
1169 // lyxerr << "use selection: " << ar << endl;
1170 // insert(pipeThroughExtern(lang, extra, ar));
1175 eq.push_back(MathAtom(new InsetMathChar('=')));
1177 // go to first item in line
1178 cur.idx() -= cur.idx() % ncols();
1181 if (getType() == hullSimple) {
1182 size_type pos = cur.cell().find_last(eq);
1184 if (cur.inMathed() && cur.selection()) {
1185 asArray(grabAndEraseSelection(cur), ar);
1186 } else if (pos == cur.cell().size()) {
1188 lyxerr << "use whole cell: " << ar << endl;
1190 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1191 lyxerr << "use partial cell form pos: " << pos << endl;
1193 cur.cell().append(eq);
1194 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1195 cur.pos() = cur.lastpos();
1199 if (getType() == hullEquation) {
1200 lyxerr << "use equation inset" << endl;
1201 mutate(hullEqnArray);
1202 MathData & ar = cur.cell();
1203 lyxerr << "use cell: " << ar << endl;
1207 cur.cell() = pipeThroughExtern(lang, extra, ar);
1208 // move to end of line
1209 cur.pos() = cur.lastpos();
1214 lyxerr << "use eqnarray" << endl;
1215 cur.idx() += 2 - cur.idx() % ncols();
1217 MathData ar = cur.cell();
1218 lyxerr << "use cell: " << ar << endl;
1219 // FIXME: temporarily disabled
1225 cur.cell() = pipeThroughExtern(lang, extra, ar);
1226 cur.pos() = cur.lastpos();
1231 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1233 //lyxerr << "action: " << cmd.action << endl;
1234 switch (cmd.action) {
1236 case LFUN_FINISHED_BACKWARD:
1237 case LFUN_FINISHED_FORWARD:
1238 case LFUN_FINISHED_RIGHT:
1239 case LFUN_FINISHED_LEFT:
1240 //lyxerr << "action: " << cmd.action << endl;
1241 InsetMathGrid::doDispatch(cur, cmd);
1245 case LFUN_BREAK_PARAGRAPH:
1246 // just swallow this
1249 case LFUN_NEWLINE_INSERT:
1250 // some magic for the common case
1251 if (type_ == hullSimple || type_ == hullEquation) {
1252 cur.recordUndoInset();
1254 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1255 mutate(align ? hullAlign : hullEqnArray);
1256 cur.idx() = nrows() * ncols() - 1;
1257 cur.pos() = cur.lastpos();
1259 InsetMathGrid::doDispatch(cur, cmd);
1262 case LFUN_MATH_NUMBER_TOGGLE: {
1263 //lyxerr << "toggling all numbers" << endl;
1264 cur.recordUndoInset();
1265 bool old = numberedType();
1266 if (type_ == hullMultline)
1267 numbered(nrows() - 1, !old);
1269 for (row_type row = 0; row < nrows(); ++row)
1270 numbered(row, !old);
1272 cur.message(old ? _("No number") : _("Number"));
1276 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1277 cur.recordUndoInset();
1278 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1279 bool old = numbered(r);
1280 cur.message(old ? _("No number") : _("Number"));
1285 case LFUN_LABEL_INSERT: {
1286 cur.recordUndoInset();
1287 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1288 docstring old_label = label(r);
1290 // Allow customization of this separator
1291 docstring const default_label = from_ascii("eq:");
1292 if (old_label.empty())
1293 old_label = default_label;
1295 InsetCommandParams p(LABEL_CODE);
1296 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1297 string const data = InsetCommand::params2string("label", p);
1299 if (cmd.argument().empty())
1300 cur.bv().showDialog("label", data);
1302 FuncRequest fr(LFUN_INSET_INSERT, data);
1308 case LFUN_LABEL_COPY_AS_REF: {
1310 if (cmd.argument().empty() && &cur.inset() == this)
1311 // if there is no argument and we're inside math, we retrieve
1312 // the row number from the cursor position.
1313 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1315 // if there is an argument, find the corresponding label, else
1316 // check whether there is at least one label.
1317 for (row = 0; row != nrows(); ++row)
1318 if (!nonum_[row] && label_[row]
1319 && (cmd.argument().empty() || label(row) == cmd.argument()))
1326 InsetCommandParams p(REF_CODE, "ref");
1327 p["reference"] = label(row);
1328 cap::clearSelection();
1329 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1333 case LFUN_WORD_DELETE_FORWARD:
1334 case LFUN_CHAR_DELETE_FORWARD:
1335 if (col(cur.idx()) + 1 == ncols()
1336 && cur.pos() == cur.lastpos()
1337 && !cur.selection()) {
1338 if (!label(row(cur.idx())).empty()) {
1339 cur.recordUndoInset();
1340 label(row(cur.idx()), docstring());
1341 } else if (numbered(row(cur.idx()))) {
1342 cur.recordUndoInset();
1343 numbered(row(cur.idx()), false);
1345 InsetMathGrid::doDispatch(cur, cmd);
1349 InsetMathGrid::doDispatch(cur, cmd);
1354 case LFUN_INSET_INSERT: {
1355 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1356 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1357 string const name = cmd.getArg(0);
1358 if (name == "label") {
1359 InsetCommandParams p(LABEL_CODE);
1360 InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1361 docstring str = p["name"];
1362 cur.recordUndoInset();
1363 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1367 docstring old = label(r);
1370 // The label will take care of the reference update.
1374 // Newly created inset so initialize it.
1375 label_[r]->initView();
1380 InsetMathGrid::doDispatch(cur, cmd);
1384 case LFUN_MATH_EXTERN:
1385 cur.recordUndoInset();
1389 case LFUN_MATH_MUTATE: {
1390 cur.recordUndoInset();
1391 row_type row = cur.row();
1392 col_type col = cur.col();
1393 mutate(hullType(cmd.argument()));
1394 cur.idx() = row * ncols() + col;
1395 if (cur.idx() > cur.lastidx()) {
1396 cur.idx() = cur.lastidx();
1397 cur.pos() = cur.lastpos();
1399 if (cur.pos() > cur.lastpos())
1400 cur.pos() = cur.lastpos();
1402 // FIXME: find some more clever handling of the selection,
1403 // i.e. preserve it.
1404 cur.clearSelection();
1405 //cur.dispatched(FINISHED);
1409 case LFUN_MATH_DISPLAY: {
1410 cur.recordUndoInset();
1411 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1413 cur.pos() = cur.lastpos();
1414 //cur.dispatched(FINISHED);
1419 InsetMathGrid::doDispatch(cur, cmd);
1425 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1426 FuncStatus & status) const
1428 switch (cmd.action) {
1429 case LFUN_FINISHED_BACKWARD:
1430 case LFUN_FINISHED_FORWARD:
1431 case LFUN_FINISHED_RIGHT:
1432 case LFUN_FINISHED_LEFT:
1435 case LFUN_NEWLINE_INSERT:
1436 case LFUN_MATH_EXTERN:
1437 case LFUN_MATH_DISPLAY:
1439 status.setEnabled(true);
1442 case LFUN_MATH_MUTATE: {
1443 HullType ht = hullType(cmd.argument());
1444 status.setOnOff(type_ == ht);
1445 status.setEnabled(true);
1449 case LFUN_MATH_NUMBER_TOGGLE:
1450 // FIXME: what is the right test, this or the one of
1452 status.setEnabled(display());
1453 status.setOnOff(numberedType());
1456 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1457 // FIXME: what is the right test, this or the one of
1459 bool const enable = (type_ == hullMultline)
1460 ? (nrows() - 1 == cur.row())
1461 : display() != Inline && nrows() > 1;
1462 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1463 status.setEnabled(enable);
1464 status.setOnOff(enable && numbered(r));
1468 case LFUN_LABEL_INSERT:
1469 status.setEnabled(type_ != hullSimple);
1472 case LFUN_LABEL_COPY_AS_REF: {
1473 bool enabled = false;
1475 if (cmd.argument().empty() && &cur.inset() == this) {
1476 // if there is no argument and we're inside math, we retrieve
1477 // the row number from the cursor position.
1478 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1479 enabled = numberedType() && label_[row] && !nonum_[row];
1481 // if there is an argument, find the corresponding label, else
1482 // check whether there is at least one label.
1483 for (row_type row = 0; row != nrows(); ++row) {
1484 if (!nonum_[row] && label_[row] &&
1485 (cmd.argument().empty() || label(row) == cmd.argument())) {
1491 status.setEnabled(enabled);
1495 case LFUN_INSET_INSERT:
1496 if (cmd.getArg(0) == "label") {
1497 status.setEnabled(type_ != hullSimple);
1500 return InsetMathGrid::getStatus(cur, cmd, status);
1502 case LFUN_INSET_MODIFY: {
1503 istringstream is(to_utf8(cmd.argument()));
1507 return InsetMathGrid::getStatus(cur, cmd, status);
1510 && (s == "append-row"
1511 || s == "delete-row"
1512 || s == "copy-row")) {
1513 status.message(bformat(
1514 from_utf8(N_("Can't change number of rows in '%1$s'")),
1516 status.setEnabled(false);
1520 && (s == "append-column"
1521 || s == "delete-column"
1522 || s == "copy-column")) {
1523 status.message(bformat(
1524 from_utf8(N_("Can't change number of columns in '%1$s'")),
1526 status.setEnabled(false);
1529 if ((type_ == hullSimple
1530 || type_ == hullEquation
1531 || type_ == hullNone) &&
1532 (s == "add-hline-above" || s == "add-hline-below")) {
1533 status.message(bformat(
1534 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1536 status.setEnabled(false);
1539 if (s == "add-vline-left" || s == "add-vline-right") {
1540 status.message(bformat(
1541 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1543 status.setEnabled(false);
1546 if (s == "valign-top" || s == "valign-middle"
1547 || s == "valign-bottom" || s == "align-left"
1548 || s == "align-center" || s == "align-right") {
1549 status.setEnabled(false);
1552 return InsetMathGrid::getStatus(cur, cmd, status);
1556 return InsetMathGrid::getStatus(cur, cmd, status);
1559 // This cannot really happen, but inserted to shut-up gcc
1560 return InsetMathGrid::getStatus(cur, cmd, status);
1564 /////////////////////////////////////////////////////////////////////
1568 // simply scrap this function if you want
1569 void InsetMathHull::mutateToText()
1572 // translate to latex
1574 latex(os, false, false);
1575 string str = os.str();
1578 Text * lt = view_->cursor().innerText();
1579 string::const_iterator cit = str.begin();
1580 string::const_iterator end = str.end();
1581 for (; cit != end; ++cit)
1582 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1585 //dispatch(LFUN_ESCAPE);
1590 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1591 docstring const & font)
1593 // this whole function is a hack and won't work for incremental font
1596 if (cur.inset().asInsetMath()->name() == font)
1597 cur.handleFont(to_utf8(font));
1599 cur.handleNest(createInsetMath(font, cur.buffer()));
1605 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1610 font.fromString(to_utf8(arg), b);
1611 if (font.fontInfo().color() != Color_inherit) {
1612 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1613 cur.handleNest(at, 0);
1618 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1621 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1622 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1623 enter_front ? idxFirst(cur) : idxLast(cur);
1624 // The inset formula dimension is not necessarily the same as the
1625 // one of the instant preview image, so we have to indicate to the
1626 // BufferView that a metrics update is needed.
1627 cur.updateFlags(Update::Force);
1631 void InsetMathHull::revealCodes(Cursor & cur) const
1633 if (!cur.inMathed())
1635 odocstringstream os;
1637 cur.message(os.str());
1639 // write something to the minibuffer
1640 // translate to latex
1644 string str = os.str();
1646 string::size_type pos = 0;
1648 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1651 else if (*it == '\0') {
1653 pos = it - str.begin();
1659 res = res.substr(pos - 30);
1660 if (res.size() > 60)
1661 res = res.substr(0, 60);
1667 /////////////////////////////////////////////////////////////////////
1671 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1674 // FIXME: completely broken
1675 static InsetMathHull * lastformula = 0;
1676 static CursorBase current = DocIterator(ibegin(nucleus()));
1678 static string laststr;
1680 if (lastformula != this || laststr != str) {
1681 //lyxerr << "reset lastformula to " << this << endl;
1684 current = ibegin(nucleus());
1686 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1690 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1692 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1693 CursorSlice & top = it.back();
1694 MathData const & a = top.asInsetMath()->cell(top.idx_);
1695 if (a.matchpart(ar, top.pos_)) {
1696 bv->cursor().setSelection(it, ar.size());
1698 top.pos_ += ar.size();
1704 //lyxerr << "not found!" << endl;
1711 void InsetMathHull::write(ostream & os) const
1713 odocstringstream oss;
1714 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1717 os << to_utf8(oss.str());
1721 void InsetMathHull::read(Lexer & lex)
1724 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1725 operator=(*at->asHullInset());
1729 bool InsetMathHull::readQuiet(Lexer & lex)
1732 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1734 operator=(*at->asHullInset());
1739 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1741 if (0 && display()) {
1745 TextPainter tpain(dim.width(), dim.height());
1746 drawT(tpain, 0, dim.ascent());
1748 // reset metrics cache to "real" values
1750 return tpain.textheight();
1752 odocstringstream oss;
1753 Encoding const * const enc = encodings.fromLyXName("utf8");
1754 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1756 if (type_ == hullRegexp)
1760 docstring const str = oss.str();
1767 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1772 if (getType() == hullSimple)
1773 name = from_ascii("inlineequation");
1775 name = from_ascii("informalequation");
1777 docstring bname = name;
1778 if (!label(0).empty())
1779 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1781 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1783 odocstringstream ls;
1784 if (runparams.flavor == OutputParams::XML) {
1785 ms << MTag("alt role='tex' ");
1786 // Workaround for db2latex: db2latex always includes equations with
1787 // \ensuremath{} or \begin{display}\end{display}
1788 // so we strip LyX' math environment
1789 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1790 InsetMathGrid::write(wi);
1791 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1796 InsetMathGrid::mathmlize(ms);
1799 ms << MTag("alt role='tex'");
1800 res = latex(ls, runparams);
1801 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1805 ms << from_ascii("<graphic fileref=\"eqn/");
1806 if (!label(0).empty())
1807 ms << sgml::cleanID(buffer(), runparams, label(0));
1809 ms << sgml::uniqueID(from_ascii("anon"));
1811 if (runparams.flavor == OutputParams::XML)
1812 ms << from_ascii("\"/>");
1814 ms << from_ascii("\">");
1816 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1818 return ms.line() + res;
1822 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const &) const
1824 BufferParams::MathOutput mathtype = buffer().params().html_math_output;
1825 // FIXME Eventually we would like to do this inset by inset.
1827 case BufferParams::MathML: {
1828 if (getType() == hullSimple)
1829 xs << html::StartTag("math",
1830 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1832 xs << html::StartTag("math",
1833 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1834 MathStream ms(xs.os());
1835 InsetMathGrid::mathmlize(ms);
1836 xs << html::EndTag("math");
1839 case BufferParams::HTML: {
1840 string tag = (getType() == hullSimple) ? "span" : "div";
1841 xs << html::StartTag(tag, "class='formula'", true);
1842 HtmlStream ms(xs.os());
1843 InsetMathGrid::htmlize(ms);
1844 xs << html::EndTag(tag);
1847 case BufferParams::Images: {
1848 LYXERR0("Image output for math presently unsupported.");
1851 case BufferParams::LaTeX: {
1852 // FIXME Obviously, the only real question is how to wrap this.
1853 LYXERR0("LaTeX output for math presently unsupported.");
1860 void InsetMathHull::tocString(odocstream & os) const
1862 plaintext(os, OutputParams(0));
1866 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1868 return from_ascii("context-math");