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"
29 #include "FuncRequest.h"
30 #include "FuncStatus.h"
31 #include "LaTeXFeatures.h"
33 #include "MacroTable.h"
34 #include "output_xhtml.h"
36 #include "TextPainter.h"
37 #include "TocBackend.h"
39 #include "insets/InsetLabel.h"
40 #include "insets/InsetRef.h"
41 #include "insets/RenderPreview.h"
43 #include "graphics/PreviewImage.h"
44 #include "graphics/PreviewLoader.h"
46 #include "frontends/Painter.h"
48 #include "support/lassert.h"
49 #include "support/debug.h"
50 #include "support/gettext.h"
51 #include "support/lstrings.h"
56 using namespace lyx::support;
60 using cap::grabAndEraseSelection;
64 int getCols(HullType type)
81 // returns position of first relation operator in the array
82 // used for "intelligent splitting"
83 size_t firstRelOp(MathData const & ar)
85 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
87 return it - ar.begin();
92 char const * star(bool numbered)
94 return numbered ? "" : "*";
98 } // end anon namespace
101 HullType hullType(docstring const & s)
103 if (s == "none") return hullNone;
104 if (s == "simple") return hullSimple;
105 if (s == "equation") return hullEquation;
106 if (s == "eqnarray") return hullEqnArray;
107 if (s == "align") return hullAlign;
108 if (s == "alignat") return hullAlignAt;
109 if (s == "xalignat") return hullXAlignAt;
110 if (s == "xxalignat") return hullXXAlignAt;
111 if (s == "multline") return hullMultline;
112 if (s == "gather") return hullGather;
113 if (s == "flalign") return hullFlAlign;
114 if (s == "regexp") return hullRegexp;
115 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
120 docstring hullName(HullType type)
123 case hullNone: return from_ascii("none");
124 case hullSimple: return from_ascii("simple");
125 case hullEquation: return from_ascii("equation");
126 case hullEqnArray: return from_ascii("eqnarray");
127 case hullAlign: return from_ascii("align");
128 case hullAlignAt: return from_ascii("alignat");
129 case hullXAlignAt: return from_ascii("xalignat");
130 case hullXXAlignAt: return from_ascii("xxalignat");
131 case hullMultline: return from_ascii("multline");
132 case hullGather: return from_ascii("gather");
133 case hullFlAlign: return from_ascii("flalign");
134 case hullRegexp: return from_ascii("regexp");
136 lyxerr << "unknown hull type '" << type << "'" << endl;
137 return from_ascii("none");
141 static InsetLabel * dummy_pointer = 0;
143 InsetMathHull::InsetMathHull(Buffer * buf)
144 : InsetMathGrid(buf, 1, 1), type_(hullNone), nonum_(1, false),
145 label_(1, dummy_pointer), preview_(new RenderPreview(this))
147 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
148 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
149 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
150 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
157 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
158 : InsetMathGrid(buf, getCols(type), 1), type_(type), nonum_(1, false),
159 label_(1, dummy_pointer), preview_(new RenderPreview(this))
167 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
173 InsetMathHull::~InsetMathHull()
175 for (size_t i = 0; i < label_.size(); ++i)
180 Inset * InsetMathHull::clone() const
182 return new InsetMathHull(*this);
186 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
190 InsetMathGrid::operator=(other);
192 nonum_ = other.nonum_;
193 buffer_ = other.buffer_;
194 for (size_t i = 0; i < label_.size(); ++i)
196 label_ = other.label_;
197 for (size_t i = 0; i != label_.size(); ++i) {
199 label_[i] = new InsetLabel(*label_[i]);
201 preview_.reset(new RenderPreview(*other.preview_, this));
207 void InsetMathHull::setBuffer(Buffer & buffer)
209 InsetMathGrid::setBuffer(buffer);
211 for (size_t i = 0; i != label_.size(); ++i) {
213 label_[i]->setBuffer(buffer);
218 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
221 //FIXME: buffer_ should be set at creation for this inset! Problem is
222 // This inset is created at too many places (see Parser::parse1() in
226 for (size_t i = 0; i != label_.size(); ++i) {
228 label_[i]->updateBuffer(it, utype);
231 InsetMathGrid::updateBuffer(it, utype);
235 void InsetMathHull::addToToc(DocIterator const & pit)
238 //FIXME: buffer_ should be set at creation for this inset! Problem is
239 // This inset is created at too many places (see Parser::parse1() in
244 Toc & toc = buffer().tocBackend().toc("equation");
246 for (row_type row = 0; row != nrows(); ++row) {
250 label_[row]->addToToc(pit);
251 toc.push_back(TocItem(pit, 0, nicelabel(row)));
256 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
262 return InsetMathNest::editXY(cur, x, y);
266 InsetMath::mode_type InsetMathHull::currentMode() const
268 if (type_ == hullNone)
269 return UNDECIDED_MODE;
270 // definitely math mode ...
275 bool InsetMathHull::idxFirst(Cursor & cur) const
283 bool InsetMathHull::idxLast(Cursor & cur) const
285 cur.idx() = nargs() - 1;
286 cur.pos() = cur.lastpos();
291 char InsetMathHull::defaultColAlign(col_type col)
293 if (type_ == hullEqnArray)
295 if (type_ == hullGather)
297 if (type_ >= hullAlign)
298 return "rl"[col & 1];
303 int InsetMathHull::defaultColSpace(col_type col)
305 if (type_ == hullAlign || type_ == hullAlignAt)
307 if (type_ == hullXAlignAt)
308 return (col & 1) ? 20 : 0;
309 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
310 return (col & 1) ? 40 : 0;
315 docstring InsetMathHull::standardFont() const
320 font_name = from_ascii("texttt");
323 font_name = from_ascii("lyxnochange");
326 font_name = from_ascii("mathnormal");
332 docstring InsetMathHull::standardColor() const
337 color = from_ascii("foreground");
340 color = from_ascii("foreground");
343 color = from_ascii("math");
349 bool InsetMathHull::previewState(BufferView * bv) const
351 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
352 graphics::PreviewImage const * pimage =
353 preview_->getPreviewImage(bv->buffer());
354 return pimage && pimage->image();
360 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
362 if (previewState(mi.base.bv)) {
363 preview_->metrics(mi, dim);
364 // insert a one pixel gap in front of the formula
367 dim.des += displayMargin();
368 // Cache the inset dimension.
369 setDimCache(mi, dim);
373 FontSetChanger dummy1(mi.base, standardFont());
374 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
376 // let the cells adjust themselves
377 InsetMathGrid::metrics(mi, dim);
380 dim.asc += displayMargin();
381 dim.des += displayMargin();
384 if (numberedType()) {
385 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
387 for (row_type row = 0; row < nrows(); ++row)
388 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
394 // make it at least as high as the current font
397 math_font_max_dim(mi.base.font, asc, des);
398 dim.asc = max(dim.asc, asc);
399 dim.des = max(dim.des, des);
400 // Cache the inset dimension.
401 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
402 setDimCache(mi, dim);
406 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
408 if (previewState(pi.base.bv))
409 return graphics::PreviewLoader::backgroundColor();
414 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
416 Dimension const dim = dimension(*pi.base.bv);
417 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
418 dim.asc + dim.des - 1, pi.backgroundColor(this));
422 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
424 use_preview_ = previewState(pi.base.bv);
426 if (type_ == hullRegexp) {
427 Dimension const dim = dimension(*pi.base.bv);
428 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
429 dim.width() - 2, dim.height() - 2, Color_regexpframe);
432 // one pixel gap in front
433 preview_->draw(pi, x + 1, y);
434 setPosCache(pi, x, y);
438 bool const really_change_color = pi.base.font.color() == Color_none;
439 ColorChanger dummy0(pi.base.font, standardColor(), really_change_color);
440 FontSetChanger dummy1(pi.base, standardFont());
441 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
443 InsetMathGrid::draw(pi, x + 1, y);
445 if (numberedType()) {
446 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
447 for (row_type row = 0; row < nrows(); ++row) {
448 int const yy = y + rowinfo_[row].offset_;
449 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
450 docstring const nl = nicelabel(row);
454 setPosCache(pi, x, y);
458 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
461 InsetMathGrid::metricsT(mi, dim);
464 WriteStream wi(os, false, true, WriteStream::wsDefault);
466 dim.wid = os.str().size();
473 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
476 InsetMathGrid::drawT(pain, x, y);
479 WriteStream wi(os, false, true, WriteStream::wsDefault);
481 pain.draw(x, y, os.str().c_str());
486 static docstring latexString(InsetMathHull const & inset,
487 bool do_header = true)
490 // This has to be static, because a preview snippet or a math
491 // macro containing math in text mode (such as $\text{$\phi$}$ or
492 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
493 // first time as a whole, and the second time only the inner math.
494 // In this last case inset.buffer() would be invalid.
495 static Encoding const * encoding = 0;
496 if (inset.isBufferValid())
497 encoding = &(inset.buffer().params().encoding());
498 WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
499 inset.write(wi, do_header);
504 void InsetMathHull::initUnicodeMath() const
506 // Trigger classification of the unicode symbols in this inset
507 docstring const dummy = latexString(*this);
511 void InsetMathHull::addPreview(DocIterator const & inset_pos,
512 graphics::PreviewLoader & /*ploader*/) const
514 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
515 preparePreview(inset_pos);
520 void InsetMathHull::preparePreview(DocIterator const & pos) const
522 Buffer const * buffer = pos.buffer();
524 // collect macros at this position
526 buffer->listMacroNames(macros);
527 MacroNameSet::iterator it = macros.begin();
528 MacroNameSet::iterator end = macros.end();
529 odocstringstream macro_preamble;
530 for (; it != end; ++it) {
531 MacroData const * data = buffer->getMacro(*it, pos, true);
533 data->write(macro_preamble, true);
534 macro_preamble << endl;
538 docstring const snippet = macro_preamble.str() + latexString(*this);
539 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
540 preview_->addPreview(snippet, *buffer);
544 void InsetMathHull::reloadPreview(DocIterator const & pos, bool wait) const
547 preview_->startLoading(*pos.buffer(), wait);
551 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
553 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
555 cur.screenUpdateFlags(Update::Force);
561 docstring InsetMathHull::label(row_type row) const
563 LASSERT(row < nrows(), /**/);
564 if (InsetLabel * il = label_[row])
565 return il->screenLabel();
570 void InsetMathHull::label(row_type row, docstring const & label)
572 //lyxerr << "setting label '" << label << "' for row " << row << endl;
576 label_[row] = dummy_pointer;
579 label_[row]->updateCommand(label);
581 label_[row]->setParam("name", label);
585 InsetCommandParams p(LABEL_CODE);
587 label_[row] = new InsetLabel(buffer_, p);
589 label_[row]->setBuffer(buffer());
593 void InsetMathHull::numbered(row_type row, bool num)
596 if (nonum_[row] && label_[row]) {
603 bool InsetMathHull::numbered(row_type row) const
609 bool InsetMathHull::ams() const
611 return type_ == hullAlign
612 || type_ == hullFlAlign
613 || type_ == hullMultline
614 || type_ == hullGather
615 || type_ == hullAlignAt
616 || type_ == hullXAlignAt
617 || type_ == hullXXAlignAt;
621 Inset::DisplayType InsetMathHull::display() const
623 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
628 bool InsetMathHull::numberedType() const
630 if (type_ == hullNone)
632 if (type_ == hullSimple)
634 if (type_ == hullXXAlignAt)
636 if (type_ == hullRegexp)
638 for (row_type row = 0; row < nrows(); ++row)
645 void InsetMathHull::validate(LaTeXFeatures & features) const
647 if (features.runparams().isLaTeX()) {
649 features.require("amsmath");
651 if (type_ == hullRegexp) {
652 features.require("color");
653 string frcol = lcolor.getLaTeXName(Color_regexpframe);
654 string bgcol = "white";
655 features.addPreambleSnippet(
656 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
657 + frcol + string("}{")
658 + bgcol + string("}{\\texttt{#1}}}"));
661 // Validation is necessary only if not using AMS math.
662 // To be safe, we will always run mathedvalidate.
663 //if (features.amsstyle)
666 //features.binom = true;
667 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
668 // it would be better to do this elsewhere, but we can't validate in
669 // InsetMathMatrix and we have no way, outside MathExtern, to know if
670 // we even have any matrices.
671 features.addPreambleSnippet("<style type=\"text/css\">\n"
672 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
673 "table.matrix td{padding: 0.25px;}\n"
674 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
675 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}\n"
678 InsetMathGrid::validate(features);
682 void InsetMathHull::header_write(WriteStream & os) const
684 bool n = numberedType();
698 os << "\\begin{equation" << star(n) << "}\n";
708 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
713 os << "\\begin{" << hullName(type_) << star(n) << '}'
714 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
718 os << "\\begin{" << hullName(type_) << '}'
719 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
727 os << "\\begin{unknown" << star(n) << '}';
733 void InsetMathHull::footer_write(WriteStream & os) const
735 bool n = numberedType();
748 os << "\\end{equation" << star(n) << "}\n";
760 os << "\\end{" << hullName(type_) << star(n) << "}\n";
764 os << "\\end{" << hullName(type_) << "}\n";
772 os << "\\end{unknown" << star(n) << '}';
778 bool InsetMathHull::rowChangeOK() const
781 type_ == hullEqnArray || type_ == hullAlign ||
782 type_ == hullFlAlign || type_ == hullAlignAt ||
783 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
784 type_ == hullGather || type_ == hullMultline;
788 bool InsetMathHull::colChangeOK() const
791 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
792 type_ == hullXAlignAt || type_ == hullXXAlignAt;
796 void InsetMathHull::addRow(row_type row)
801 bool numbered = numberedType();
803 if (type_ == hullMultline) {
804 if (row + 1 == nrows()) {
811 nonum_.insert(nonum_.begin() + row + 1, !numbered);
812 label_.insert(label_.begin() + row + 1, dummy_pointer);
815 InsetMathGrid::addRow(row);
819 void InsetMathHull::swapRow(row_type row)
823 if (row + 1 == nrows())
825 // gcc implements the standard std::vector<bool> which is *not* a container:
826 // http://www.gotw.ca/publications/N1185.pdf
827 // As a results, it doesn't like this:
828 // swap(nonum_[row], nonum_[row + 1]);
829 // so we do it manually:
830 bool const b = nonum_[row];
831 nonum_[row] = nonum_[row + 1];
833 swap(label_[row], label_[row + 1]);
834 InsetMathGrid::swapRow(row);
838 void InsetMathHull::delRow(row_type row)
840 if (nrows() <= 1 || !rowChangeOK())
842 if (row + 1 == nrows() && type_ == hullMultline) {
843 bool const b = nonum_[row - 1];
844 nonum_[row - 1] = nonum_[row];
846 swap(label_[row - 1], label_[row]);
847 InsetMathGrid::delRow(row);
850 InsetMathGrid::delRow(row);
851 // The last dummy row has no number info nor a label.
852 // Test nrows() + 1 because we have already erased the row.
853 if (row == nrows() + 1)
855 nonum_.erase(nonum_.begin() + row);
857 label_.erase(label_.begin() + row);
861 void InsetMathHull::addCol(col_type col)
865 InsetMathGrid::addCol(col);
869 void InsetMathHull::delCol(col_type col)
871 if (ncols() <= 1 || !colChangeOK())
873 InsetMathGrid::delCol(col);
877 docstring InsetMathHull::nicelabel(row_type row) const
882 return from_ascii("(#)");
883 return '(' + label_[row]->screenLabel() + from_ascii(", #)");
887 void InsetMathHull::glueall()
890 for (idx_type i = 0; i < nargs(); ++i)
892 *this = InsetMathHull(buffer_, hullSimple);
898 void InsetMathHull::splitTo2Cols()
900 LASSERT(ncols() == 1, /**/);
901 InsetMathGrid::addCol(1);
902 for (row_type row = 0; row < nrows(); ++row) {
903 idx_type const i = 2 * row;
904 pos_type pos = firstRelOp(cell(i));
905 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
906 cell(i).erase(pos, cell(i).size());
911 void InsetMathHull::splitTo3Cols()
913 LASSERT(ncols() < 3, /**/);
916 InsetMathGrid::addCol(2);
917 for (row_type row = 0; row < nrows(); ++row) {
918 idx_type const i = 3 * row + 1;
919 if (cell(i).size()) {
920 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
921 cell(i).erase(1, cell(i).size());
927 void InsetMathHull::changeCols(col_type cols)
931 else if (ncols() < cols) {
937 while (ncols() < cols)
938 InsetMathGrid::addCol(ncols());
944 for (row_type row = 0; row < nrows(); ++row) {
945 idx_type const i = row * ncols();
946 for (col_type col = cols; col < ncols(); ++col) {
947 cell(i + cols - 1).append(cell(i + col));
951 while (ncols() > cols) {
952 InsetMathGrid::delCol(ncols() - 1);
957 HullType InsetMathHull::getType() const
963 void InsetMathHull::setType(HullType type)
970 void InsetMathHull::mutate(HullType newtype)
972 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
974 // we try to move along the chain
975 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
977 // +-------------------------------------+
978 // we use eqnarray as intermediate type for mutations that are not
979 // directly supported because it handles labels and numbering for
982 if (newtype == type_) {
986 else if (newtype < hullNone) {
991 else if (type_ == hullNone) {
997 else if (type_ == hullSimple) {
998 if (newtype == hullNone) {
1002 setType(hullEquation);
1008 else if (type_ == hullEquation) {
1009 if (newtype < type_) {
1010 setType(hullSimple);
1013 } else if (newtype == hullEqnArray) {
1014 // split it "nicely" on the first relop
1016 setType(hullEqnArray);
1017 } else if (newtype == hullMultline || newtype == hullGather) {
1020 // split it "nicely"
1027 else if (type_ == hullEqnArray) {
1028 if (newtype < type_) {
1029 // set correct (no)numbering
1031 for (row_type row = 0; row < nrows(); ++row) {
1038 // set first non-empty label
1039 for (row_type row = 0; row < nrows(); ++row) {
1041 label_[0] = label_[row];
1048 } else { // align & Co.
1055 else if (type_ == hullAlign || type_ == hullAlignAt ||
1056 type_ == hullXAlignAt || type_ == hullFlAlign) {
1057 if (newtype < hullAlign) {
1059 setType(hullEqnArray);
1061 } else if (newtype == hullGather || newtype == hullMultline) {
1064 } else if (newtype == hullXXAlignAt) {
1065 for (row_type row = 0; row < nrows(); ++row)
1066 numbered(row, false);
1073 else if (type_ == hullXXAlignAt) {
1074 for (row_type row = 0; row < nrows(); ++row)
1075 numbered(row, false);
1076 if (newtype < hullAlign) {
1078 setType(hullEqnArray);
1080 } else if (newtype == hullGather || newtype == hullMultline) {
1088 else if (type_ == hullMultline || type_ == hullGather) {
1089 if (newtype == hullGather || newtype == hullMultline)
1091 else if (newtype == hullAlign || newtype == hullFlAlign ||
1092 newtype == hullAlignAt || newtype == hullXAlignAt) {
1095 } else if (newtype == hullXXAlignAt) {
1097 for (row_type row = 0; row < nrows(); ++row)
1098 numbered(row, false);
1102 setType(hullEqnArray);
1108 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1109 << "' to '" << to_utf8(hullName(newtype))
1110 << "' not implemented" << endl;
1115 docstring InsetMathHull::eolString(row_type row, bool fragile, bool last_eoln) const
1118 if (numberedType()) {
1119 if (label_[row] && !nonum_[row])
1121 escape(label_[row]->getParam("name")) + '}';
1122 if (nonum_[row] && (type_ != hullMultline))
1123 res += "\\nonumber ";
1125 // Never add \\ on the last empty line of eqnarray and friends
1127 return res + InsetMathGrid::eolString(row, fragile, last_eoln);
1131 void InsetMathHull::write(WriteStream & os, bool do_header) const
1133 ModeSpecifier specifier(os, MATH_MODE);
1136 InsetMathGrid::write(os);
1142 void InsetMathHull::normalize(NormalStream & os) const
1144 os << "[formula " << hullName(type_) << ' ';
1145 InsetMathGrid::normalize(os);
1150 void InsetMathHull::mathmlize(MathStream & os) const
1152 InsetMathGrid::mathmlize(os);
1156 void InsetMathHull::infoize(odocstream & os) const
1158 os << "Type: " << hullName(type_);
1162 void InsetMathHull::check() const
1164 LASSERT(nonum_.size() == nrows(), /**/);
1165 LASSERT(label_.size() == nrows(), /**/);
1169 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1173 idocstringstream iss(func.argument());
1174 iss >> dlang >> extra;
1176 extra = from_ascii("noextra");
1177 string const lang = to_ascii(dlang);
1179 // FIXME: temporarily disabled
1180 //if (cur.selection()) {
1183 // lyxerr << "use selection: " << ar << endl;
1184 // insert(pipeThroughExtern(lang, extra, ar));
1189 eq.push_back(MathAtom(new InsetMathChar('=')));
1191 // go to first item in line
1192 cur.idx() -= cur.idx() % ncols();
1195 if (getType() == hullSimple) {
1196 size_type pos = cur.cell().find_last(eq);
1198 if (cur.inMathed() && cur.selection()) {
1199 asArray(grabAndEraseSelection(cur), ar);
1200 } else if (pos == cur.cell().size()) {
1202 lyxerr << "use whole cell: " << ar << endl;
1204 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1205 lyxerr << "use partial cell form pos: " << pos << endl;
1207 cur.cell().append(eq);
1208 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1209 cur.pos() = cur.lastpos();
1213 if (getType() == hullEquation) {
1214 lyxerr << "use equation inset" << endl;
1215 mutate(hullEqnArray);
1216 MathData & ar = cur.cell();
1217 lyxerr << "use cell: " << ar << endl;
1221 cur.cell() = pipeThroughExtern(lang, extra, ar);
1222 // move to end of line
1223 cur.pos() = cur.lastpos();
1228 lyxerr << "use eqnarray" << endl;
1229 cur.idx() += 2 - cur.idx() % ncols();
1231 MathData ar = cur.cell();
1232 lyxerr << "use cell: " << ar << endl;
1233 // FIXME: temporarily disabled
1239 cur.cell() = pipeThroughExtern(lang, extra, ar);
1240 cur.pos() = cur.lastpos();
1245 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1247 //lyxerr << "action: " << cmd.action() << endl;
1248 switch (cmd.action()) {
1250 case LFUN_FINISHED_BACKWARD:
1251 case LFUN_FINISHED_FORWARD:
1252 case LFUN_FINISHED_RIGHT:
1253 case LFUN_FINISHED_LEFT:
1254 //lyxerr << "action: " << cmd.action() << endl;
1255 InsetMathGrid::doDispatch(cur, cmd);
1259 case LFUN_BREAK_PARAGRAPH:
1260 // just swallow this
1263 case LFUN_NEWLINE_INSERT:
1264 // some magic for the common case
1265 if (type_ == hullSimple || type_ == hullEquation) {
1266 cur.recordUndoInset();
1268 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1269 mutate(align ? hullAlign : hullEqnArray);
1270 // mutate() may change labels and such.
1271 cur.forceBufferUpdate();
1272 cur.idx() = nrows() * ncols() - 1;
1273 cur.pos() = cur.lastpos();
1275 InsetMathGrid::doDispatch(cur, cmd);
1278 case LFUN_MATH_NUMBER_TOGGLE: {
1279 //lyxerr << "toggling all numbers" << endl;
1280 cur.recordUndoInset();
1281 bool old = numberedType();
1282 if (type_ == hullMultline)
1283 numbered(nrows() - 1, !old);
1285 for (row_type row = 0; row < nrows(); ++row)
1286 numbered(row, !old);
1288 cur.message(old ? _("No number") : _("Number"));
1289 cur.forceBufferUpdate();
1293 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1294 cur.recordUndoInset();
1295 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1296 bool old = numbered(r);
1297 cur.message(old ? _("No number") : _("Number"));
1299 cur.forceBufferUpdate();
1303 case LFUN_LABEL_INSERT: {
1304 cur.recordUndoInset();
1305 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1306 docstring old_label = label(r);
1308 // Allow customization of this separator
1309 docstring const default_label = from_ascii("eq:");
1310 if (old_label.empty())
1311 old_label = default_label;
1313 InsetCommandParams p(LABEL_CODE);
1314 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1315 string const data = InsetCommand::params2string("label", p);
1317 if (cmd.argument().empty())
1318 cur.bv().showDialog("label", data);
1320 FuncRequest fr(LFUN_INSET_INSERT, data);
1326 case LFUN_LABEL_COPY_AS_REF: {
1328 if (cmd.argument().empty() && &cur.inset() == this)
1329 // if there is no argument and we're inside math, we retrieve
1330 // the row number from the cursor position.
1331 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1333 // if there is an argument, find the corresponding label, else
1334 // check whether there is at least one label.
1335 for (row = 0; row != nrows(); ++row)
1336 if (!nonum_[row] && label_[row]
1337 && (cmd.argument().empty() || label(row) == cmd.argument()))
1344 InsetCommandParams p(REF_CODE, "ref");
1345 p["reference"] = label(row);
1346 cap::clearSelection();
1347 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1351 case LFUN_WORD_DELETE_FORWARD:
1352 case LFUN_CHAR_DELETE_FORWARD:
1353 if (col(cur.idx()) + 1 == ncols()
1354 && cur.pos() == cur.lastpos()
1355 && !cur.selection()) {
1356 if (!label(row(cur.idx())).empty()) {
1357 cur.recordUndoInset();
1358 label(row(cur.idx()), docstring());
1359 } else if (numbered(row(cur.idx()))) {
1360 cur.recordUndoInset();
1361 numbered(row(cur.idx()), false);
1362 cur.forceBufferUpdate();
1364 InsetMathGrid::doDispatch(cur, cmd);
1368 InsetMathGrid::doDispatch(cur, cmd);
1373 case LFUN_INSET_INSERT: {
1374 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1375 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1376 string const name = cmd.getArg(0);
1377 if (name == "label") {
1378 InsetCommandParams p(LABEL_CODE);
1379 InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1380 docstring str = p["name"];
1381 cur.recordUndoInset();
1382 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1386 docstring old = label(r);
1389 // The label will take care of the reference update.
1393 // Newly created inset so initialize it.
1394 label_[r]->initView();
1397 cur.forceBufferUpdate();
1400 InsetMathGrid::doDispatch(cur, cmd);
1404 case LFUN_MATH_EXTERN:
1405 cur.recordUndoInset();
1409 case LFUN_MATH_MUTATE: {
1410 cur.recordUndoInset();
1411 row_type row = cur.row();
1412 col_type col = cur.col();
1413 mutate(hullType(cmd.argument()));
1414 cur.idx() = row * ncols() + col;
1415 if (cur.idx() > cur.lastidx()) {
1416 cur.idx() = cur.lastidx();
1417 cur.pos() = cur.lastpos();
1419 if (cur.pos() > cur.lastpos())
1420 cur.pos() = cur.lastpos();
1422 cur.forceBufferUpdate();
1423 // FIXME: find some more clever handling of the selection,
1424 // i.e. preserve it.
1425 cur.clearSelection();
1426 //cur.dispatched(FINISHED);
1430 case LFUN_MATH_DISPLAY: {
1431 cur.recordUndoInset();
1432 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1434 cur.pos() = cur.lastpos();
1435 //cur.dispatched(FINISHED);
1440 InsetMathGrid::doDispatch(cur, cmd);
1446 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1447 FuncStatus & status) const
1449 switch (cmd.action()) {
1450 case LFUN_FINISHED_BACKWARD:
1451 case LFUN_FINISHED_FORWARD:
1452 case LFUN_FINISHED_RIGHT:
1453 case LFUN_FINISHED_LEFT:
1456 case LFUN_NEWLINE_INSERT:
1457 case LFUN_MATH_EXTERN:
1458 case LFUN_MATH_DISPLAY:
1460 status.setEnabled(true);
1463 case LFUN_MATH_MUTATE: {
1464 HullType ht = hullType(cmd.argument());
1465 status.setOnOff(type_ == ht);
1466 status.setEnabled(true);
1470 case LFUN_MATH_NUMBER_TOGGLE:
1471 // FIXME: what is the right test, this or the one of
1473 status.setEnabled(display() != Inline);
1474 status.setOnOff(numberedType());
1477 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1478 // FIXME: what is the right test, this or the one of
1480 bool const enable = (type_ == hullMultline)
1481 ? (nrows() - 1 == cur.row())
1482 : display() != Inline && nrows() > 1;
1483 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1484 status.setEnabled(enable);
1485 status.setOnOff(enable && numbered(r));
1489 case LFUN_LABEL_INSERT:
1490 status.setEnabled(type_ != hullSimple);
1493 case LFUN_LABEL_COPY_AS_REF: {
1494 bool enabled = false;
1496 if (cmd.argument().empty() && &cur.inset() == this) {
1497 // if there is no argument and we're inside math, we retrieve
1498 // the row number from the cursor position.
1499 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1500 enabled = numberedType() && label_[row] && !nonum_[row];
1502 // if there is an argument, find the corresponding label, else
1503 // check whether there is at least one label.
1504 for (row_type row = 0; row != nrows(); ++row) {
1505 if (!nonum_[row] && label_[row] &&
1506 (cmd.argument().empty() || label(row) == cmd.argument())) {
1512 status.setEnabled(enabled);
1516 case LFUN_INSET_INSERT:
1517 if (cmd.getArg(0) == "label") {
1518 status.setEnabled(type_ != hullSimple);
1521 return InsetMathGrid::getStatus(cur, cmd, status);
1523 case LFUN_INSET_MODIFY: {
1524 istringstream is(to_utf8(cmd.argument()));
1528 return InsetMathGrid::getStatus(cur, cmd, status);
1531 && (s == "append-row"
1532 || s == "delete-row"
1533 || s == "copy-row")) {
1534 status.message(bformat(
1535 from_utf8(N_("Can't change number of rows in '%1$s'")),
1537 status.setEnabled(false);
1541 && (s == "append-column"
1542 || s == "delete-column"
1543 || s == "copy-column")) {
1544 status.message(bformat(
1545 from_utf8(N_("Can't change number of columns in '%1$s'")),
1547 status.setEnabled(false);
1550 if ((type_ == hullSimple
1551 || type_ == hullEquation
1552 || type_ == hullNone) &&
1553 (s == "add-hline-above" || s == "add-hline-below")) {
1554 status.message(bformat(
1555 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1557 status.setEnabled(false);
1560 if (s == "add-vline-left" || s == "add-vline-right") {
1561 status.message(bformat(
1562 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1564 status.setEnabled(false);
1567 if (s == "valign-top" || s == "valign-middle"
1568 || s == "valign-bottom" || s == "align-left"
1569 || s == "align-center" || s == "align-right") {
1570 status.setEnabled(false);
1573 return InsetMathGrid::getStatus(cur, cmd, status);
1577 return InsetMathGrid::getStatus(cur, cmd, status);
1580 // This cannot really happen, but inserted to shut-up gcc
1581 return InsetMathGrid::getStatus(cur, cmd, status);
1585 /////////////////////////////////////////////////////////////////////
1589 // simply scrap this function if you want
1590 void InsetMathHull::mutateToText()
1593 // translate to latex
1595 latex(os, false, false);
1596 string str = os.str();
1599 Text * lt = view_->cursor().innerText();
1600 string::const_iterator cit = str.begin();
1601 string::const_iterator end = str.end();
1602 for (; cit != end; ++cit)
1603 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1606 //dispatch(LFUN_ESCAPE);
1611 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1612 docstring const & font)
1614 // this whole function is a hack and won't work for incremental font
1617 if (cur.inset().asInsetMath()->name() == font)
1618 cur.handleFont(to_utf8(font));
1620 cur.handleNest(createInsetMath(font, cur.buffer()));
1626 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1631 font.fromString(to_utf8(arg), b);
1632 if (font.fontInfo().color() != Color_inherit) {
1633 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1634 cur.handleNest(at, 0);
1639 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1642 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1643 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1644 enter_front ? idxFirst(cur) : idxLast(cur);
1645 // The inset formula dimension is not necessarily the same as the
1646 // one of the instant preview image, so we have to indicate to the
1647 // BufferView that a metrics update is needed.
1648 cur.screenUpdateFlags(Update::Force);
1652 void InsetMathHull::revealCodes(Cursor & cur) const
1654 if (!cur.inMathed())
1656 odocstringstream os;
1658 cur.message(os.str());
1660 // write something to the minibuffer
1661 // translate to latex
1665 string str = os.str();
1667 string::size_type pos = 0;
1669 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1672 else if (*it == '\0') {
1674 pos = it - str.begin();
1680 res = res.substr(pos - 30);
1681 if (res.size() > 60)
1682 res = res.substr(0, 60);
1688 /////////////////////////////////////////////////////////////////////
1692 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1695 // FIXME: completely broken
1696 static InsetMathHull * lastformula = 0;
1697 static CursorBase current = DocIterator(ibegin(nucleus()));
1699 static string laststr;
1701 if (lastformula != this || laststr != str) {
1702 //lyxerr << "reset lastformula to " << this << endl;
1705 current = ibegin(nucleus());
1707 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1711 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1713 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1714 CursorSlice & top = it.back();
1715 MathData const & a = top.asInsetMath()->cell(top.idx_);
1716 if (a.matchpart(ar, top.pos_)) {
1717 bv->cursor().setSelection(it, ar.size());
1719 top.pos_ += ar.size();
1725 //lyxerr << "not found!" << endl;
1732 void InsetMathHull::write(ostream & os) const
1734 odocstringstream oss;
1735 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1738 os << to_utf8(oss.str());
1742 void InsetMathHull::read(Lexer & lex)
1745 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1746 operator=(*at->asHullInset());
1750 bool InsetMathHull::readQuiet(Lexer & lex)
1753 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1755 operator=(*at->asHullInset());
1760 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1762 // disables ASCII-art for export of equations. See #2275.
1763 if (0 && display()) {
1767 TextPainter tpain(dim.width(), dim.height());
1768 drawT(tpain, 0, dim.ascent());
1770 // reset metrics cache to "real" values
1772 return tpain.textheight();
1774 odocstringstream oss;
1775 Encoding const * const enc = encodings.fromLyXName("utf8");
1776 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1778 if (type_ == hullRegexp)
1782 docstring const str = oss.str();
1789 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1794 if (getType() == hullSimple)
1795 name = from_ascii("inlineequation");
1797 name = from_ascii("informalequation");
1799 docstring bname = name;
1800 if (!label(0).empty())
1801 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1803 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1805 odocstringstream ls;
1806 if (runparams.flavor == OutputParams::XML) {
1807 ms << MTag("alt role='tex' ");
1808 // Workaround for db2latex: db2latex always includes equations with
1809 // \ensuremath{} or \begin{display}\end{display}
1810 // so we strip LyX' math environment
1811 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1812 InsetMathGrid::write(wi);
1813 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1818 InsetMathGrid::mathmlize(ms);
1821 ms << MTag("alt role='tex'");
1822 res = latex(ls, runparams);
1823 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1827 ms << from_ascii("<graphic fileref=\"eqn/");
1828 if (!label(0).empty())
1829 ms << sgml::cleanID(buffer(), runparams, label(0));
1831 ms << sgml::uniqueID(from_ascii("anon"));
1833 if (runparams.flavor == OutputParams::XML)
1834 ms << from_ascii("\"/>");
1836 ms << from_ascii("\">");
1838 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1840 return ms.line() + res;
1844 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
1846 BufferParams::MathOutput mathtype = buffer().params().html_math_output;
1848 // FIXME Eventually we would like to do this inset by inset.
1850 case BufferParams::MathML: {
1851 odocstringstream os;
1853 InsetMathGrid::mathmlize(ms);
1854 if (getType() == hullSimple)
1855 xs << html::StartTag("math",
1856 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1858 xs << html::StartTag("math",
1859 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1860 xs << XHTMLStream::NextRaw()
1862 << html::EndTag("math");
1865 case BufferParams::HTML: {
1866 odocstringstream os;
1868 InsetMathGrid::htmlize(ms);
1869 string const tag = (getType() == hullSimple) ? "span" : "div";
1870 xs << html::StartTag(tag, "class='formula'", true)
1871 << XHTMLStream::NextRaw()
1873 << html::EndTag(tag);
1876 case BufferParams::Images: {
1877 reloadPreview(docit_, true);
1878 graphics::PreviewImage const * pimage = preview_->getPreviewImage(buffer());
1880 // FIXME Do we always have png?
1881 string const tag = (getType() == hullSimple) ? "span" : "div";
1882 FileName const & mathimg = pimage->filename();
1883 xs << html::StartTag(tag)
1884 << html::CompTag("img", "src=\"" + mathimg.onlyFileName() + "\"")
1885 << html::EndTag(tag);
1887 // add the file to the list of files to be exported
1888 op.exportdata->addExternalFile("xhtml", mathimg);
1891 LYXERR0("Unable to generate image. Falling through to LaTeX output.");
1893 case BufferParams::LaTeX: {
1894 string const tag = (getType() == hullSimple) ? "span" : "div";
1895 docstring const latex = latexString(*this, false);
1896 // class='math' allows for use of jsMath
1897 // http://www.math.union.edu/~dpvc/jsMath/
1899 // probably should allow for some kind of customization here
1900 xs << html::StartTag(tag, "class='math'")
1902 << html::EndTag(tag);
1910 void InsetMathHull::tocString(odocstream & os) const
1912 plaintext(os, OutputParams(0));
1916 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1918 return from_ascii("context-math");
1922 void InsetMathHull::recordLocation(DocIterator const & di)