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 docstring InsetMathHull::standardColor() const
336 color = from_ascii("foreground");
339 color = from_ascii("foreground");
342 color = from_ascii("math");
348 bool InsetMathHull::previewState(BufferView * bv) const
350 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
351 graphics::PreviewImage const * pimage =
352 preview_->getPreviewImage(bv->buffer());
353 return pimage && pimage->image();
359 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
361 if (previewState(mi.base.bv)) {
362 preview_->metrics(mi, dim);
363 // insert a one pixel gap in front of the formula
366 dim.des += displayMargin();
367 // Cache the inset dimension.
368 setDimCache(mi, dim);
372 FontSetChanger dummy1(mi.base, standardFont());
373 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
375 // let the cells adjust themselves
376 InsetMathGrid::metrics(mi, dim);
379 dim.asc += displayMargin();
380 dim.des += displayMargin();
383 if (numberedType()) {
384 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
386 for (row_type row = 0; row < nrows(); ++row)
387 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
393 // make it at least as high as the current font
396 math_font_max_dim(mi.base.font, asc, des);
397 dim.asc = max(dim.asc, asc);
398 dim.des = max(dim.des, des);
399 // Cache the inset dimension.
400 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
401 setDimCache(mi, dim);
405 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
407 if (previewState(pi.base.bv))
408 return graphics::PreviewLoader::backgroundColor();
413 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
415 Dimension const dim = dimension(*pi.base.bv);
416 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
417 dim.asc + dim.des - 1, pi.backgroundColor(this));
421 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
423 use_preview_ = previewState(pi.base.bv);
425 if (type_ == hullRegexp) {
426 Dimension const dim = dimension(*pi.base.bv);
427 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
428 dim.width() - 2, dim.height() - 2, Color_regexpframe);
431 // one pixel gap in front
432 preview_->draw(pi, x + 1, y);
433 setPosCache(pi, x, y);
437 bool const really_change_color = pi.base.font.color() == Color_none;
438 ColorChanger dummy0(pi.base.font, standardColor(), really_change_color);
439 FontSetChanger dummy1(pi.base, standardFont());
440 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
442 InsetMathGrid::draw(pi, x + 1, y);
444 if (numberedType()) {
445 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
446 for (row_type row = 0; row < nrows(); ++row) {
447 int const yy = y + rowinfo_[row].offset_;
448 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
449 docstring const nl = nicelabel(row);
453 setPosCache(pi, x, y);
457 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
460 InsetMathGrid::metricsT(mi, dim);
463 WriteStream wi(os, false, true, WriteStream::wsDefault);
465 dim.wid = os.str().size();
472 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
475 InsetMathGrid::drawT(pain, x, y);
478 WriteStream wi(os, false, true, WriteStream::wsDefault);
480 pain.draw(x, y, os.str().c_str());
485 static docstring latexString(InsetMathHull const & inset)
488 // This has to be static, because a preview snippet or a math
489 // macro containing math in text mode (such as $\text{$\phi$}$ or
490 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
491 // first time as a whole, and the second time only the inner math.
492 // In this last case inset.buffer() would be invalid.
493 static Encoding const * encoding = 0;
494 if (inset.isBufferValid())
495 encoding = &(inset.buffer().params().encoding());
496 WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
502 void InsetMathHull::initUnicodeMath() const
504 // Trigger classification of the unicode symbols in this inset
505 docstring const dummy = latexString(*this);
509 void InsetMathHull::addPreview(DocIterator const & inset_pos,
510 graphics::PreviewLoader & /*ploader*/) const
512 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
513 preparePreview(inset_pos);
518 void InsetMathHull::preparePreview(DocIterator const & pos) const
520 Buffer const * buffer = pos.buffer();
522 // collect macros at this position
524 buffer->listMacroNames(macros);
525 MacroNameSet::iterator it = macros.begin();
526 MacroNameSet::iterator end = macros.end();
527 odocstringstream macro_preamble;
528 for (; it != end; ++it) {
529 MacroData const * data = buffer->getMacro(*it, pos, true);
531 data->write(macro_preamble, true);
532 macro_preamble << endl;
536 docstring const snippet = macro_preamble.str() + latexString(*this);
537 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
538 preview_->addPreview(snippet, *buffer);
542 void InsetMathHull::reloadPreview(DocIterator const & pos) const
545 preview_->startLoading(*pos.buffer());
549 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
551 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
553 cur.screenUpdateFlags(Update::Force);
559 docstring InsetMathHull::label(row_type row) const
561 LASSERT(row < nrows(), /**/);
562 if (InsetLabel * il = label_[row])
563 return il->screenLabel();
568 void InsetMathHull::label(row_type row, docstring const & label)
570 //lyxerr << "setting label '" << label << "' for row " << row << endl;
574 label_[row] = dummy_pointer;
577 label_[row]->updateCommand(label);
579 label_[row]->setParam("name", label);
583 InsetCommandParams p(LABEL_CODE);
585 label_[row] = new InsetLabel(buffer_, p);
587 label_[row]->setBuffer(buffer());
591 void InsetMathHull::numbered(row_type row, bool num)
594 if (nonum_[row] && label_[row]) {
601 bool InsetMathHull::numbered(row_type row) const
607 bool InsetMathHull::ams() const
609 return type_ == hullAlign
610 || type_ == hullFlAlign
611 || type_ == hullMultline
612 || type_ == hullGather
613 || type_ == hullAlignAt
614 || type_ == hullXAlignAt
615 || type_ == hullXXAlignAt;
619 Inset::DisplayType InsetMathHull::display() const
621 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
626 bool InsetMathHull::numberedType() const
628 if (type_ == hullNone)
630 if (type_ == hullSimple)
632 if (type_ == hullXXAlignAt)
634 if (type_ == hullRegexp)
636 for (row_type row = 0; row < nrows(); ++row)
643 void InsetMathHull::validate(LaTeXFeatures & features) const
645 if (features.runparams().isLaTeX()) {
647 features.require("amsmath");
649 if (type_ == hullRegexp) {
650 features.require("color");
651 string frcol = lcolor.getLaTeXName(Color_regexpframe);
652 string bgcol = "white";
653 features.addPreambleSnippet(
654 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
655 + frcol + string("}{")
656 + bgcol + string("}{\\texttt{#1}}}"));
659 // Validation is necessary only if not using AMS math.
660 // To be safe, we will always run mathedvalidate.
661 //if (features.amsstyle)
664 //features.binom = true;
665 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
666 // it would be better to do this elsewhere, but we can't validate in
667 // InsetMathMatrix and we have no way, outside MathExtern, to know if
668 // we even have any matrices.
669 features.addPreambleSnippet("<style type=\"text/css\">\n"
670 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
671 "table.matrix td{padding: 0.25px;}\n"
672 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
673 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}\n"
676 InsetMathGrid::validate(features);
680 void InsetMathHull::header_write(WriteStream & os) const
682 bool n = numberedType();
696 os << "\\begin{equation" << star(n) << "}\n";
706 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
711 os << "\\begin{" << hullName(type_) << star(n) << '}'
712 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
716 os << "\\begin{" << hullName(type_) << '}'
717 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
725 os << "\\begin{unknown" << star(n) << '}';
731 void InsetMathHull::footer_write(WriteStream & os) const
733 bool n = numberedType();
746 os << "\\end{equation" << star(n) << "}\n";
758 os << "\\end{" << hullName(type_) << star(n) << "}\n";
762 os << "\\end{" << hullName(type_) << "}\n";
770 os << "\\end{unknown" << star(n) << '}';
776 bool InsetMathHull::rowChangeOK() const
779 type_ == hullEqnArray || type_ == hullAlign ||
780 type_ == hullFlAlign || type_ == hullAlignAt ||
781 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
782 type_ == hullGather || type_ == hullMultline;
786 bool InsetMathHull::colChangeOK() const
789 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
790 type_ == hullXAlignAt || type_ == hullXXAlignAt;
794 void InsetMathHull::addRow(row_type row)
799 bool numbered = numberedType();
801 if (type_ == hullMultline) {
802 if (row + 1 == nrows()) {
809 nonum_.insert(nonum_.begin() + row + 1, !numbered);
810 label_.insert(label_.begin() + row + 1, dummy_pointer);
813 InsetMathGrid::addRow(row);
817 void InsetMathHull::swapRow(row_type row)
821 if (row + 1 == nrows())
823 // gcc implements the standard std::vector<bool> which is *not* a container:
824 // http://www.gotw.ca/publications/N1185.pdf
825 // As a results, it doesn't like this:
826 // swap(nonum_[row], nonum_[row + 1]);
827 // so we do it manually:
828 bool const b = nonum_[row];
829 nonum_[row] = nonum_[row + 1];
831 swap(label_[row], label_[row + 1]);
832 InsetMathGrid::swapRow(row);
836 void InsetMathHull::delRow(row_type row)
838 if (nrows() <= 1 || !rowChangeOK())
840 if (row + 1 == nrows() && type_ == hullMultline) {
841 bool const b = nonum_[row - 1];
842 nonum_[row - 1] = nonum_[row];
844 swap(label_[row - 1], label_[row]);
845 InsetMathGrid::delRow(row);
848 InsetMathGrid::delRow(row);
849 // The last dummy row has no number info nor a label.
850 // Test nrows() + 1 because we have already erased the row.
851 if (row == nrows() + 1)
853 nonum_.erase(nonum_.begin() + row);
855 label_.erase(label_.begin() + row);
859 void InsetMathHull::addCol(col_type col)
863 InsetMathGrid::addCol(col);
867 void InsetMathHull::delCol(col_type col)
869 if (ncols() <= 1 || !colChangeOK())
871 InsetMathGrid::delCol(col);
875 docstring InsetMathHull::nicelabel(row_type row) const
880 return from_ascii("(#)");
881 return '(' + label_[row]->screenLabel() + from_ascii(", #)");
885 void InsetMathHull::glueall()
888 for (idx_type i = 0; i < nargs(); ++i)
890 *this = InsetMathHull(buffer_, hullSimple);
896 void InsetMathHull::splitTo2Cols()
898 LASSERT(ncols() == 1, /**/);
899 InsetMathGrid::addCol(1);
900 for (row_type row = 0; row < nrows(); ++row) {
901 idx_type const i = 2 * row;
902 pos_type pos = firstRelOp(cell(i));
903 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
904 cell(i).erase(pos, cell(i).size());
909 void InsetMathHull::splitTo3Cols()
911 LASSERT(ncols() < 3, /**/);
914 InsetMathGrid::addCol(2);
915 for (row_type row = 0; row < nrows(); ++row) {
916 idx_type const i = 3 * row + 1;
917 if (cell(i).size()) {
918 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
919 cell(i).erase(1, cell(i).size());
925 void InsetMathHull::changeCols(col_type cols)
929 else if (ncols() < cols) {
935 while (ncols() < cols)
936 InsetMathGrid::addCol(ncols());
942 for (row_type row = 0; row < nrows(); ++row) {
943 idx_type const i = row * ncols();
944 for (col_type col = cols; col < ncols(); ++col) {
945 cell(i + cols - 1).append(cell(i + col));
949 while (ncols() > cols) {
950 InsetMathGrid::delCol(ncols() - 1);
955 HullType InsetMathHull::getType() const
961 void InsetMathHull::setType(HullType type)
968 void InsetMathHull::mutate(HullType newtype)
970 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
972 // we try to move along the chain
973 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
975 // +-------------------------------------+
976 // we use eqnarray as intermediate type for mutations that are not
977 // directly supported because it handles labels and numbering for
980 if (newtype == type_) {
984 else if (newtype < hullNone) {
989 else if (type_ == hullNone) {
995 else if (type_ == hullSimple) {
996 if (newtype == hullNone) {
1000 setType(hullEquation);
1006 else if (type_ == hullEquation) {
1007 if (newtype < type_) {
1008 setType(hullSimple);
1011 } else if (newtype == hullEqnArray) {
1012 // split it "nicely" on the first relop
1014 setType(hullEqnArray);
1015 } else if (newtype == hullMultline || newtype == hullGather) {
1018 // split it "nicely"
1025 else if (type_ == hullEqnArray) {
1026 if (newtype < type_) {
1027 // set correct (no)numbering
1029 for (row_type row = 0; row < nrows(); ++row) {
1036 // set first non-empty label
1037 for (row_type row = 0; row < nrows(); ++row) {
1039 label_[0] = label_[row];
1046 } else { // align & Co.
1053 else if (type_ == hullAlign || type_ == hullAlignAt ||
1054 type_ == hullXAlignAt || type_ == hullFlAlign) {
1055 if (newtype < hullAlign) {
1057 setType(hullEqnArray);
1059 } else if (newtype == hullGather || newtype == hullMultline) {
1062 } else if (newtype == hullXXAlignAt) {
1063 for (row_type row = 0; row < nrows(); ++row)
1064 numbered(row, false);
1071 else if (type_ == hullXXAlignAt) {
1072 for (row_type row = 0; row < nrows(); ++row)
1073 numbered(row, false);
1074 if (newtype < hullAlign) {
1076 setType(hullEqnArray);
1078 } else if (newtype == hullGather || newtype == hullMultline) {
1086 else if (type_ == hullMultline || type_ == hullGather) {
1087 if (newtype == hullGather || newtype == hullMultline)
1089 else if (newtype == hullAlign || newtype == hullFlAlign ||
1090 newtype == hullAlignAt || newtype == hullXAlignAt) {
1093 } else if (newtype == hullXXAlignAt) {
1095 for (row_type row = 0; row < nrows(); ++row)
1096 numbered(row, false);
1100 setType(hullEqnArray);
1106 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1107 << "' to '" << to_utf8(hullName(newtype))
1108 << "' not implemented" << endl;
1113 docstring InsetMathHull::eolString(row_type row, bool fragile, bool last_eoln) const
1116 if (numberedType()) {
1117 if (label_[row] && !nonum_[row])
1119 escape(label_[row]->getParam("name")) + '}';
1120 if (nonum_[row] && (type_ != hullMultline))
1121 res += "\\nonumber ";
1123 // Never add \\ on the last empty line of eqnarray and friends
1125 return res + InsetMathGrid::eolString(row, fragile, last_eoln);
1129 void InsetMathHull::write(WriteStream & os) const
1131 ModeSpecifier specifier(os, MATH_MODE);
1133 InsetMathGrid::write(os);
1138 void InsetMathHull::normalize(NormalStream & os) const
1140 os << "[formula " << hullName(type_) << ' ';
1141 InsetMathGrid::normalize(os);
1146 void InsetMathHull::mathmlize(MathStream & os) const
1148 InsetMathGrid::mathmlize(os);
1152 void InsetMathHull::infoize(odocstream & os) const
1154 os << "Type: " << hullName(type_);
1158 void InsetMathHull::check() const
1160 LASSERT(nonum_.size() == nrows(), /**/);
1161 LASSERT(label_.size() == nrows(), /**/);
1165 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1169 idocstringstream iss(func.argument());
1170 iss >> dlang >> extra;
1172 extra = from_ascii("noextra");
1173 string const lang = to_ascii(dlang);
1175 // FIXME: temporarily disabled
1176 //if (cur.selection()) {
1179 // lyxerr << "use selection: " << ar << endl;
1180 // insert(pipeThroughExtern(lang, extra, ar));
1185 eq.push_back(MathAtom(new InsetMathChar('=')));
1187 // go to first item in line
1188 cur.idx() -= cur.idx() % ncols();
1191 if (getType() == hullSimple) {
1192 size_type pos = cur.cell().find_last(eq);
1194 if (cur.inMathed() && cur.selection()) {
1195 asArray(grabAndEraseSelection(cur), ar);
1196 } else if (pos == cur.cell().size()) {
1198 lyxerr << "use whole cell: " << ar << endl;
1200 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1201 lyxerr << "use partial cell form pos: " << pos << endl;
1203 cur.cell().append(eq);
1204 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1205 cur.pos() = cur.lastpos();
1209 if (getType() == hullEquation) {
1210 lyxerr << "use equation inset" << endl;
1211 mutate(hullEqnArray);
1212 MathData & ar = cur.cell();
1213 lyxerr << "use cell: " << ar << endl;
1217 cur.cell() = pipeThroughExtern(lang, extra, ar);
1218 // move to end of line
1219 cur.pos() = cur.lastpos();
1224 lyxerr << "use eqnarray" << endl;
1225 cur.idx() += 2 - cur.idx() % ncols();
1227 MathData ar = cur.cell();
1228 lyxerr << "use cell: " << ar << endl;
1229 // FIXME: temporarily disabled
1235 cur.cell() = pipeThroughExtern(lang, extra, ar);
1236 cur.pos() = cur.lastpos();
1241 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1243 //lyxerr << "action: " << cmd.action() << endl;
1244 switch (cmd.action()) {
1246 case LFUN_FINISHED_BACKWARD:
1247 case LFUN_FINISHED_FORWARD:
1248 case LFUN_FINISHED_RIGHT:
1249 case LFUN_FINISHED_LEFT:
1250 //lyxerr << "action: " << cmd.action() << endl;
1251 InsetMathGrid::doDispatch(cur, cmd);
1255 case LFUN_BREAK_PARAGRAPH:
1256 // just swallow this
1259 case LFUN_NEWLINE_INSERT:
1260 // some magic for the common case
1261 if (type_ == hullSimple || type_ == hullEquation) {
1262 cur.recordUndoInset();
1264 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1265 mutate(align ? hullAlign : hullEqnArray);
1266 // mutate() may change labels and such.
1267 cur.forceBufferUpdate();
1268 cur.idx() = nrows() * ncols() - 1;
1269 cur.pos() = cur.lastpos();
1271 InsetMathGrid::doDispatch(cur, cmd);
1274 case LFUN_MATH_NUMBER_TOGGLE: {
1275 //lyxerr << "toggling all numbers" << endl;
1276 cur.recordUndoInset();
1277 bool old = numberedType();
1278 if (type_ == hullMultline)
1279 numbered(nrows() - 1, !old);
1281 for (row_type row = 0; row < nrows(); ++row)
1282 numbered(row, !old);
1284 cur.message(old ? _("No number") : _("Number"));
1285 cur.forceBufferUpdate();
1289 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1290 cur.recordUndoInset();
1291 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1292 bool old = numbered(r);
1293 cur.message(old ? _("No number") : _("Number"));
1295 cur.forceBufferUpdate();
1299 case LFUN_LABEL_INSERT: {
1300 cur.recordUndoInset();
1301 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1302 docstring old_label = label(r);
1304 // Allow customization of this separator
1305 docstring const default_label = from_ascii("eq:");
1306 if (old_label.empty())
1307 old_label = default_label;
1309 InsetCommandParams p(LABEL_CODE);
1310 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1311 string const data = InsetCommand::params2string("label", p);
1313 if (cmd.argument().empty())
1314 cur.bv().showDialog("label", data);
1316 FuncRequest fr(LFUN_INSET_INSERT, data);
1322 case LFUN_LABEL_COPY_AS_REF: {
1324 if (cmd.argument().empty() && &cur.inset() == this)
1325 // if there is no argument and we're inside math, we retrieve
1326 // the row number from the cursor position.
1327 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1329 // if there is an argument, find the corresponding label, else
1330 // check whether there is at least one label.
1331 for (row = 0; row != nrows(); ++row)
1332 if (!nonum_[row] && label_[row]
1333 && (cmd.argument().empty() || label(row) == cmd.argument()))
1340 InsetCommandParams p(REF_CODE, "ref");
1341 p["reference"] = label(row);
1342 cap::clearSelection();
1343 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1347 case LFUN_WORD_DELETE_FORWARD:
1348 case LFUN_CHAR_DELETE_FORWARD:
1349 if (col(cur.idx()) + 1 == ncols()
1350 && cur.pos() == cur.lastpos()
1351 && !cur.selection()) {
1352 if (!label(row(cur.idx())).empty()) {
1353 cur.recordUndoInset();
1354 label(row(cur.idx()), docstring());
1355 } else if (numbered(row(cur.idx()))) {
1356 cur.recordUndoInset();
1357 numbered(row(cur.idx()), false);
1358 cur.forceBufferUpdate();
1360 InsetMathGrid::doDispatch(cur, cmd);
1364 InsetMathGrid::doDispatch(cur, cmd);
1369 case LFUN_INSET_INSERT: {
1370 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1371 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1372 string const name = cmd.getArg(0);
1373 if (name == "label") {
1374 InsetCommandParams p(LABEL_CODE);
1375 InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1376 docstring str = p["name"];
1377 cur.recordUndoInset();
1378 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1382 docstring old = label(r);
1385 // The label will take care of the reference update.
1389 // Newly created inset so initialize it.
1390 label_[r]->initView();
1393 cur.forceBufferUpdate();
1396 InsetMathGrid::doDispatch(cur, cmd);
1400 case LFUN_MATH_EXTERN:
1401 cur.recordUndoInset();
1405 case LFUN_MATH_MUTATE: {
1406 cur.recordUndoInset();
1407 row_type row = cur.row();
1408 col_type col = cur.col();
1409 mutate(hullType(cmd.argument()));
1410 cur.idx() = row * ncols() + col;
1411 if (cur.idx() > cur.lastidx()) {
1412 cur.idx() = cur.lastidx();
1413 cur.pos() = cur.lastpos();
1415 if (cur.pos() > cur.lastpos())
1416 cur.pos() = cur.lastpos();
1418 cur.forceBufferUpdate();
1419 // FIXME: find some more clever handling of the selection,
1420 // i.e. preserve it.
1421 cur.clearSelection();
1422 //cur.dispatched(FINISHED);
1426 case LFUN_MATH_DISPLAY: {
1427 cur.recordUndoInset();
1428 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1430 cur.pos() = cur.lastpos();
1431 //cur.dispatched(FINISHED);
1436 InsetMathGrid::doDispatch(cur, cmd);
1442 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1443 FuncStatus & status) const
1445 switch (cmd.action()) {
1446 case LFUN_FINISHED_BACKWARD:
1447 case LFUN_FINISHED_FORWARD:
1448 case LFUN_FINISHED_RIGHT:
1449 case LFUN_FINISHED_LEFT:
1452 case LFUN_NEWLINE_INSERT:
1453 case LFUN_MATH_EXTERN:
1454 case LFUN_MATH_DISPLAY:
1456 status.setEnabled(true);
1459 case LFUN_MATH_MUTATE: {
1460 HullType ht = hullType(cmd.argument());
1461 status.setOnOff(type_ == ht);
1462 status.setEnabled(true);
1466 case LFUN_MATH_NUMBER_TOGGLE:
1467 // FIXME: what is the right test, this or the one of
1469 status.setEnabled(display() != Inline);
1470 status.setOnOff(numberedType());
1473 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1474 // FIXME: what is the right test, this or the one of
1476 bool const enable = (type_ == hullMultline)
1477 ? (nrows() - 1 == cur.row())
1478 : display() != Inline && nrows() > 1;
1479 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1480 status.setEnabled(enable);
1481 status.setOnOff(enable && numbered(r));
1485 case LFUN_LABEL_INSERT:
1486 status.setEnabled(type_ != hullSimple);
1489 case LFUN_LABEL_COPY_AS_REF: {
1490 bool enabled = false;
1492 if (cmd.argument().empty() && &cur.inset() == this) {
1493 // if there is no argument and we're inside math, we retrieve
1494 // the row number from the cursor position.
1495 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1496 enabled = numberedType() && label_[row] && !nonum_[row];
1498 // if there is an argument, find the corresponding label, else
1499 // check whether there is at least one label.
1500 for (row_type row = 0; row != nrows(); ++row) {
1501 if (!nonum_[row] && label_[row] &&
1502 (cmd.argument().empty() || label(row) == cmd.argument())) {
1508 status.setEnabled(enabled);
1512 case LFUN_INSET_INSERT:
1513 if (cmd.getArg(0) == "label") {
1514 status.setEnabled(type_ != hullSimple);
1517 return InsetMathGrid::getStatus(cur, cmd, status);
1519 case LFUN_INSET_MODIFY: {
1520 istringstream is(to_utf8(cmd.argument()));
1524 return InsetMathGrid::getStatus(cur, cmd, status);
1527 && (s == "append-row"
1528 || s == "delete-row"
1529 || s == "copy-row")) {
1530 status.message(bformat(
1531 from_utf8(N_("Can't change number of rows in '%1$s'")),
1533 status.setEnabled(false);
1537 && (s == "append-column"
1538 || s == "delete-column"
1539 || s == "copy-column")) {
1540 status.message(bformat(
1541 from_utf8(N_("Can't change number of columns in '%1$s'")),
1543 status.setEnabled(false);
1546 if ((type_ == hullSimple
1547 || type_ == hullEquation
1548 || type_ == hullNone) &&
1549 (s == "add-hline-above" || s == "add-hline-below")) {
1550 status.message(bformat(
1551 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1553 status.setEnabled(false);
1556 if (s == "add-vline-left" || s == "add-vline-right") {
1557 status.message(bformat(
1558 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1560 status.setEnabled(false);
1563 if (s == "valign-top" || s == "valign-middle"
1564 || s == "valign-bottom" || s == "align-left"
1565 || s == "align-center" || s == "align-right") {
1566 status.setEnabled(false);
1569 return InsetMathGrid::getStatus(cur, cmd, status);
1573 return InsetMathGrid::getStatus(cur, cmd, status);
1576 // This cannot really happen, but inserted to shut-up gcc
1577 return InsetMathGrid::getStatus(cur, cmd, status);
1581 /////////////////////////////////////////////////////////////////////
1585 // simply scrap this function if you want
1586 void InsetMathHull::mutateToText()
1589 // translate to latex
1591 latex(os, false, false);
1592 string str = os.str();
1595 Text * lt = view_->cursor().innerText();
1596 string::const_iterator cit = str.begin();
1597 string::const_iterator end = str.end();
1598 for (; cit != end; ++cit)
1599 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1602 //dispatch(LFUN_ESCAPE);
1607 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1608 docstring const & font)
1610 // this whole function is a hack and won't work for incremental font
1613 if (cur.inset().asInsetMath()->name() == font)
1614 cur.handleFont(to_utf8(font));
1616 cur.handleNest(createInsetMath(font, cur.buffer()));
1622 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1627 font.fromString(to_utf8(arg), b);
1628 if (font.fontInfo().color() != Color_inherit) {
1629 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1630 cur.handleNest(at, 0);
1635 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1638 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1639 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1640 enter_front ? idxFirst(cur) : idxLast(cur);
1641 // The inset formula dimension is not necessarily the same as the
1642 // one of the instant preview image, so we have to indicate to the
1643 // BufferView that a metrics update is needed.
1644 cur.screenUpdateFlags(Update::Force);
1648 void InsetMathHull::revealCodes(Cursor & cur) const
1650 if (!cur.inMathed())
1652 odocstringstream os;
1654 cur.message(os.str());
1656 // write something to the minibuffer
1657 // translate to latex
1661 string str = os.str();
1663 string::size_type pos = 0;
1665 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1668 else if (*it == '\0') {
1670 pos = it - str.begin();
1676 res = res.substr(pos - 30);
1677 if (res.size() > 60)
1678 res = res.substr(0, 60);
1684 /////////////////////////////////////////////////////////////////////
1688 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1691 // FIXME: completely broken
1692 static InsetMathHull * lastformula = 0;
1693 static CursorBase current = DocIterator(ibegin(nucleus()));
1695 static string laststr;
1697 if (lastformula != this || laststr != str) {
1698 //lyxerr << "reset lastformula to " << this << endl;
1701 current = ibegin(nucleus());
1703 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1707 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1709 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1710 CursorSlice & top = it.back();
1711 MathData const & a = top.asInsetMath()->cell(top.idx_);
1712 if (a.matchpart(ar, top.pos_)) {
1713 bv->cursor().setSelection(it, ar.size());
1715 top.pos_ += ar.size();
1721 //lyxerr << "not found!" << endl;
1728 void InsetMathHull::write(ostream & os) const
1730 odocstringstream oss;
1731 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1734 os << to_utf8(oss.str());
1738 void InsetMathHull::read(Lexer & lex)
1741 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1742 operator=(*at->asHullInset());
1746 bool InsetMathHull::readQuiet(Lexer & lex)
1749 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1751 operator=(*at->asHullInset());
1756 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1758 // disables ASCII-art for export of equations. See #2275.
1759 if (0 && display()) {
1763 TextPainter tpain(dim.width(), dim.height());
1764 drawT(tpain, 0, dim.ascent());
1766 // reset metrics cache to "real" values
1768 return tpain.textheight();
1770 odocstringstream oss;
1771 Encoding const * const enc = encodings.fromLyXName("utf8");
1772 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1774 if (type_ == hullRegexp)
1778 docstring const str = oss.str();
1785 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1790 if (getType() == hullSimple)
1791 name = from_ascii("inlineequation");
1793 name = from_ascii("informalequation");
1795 docstring bname = name;
1796 if (!label(0).empty())
1797 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1799 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1801 odocstringstream ls;
1802 if (runparams.flavor == OutputParams::XML) {
1803 ms << MTag("alt role='tex' ");
1804 // Workaround for db2latex: db2latex always includes equations with
1805 // \ensuremath{} or \begin{display}\end{display}
1806 // so we strip LyX' math environment
1807 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1808 InsetMathGrid::write(wi);
1809 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1814 InsetMathGrid::mathmlize(ms);
1817 ms << MTag("alt role='tex'");
1818 res = latex(ls, runparams);
1819 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1823 ms << from_ascii("<graphic fileref=\"eqn/");
1824 if (!label(0).empty())
1825 ms << sgml::cleanID(buffer(), runparams, label(0));
1827 ms << sgml::uniqueID(from_ascii("anon"));
1829 if (runparams.flavor == OutputParams::XML)
1830 ms << from_ascii("\"/>");
1832 ms << from_ascii("\">");
1834 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1836 return ms.line() + res;
1840 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const &) const
1842 BufferParams::MathOutput mathtype = buffer().params().html_math_output;
1843 // FIXME Eventually we would like to do this inset by inset.
1845 case BufferParams::MathML: {
1846 if (getType() == hullSimple)
1847 xs << html::StartTag("math",
1848 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1850 xs << html::StartTag("math",
1851 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1852 MathStream ms(xs.os());
1853 InsetMathGrid::mathmlize(ms);
1854 xs << html::EndTag("math");
1857 case BufferParams::HTML: {
1858 string tag = (getType() == hullSimple) ? "span" : "div";
1859 xs << html::StartTag(tag, "class='formula'", true);
1860 HtmlStream ms(xs.os());
1861 InsetMathGrid::htmlize(ms);
1862 xs << html::EndTag(tag);
1865 case BufferParams::Images: {
1866 LYXERR0("Image output for math presently unsupported.");
1869 case BufferParams::LaTeX: {
1870 // FIXME Obviously, the only real question is how to wrap this.
1871 LYXERR0("LaTeX output for math presently unsupported.");
1878 void InsetMathHull::tocString(odocstream & os) const
1880 plaintext(os, OutputParams(0));
1884 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1886 return from_ascii("context-math");