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/alert.h"
47 #include "frontends/Painter.h"
49 #include "support/lassert.h"
50 #include "support/debug.h"
51 #include "support/gettext.h"
52 #include "support/lstrings.h"
57 using namespace lyx::support;
61 using cap::grabAndEraseSelection;
65 int getCols(HullType type)
82 // returns position of first relation operator in the array
83 // used for "intelligent splitting"
84 size_t firstRelOp(MathData const & ar)
86 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
88 return it - ar.begin();
93 char const * star(bool numbered)
95 return numbered ? "" : "*";
99 } // end anon namespace
102 HullType hullType(docstring const & s)
104 if (s == "none") return hullNone;
105 if (s == "simple") return hullSimple;
106 if (s == "equation") return hullEquation;
107 if (s == "eqnarray") return hullEqnArray;
108 if (s == "align") return hullAlign;
109 if (s == "alignat") return hullAlignAt;
110 if (s == "xalignat") return hullXAlignAt;
111 if (s == "xxalignat") return hullXXAlignAt;
112 if (s == "multline") return hullMultline;
113 if (s == "gather") return hullGather;
114 if (s == "flalign") return hullFlAlign;
115 if (s == "regexp") return hullRegexp;
116 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
121 docstring hullName(HullType type)
124 case hullNone: return from_ascii("none");
125 case hullSimple: return from_ascii("simple");
126 case hullEquation: return from_ascii("equation");
127 case hullEqnArray: return from_ascii("eqnarray");
128 case hullAlign: return from_ascii("align");
129 case hullAlignAt: return from_ascii("alignat");
130 case hullXAlignAt: return from_ascii("xalignat");
131 case hullXXAlignAt: return from_ascii("xxalignat");
132 case hullMultline: return from_ascii("multline");
133 case hullGather: return from_ascii("gather");
134 case hullFlAlign: return from_ascii("flalign");
135 case hullRegexp: return from_ascii("regexp");
137 lyxerr << "unknown hull type '" << type << "'" << endl;
138 return from_ascii("none");
142 static InsetLabel * dummy_pointer = 0;
144 InsetMathHull::InsetMathHull(Buffer * buf)
145 : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, true),
146 label_(1, dummy_pointer), preview_(new RenderPreview(this))
148 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
149 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
150 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
151 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
158 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
159 : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, true),
160 label_(1, dummy_pointer), preview_(new RenderPreview(this))
168 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
174 InsetMathHull::~InsetMathHull()
176 for (size_t i = 0; i < label_.size(); ++i)
181 Inset * InsetMathHull::clone() const
183 return new InsetMathHull(*this);
187 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
191 InsetMathGrid::operator=(other);
193 numbered_ = other.numbered_;
194 buffer_ = other.buffer_;
195 for (size_t i = 0; i < label_.size(); ++i)
197 label_ = other.label_;
198 for (size_t i = 0; i != label_.size(); ++i) {
200 label_[i] = new InsetLabel(*label_[i]);
202 preview_.reset(new RenderPreview(*other.preview_, this));
208 void InsetMathHull::setBuffer(Buffer & buffer)
210 InsetMathGrid::setBuffer(buffer);
212 for (size_t i = 0; i != label_.size(); ++i) {
214 label_[i]->setBuffer(buffer);
219 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
222 //FIXME: buffer_ should be set at creation for this inset! Problem is
223 // This inset is created at too many places (see Parser::parse1() in
227 for (size_t i = 0; i != label_.size(); ++i) {
229 label_[i]->updateBuffer(it, utype);
232 InsetMathGrid::updateBuffer(it, utype);
236 void InsetMathHull::addToToc(DocIterator const & pit)
239 //FIXME: buffer_ should be set at creation for this inset! Problem is
240 // This inset is created at too many places (see Parser::parse1() in
245 Toc & toc = buffer().tocBackend().toc("equation");
247 for (row_type row = 0; row != nrows(); ++row) {
251 label_[row]->addToToc(pit);
252 toc.push_back(TocItem(pit, 0, nicelabel(row)));
257 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
263 return InsetMathNest::editXY(cur, x, y);
267 InsetMath::mode_type InsetMathHull::currentMode() const
269 if (type_ == hullNone)
270 return UNDECIDED_MODE;
271 // definitely math mode ...
276 bool InsetMathHull::idxFirst(Cursor & cur) const
284 bool InsetMathHull::idxLast(Cursor & cur) const
286 cur.idx() = nargs() - 1;
287 cur.pos() = cur.lastpos();
292 char InsetMathHull::defaultColAlign(col_type col)
294 if (type_ == hullEqnArray)
296 if (type_ == hullGather)
298 if (type_ >= hullAlign)
299 return "rl"[col & 1];
304 int InsetMathHull::defaultColSpace(col_type col)
306 if (type_ == hullAlign || type_ == hullAlignAt)
308 if (type_ == hullXAlignAt)
309 return (col & 1) ? 20 : 0;
310 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
311 return (col & 1) ? 40 : 0;
316 docstring InsetMathHull::standardFont() const
321 font_name = from_ascii("texttt");
324 font_name = from_ascii("lyxnochange");
327 font_name = from_ascii("mathnormal");
333 ColorCode InsetMathHull::standardColor() const
339 color = Color_foreground;
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 ColorCode color = pi.selected && lyxrc.use_system_colors
438 ? Color_selectiontext : standardColor();
439 bool const really_change_color = pi.base.font.color() == Color_none;
440 ColorChanger dummy0(pi.base.font, color, really_change_color);
441 FontSetChanger dummy1(pi.base, standardFont());
442 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
444 InsetMathGrid::draw(pi, x + 1, y);
446 if (numberedType()) {
447 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
448 for (row_type row = 0; row < nrows(); ++row) {
449 int const yy = y + rowinfo_[row].offset_;
450 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
451 docstring const nl = nicelabel(row);
455 setPosCache(pi, x, y);
459 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
462 InsetMathGrid::metricsT(mi, dim);
465 WriteStream wi(os, false, true, WriteStream::wsDefault);
467 dim.wid = os.str().size();
474 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
477 InsetMathGrid::drawT(pain, x, y);
480 WriteStream wi(os, false, true, WriteStream::wsDefault);
482 pain.draw(x, y, os.str().c_str());
487 static docstring latexString(InsetMathHull const & inset)
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);
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,
521 bool forexport) const
523 // there is no need to do all the macro stuff if we're not
524 // actually going to generate the preview.
525 if (RenderPreview::status() != LyXRC::PREVIEW_ON && !forexport)
528 Buffer const * buffer = pos.buffer();
530 // collect macros at this position
532 buffer->listMacroNames(macros);
533 MacroNameSet::iterator it = macros.begin();
534 MacroNameSet::iterator end = macros.end();
535 odocstringstream macro_preamble;
536 for (; it != end; ++it) {
537 MacroData const * data = buffer->getMacro(*it, pos, true);
539 data->write(macro_preamble, true);
540 macro_preamble << endl;
544 docstring const snippet = macro_preamble.str() + latexString(*this);
545 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
546 preview_->addPreview(snippet, *buffer, forexport);
550 void InsetMathHull::reloadPreview(DocIterator const & pos) const
553 preview_->startLoading(*pos.buffer());
557 void InsetMathHull::loadPreview(DocIterator const & pos) const
559 bool const forexport = true;
560 preparePreview(pos, forexport);
561 preview_->startLoading(*pos.buffer(), forexport);
565 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
567 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
569 cur.screenUpdateFlags(Update::Force);
575 docstring InsetMathHull::label(row_type row) const
577 LASSERT(row < nrows(), /**/);
578 if (InsetLabel * il = label_[row])
579 return il->screenLabel();
584 void InsetMathHull::label(row_type row, docstring const & label)
586 //lyxerr << "setting label '" << label << "' for row " << row << endl;
590 label_[row] = dummy_pointer;
593 label_[row]->updateCommand(label);
595 label_[row]->setParam("name", label);
599 InsetCommandParams p(LABEL_CODE);
601 label_[row] = new InsetLabel(buffer_, p);
603 label_[row]->setBuffer(buffer());
607 void InsetMathHull::numbered(row_type row, bool num)
609 numbered_[row] = num;
610 if (!numbered_[row] && label_[row]) {
617 bool InsetMathHull::numbered(row_type row) const
619 return numbered_[row];
623 bool InsetMathHull::ams() const
625 return type_ == hullAlign
626 || type_ == hullFlAlign
627 || type_ == hullMultline
628 || type_ == hullGather
629 || type_ == hullAlignAt
630 || type_ == hullXAlignAt
631 || type_ == hullXXAlignAt;
635 Inset::DisplayType InsetMathHull::display() const
637 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
642 bool InsetMathHull::numberedType() const
644 if (type_ == hullNone)
646 if (type_ == hullSimple)
648 if (type_ == hullXXAlignAt)
650 if (type_ == hullRegexp)
652 for (row_type row = 0; row < nrows(); ++row)
659 void InsetMathHull::validate(LaTeXFeatures & features) const
661 if (features.runparams().isLaTeX()) {
663 features.require("amsmath");
665 if (type_ == hullRegexp) {
666 features.require("color");
667 string frcol = lcolor.getLaTeXName(Color_regexpframe);
668 string bgcol = "white";
669 features.addPreambleSnippet(
670 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
671 + frcol + string("}{")
672 + bgcol + string("}{\\texttt{#1}}}"));
675 // Validation is necessary only if not using AMS math.
676 // To be safe, we will always run mathedvalidate.
677 //if (features.amsstyle)
680 //features.binom = true;
681 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
682 // it would be better to do this elsewhere, but we can't validate in
683 // InsetMathMatrix and we have no way, outside MathExtern, to know if
684 // we even have any matrices.
685 features.addPreambleSnippet("<style type=\"text/css\">\n"
686 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
687 "table.matrix td{padding: 0.25px;}\n"
688 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
689 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}\n"
692 InsetMathGrid::validate(features);
696 void InsetMathHull::header_write(WriteStream & os) const
698 bool n = numberedType();
712 os << "\\begin{equation" << star(n) << "}\n";
722 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
727 os << "\\begin{" << hullName(type_) << star(n) << '}'
728 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
732 os << "\\begin{" << hullName(type_) << '}'
733 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
741 os << "\\begin{unknown" << star(n) << "}\n";
747 void InsetMathHull::footer_write(WriteStream & os) const
749 bool n = numberedType();
762 os << "\n\\end{equation" << star(n) << "}\n";
774 os << "\n\\end{" << hullName(type_) << star(n) << "}\n";
778 os << "\n\\end{" << hullName(type_) << "}\n";
786 os << "\n\\end{unknown" << star(n) << "}\n";
792 bool InsetMathHull::rowChangeOK() const
795 type_ == hullEqnArray || type_ == hullAlign ||
796 type_ == hullFlAlign || type_ == hullAlignAt ||
797 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
798 type_ == hullGather || type_ == hullMultline;
802 bool InsetMathHull::colChangeOK() const
805 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
806 type_ == hullXAlignAt || type_ == hullXXAlignAt;
810 void InsetMathHull::addRow(row_type row)
815 bool numbered = numberedType();
817 if (type_ == hullMultline) {
818 if (row + 1 == nrows()) {
819 numbered_[row] = false;
825 numbered_.insert(numbered_.begin() + row + 1, numbered);
826 label_.insert(label_.begin() + row + 1, dummy_pointer);
829 InsetMathGrid::addRow(row);
833 void InsetMathHull::swapRow(row_type row)
837 if (row + 1 == nrows())
839 // gcc implements the standard std::vector<bool> which is *not* a container:
840 // http://www.gotw.ca/publications/N1185.pdf
841 // As a results, it doesn't like this:
842 // swap(numbered_[row], numbered_[row + 1]);
843 // so we do it manually:
844 bool const b = numbered_[row];
845 numbered_[row] = numbered_[row + 1];
846 numbered_[row + 1] = b;
847 swap(label_[row], label_[row + 1]);
848 InsetMathGrid::swapRow(row);
852 void InsetMathHull::delRow(row_type row)
854 if (nrows() <= 1 || !rowChangeOK())
856 if (row + 1 == nrows() && type_ == hullMultline) {
857 bool const b = numbered_[row - 1];
858 numbered_[row - 1] = numbered_[row];
860 swap(label_[row - 1], label_[row]);
861 InsetMathGrid::delRow(row);
864 InsetMathGrid::delRow(row);
865 // The last dummy row has no number info nor a label.
866 // Test nrows() + 1 because we have already erased the row.
867 if (row == nrows() + 1)
869 numbered_.erase(numbered_.begin() + row);
871 label_.erase(label_.begin() + row);
875 void InsetMathHull::addCol(col_type col)
879 InsetMathGrid::addCol(col);
883 void InsetMathHull::delCol(col_type col)
885 if (ncols() <= 1 || !colChangeOK())
887 InsetMathGrid::delCol(col);
891 docstring InsetMathHull::nicelabel(row_type row) const
896 return from_ascii("(#)");
897 return '(' + label_[row]->screenLabel() + from_ascii(", #)");
901 void InsetMathHull::glueall(HullType type)
904 for (idx_type i = 0; i < nargs(); ++i)
906 InsetLabel * label = 0;
907 if (type == hullEquation) {
908 // preserve first non-empty label
909 for (row_type row = 0; row < nrows(); ++row) {
917 *this = InsetMathHull(buffer_, hullSimple);
924 void InsetMathHull::splitTo2Cols()
926 LASSERT(ncols() == 1, /**/);
927 InsetMathGrid::addCol(1);
928 for (row_type row = 0; row < nrows(); ++row) {
929 idx_type const i = 2 * row;
930 pos_type pos = firstRelOp(cell(i));
931 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
932 cell(i).erase(pos, cell(i).size());
937 void InsetMathHull::splitTo3Cols()
939 LASSERT(ncols() < 3, /**/);
942 InsetMathGrid::addCol(2);
943 for (row_type row = 0; row < nrows(); ++row) {
944 idx_type const i = 3 * row + 1;
945 if (cell(i).size()) {
946 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
947 cell(i).erase(1, cell(i).size());
953 void InsetMathHull::changeCols(col_type cols)
957 else if (ncols() < cols) {
963 while (ncols() < cols)
964 InsetMathGrid::addCol(ncols());
970 for (row_type row = 0; row < nrows(); ++row) {
971 idx_type const i = row * ncols();
972 for (col_type col = cols; col < ncols(); ++col) {
973 cell(i + cols - 1).append(cell(i + col));
977 while (ncols() > cols) {
978 InsetMathGrid::delCol(ncols() - 1);
983 HullType InsetMathHull::getType() const
989 void InsetMathHull::setType(HullType type)
996 void InsetMathHull::mutate(HullType newtype)
998 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1000 // we try to move along the chain
1001 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1003 // +-------------------------------------+
1004 // we use eqnarray as intermediate type for mutations that are not
1005 // directly supported because it handles labels and numbering for
1008 if (newtype == type_) {
1012 else if (newtype < hullNone) {
1017 else if (type_ == hullNone) {
1018 setType(hullSimple);
1023 else if (type_ == hullSimple) {
1024 if (newtype == hullNone) {
1028 setType(hullEquation);
1029 numbered(0, label_[0] ? true : false);
1034 else if (type_ == hullEquation) {
1035 if (newtype < type_) {
1036 setType(hullSimple);
1039 } else if (newtype == hullEqnArray) {
1040 // split it "nicely" on the first relop
1042 setType(hullEqnArray);
1043 } else if (newtype == hullMultline || newtype == hullGather) {
1046 // split it "nicely"
1053 else if (type_ == hullEqnArray) {
1054 if (newtype < type_) {
1057 } else { // align & Co.
1064 else if (type_ == hullAlign || type_ == hullAlignAt ||
1065 type_ == hullXAlignAt || type_ == hullFlAlign) {
1066 if (newtype < hullAlign) {
1068 setType(hullEqnArray);
1070 } else if (newtype == hullGather || newtype == hullMultline) {
1073 } else if (newtype == hullXXAlignAt) {
1074 for (row_type row = 0; row < nrows(); ++row)
1075 numbered(row, false);
1082 else if (type_ == hullXXAlignAt) {
1083 for (row_type row = 0; row < nrows(); ++row)
1084 numbered(row, false);
1085 if (newtype < hullAlign) {
1087 setType(hullEqnArray);
1089 } else if (newtype == hullGather || newtype == hullMultline) {
1097 else if (type_ == hullMultline || type_ == hullGather) {
1098 if (newtype == hullGather || newtype == hullMultline)
1100 else if (newtype == hullAlign || newtype == hullFlAlign ||
1101 newtype == hullAlignAt || newtype == hullXAlignAt) {
1104 } else if (newtype == hullXXAlignAt) {
1106 for (row_type row = 0; row < nrows(); ++row)
1107 numbered(row, false);
1111 setType(hullEqnArray);
1117 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1118 << "' to '" << to_utf8(hullName(newtype))
1119 << "' not implemented" << endl;
1124 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1125 bool last_eoln) const
1128 if (numberedType()) {
1129 if (label_[row] && numbered_[row]) {
1130 docstring const name =
1131 latex ? escape(label_[row]->getParam("name"))
1132 : label_[row]->getParam("name");
1133 res += "\\label{" + name + '}';
1135 if (!numbered_[row] && (type_ != hullMultline))
1136 res += "\\nonumber ";
1138 // Never add \\ on the last empty line of eqnarray and friends
1140 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1144 void InsetMathHull::write(WriteStream & os) const
1146 ModeSpecifier specifier(os, MATH_MODE);
1148 InsetMathGrid::write(os);
1153 void InsetMathHull::normalize(NormalStream & os) const
1155 os << "[formula " << hullName(type_) << ' ';
1156 InsetMathGrid::normalize(os);
1161 void InsetMathHull::mathmlize(MathStream & os) const
1163 InsetMathGrid::mathmlize(os);
1167 void InsetMathHull::infoize(odocstream & os) const
1169 os << "Type: " << hullName(type_);
1173 void InsetMathHull::check() const
1175 LASSERT(numbered_.size() == nrows(), /**/);
1176 LASSERT(label_.size() == nrows(), /**/);
1180 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1184 idocstringstream iss(func.argument());
1185 iss >> dlang >> extra;
1187 extra = from_ascii("noextra");
1188 string const lang = to_ascii(dlang);
1190 // FIXME: temporarily disabled
1191 //if (cur.selection()) {
1194 // lyxerr << "use selection: " << ar << endl;
1195 // insert(pipeThroughExtern(lang, extra, ar));
1199 // only inline, display or eqnarray math is allowed
1200 if (getType() > hullEqnArray) {
1201 frontend::Alert::warning(_("Bad math environment"),
1202 _("Computation cannot be performed for AMS "
1203 "math environments.\nChange the math "
1204 "formula type and try again."));
1209 eq.push_back(MathAtom(new InsetMathChar('=')));
1211 // go to first item in line
1212 cur.idx() -= cur.idx() % ncols();
1215 if (getType() == hullSimple) {
1216 size_type pos = cur.cell().find_last(eq);
1218 if (cur.inMathed() && cur.selection()) {
1219 asArray(grabAndEraseSelection(cur), ar);
1220 } else if (pos == cur.cell().size()) {
1222 lyxerr << "use whole cell: " << ar << endl;
1224 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1225 lyxerr << "use partial cell form pos: " << pos << endl;
1227 cur.cell().append(eq);
1228 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1229 cur.pos() = cur.lastpos();
1233 if (getType() == hullEquation) {
1234 lyxerr << "use equation inset" << endl;
1235 mutate(hullEqnArray);
1236 MathData & ar = cur.cell();
1237 lyxerr << "use cell: " << ar << endl;
1241 cur.cell() = pipeThroughExtern(lang, extra, ar);
1242 // move to end of line
1243 cur.pos() = cur.lastpos();
1248 lyxerr << "use eqnarray" << endl;
1249 cur.idx() += 2 - cur.idx() % ncols();
1251 MathData ar = cur.cell();
1252 lyxerr << "use cell: " << ar << endl;
1253 // FIXME: temporarily disabled
1259 cur.cell() = pipeThroughExtern(lang, extra, ar);
1260 cur.pos() = cur.lastpos();
1265 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1267 //lyxerr << "action: " << cmd.action() << endl;
1268 switch (cmd.action()) {
1270 case LFUN_FINISHED_BACKWARD:
1271 case LFUN_FINISHED_FORWARD:
1272 case LFUN_FINISHED_RIGHT:
1273 case LFUN_FINISHED_LEFT:
1274 //lyxerr << "action: " << cmd.action() << endl;
1275 InsetMathGrid::doDispatch(cur, cmd);
1279 case LFUN_BREAK_PARAGRAPH:
1280 // just swallow this
1283 case LFUN_NEWLINE_INSERT:
1284 // some magic for the common case
1285 if (type_ == hullSimple || type_ == hullEquation) {
1286 cur.recordUndoInset();
1288 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1289 mutate(align ? hullAlign : hullEqnArray);
1290 // mutate() may change labels and such.
1291 cur.forceBufferUpdate();
1292 cur.idx() = nrows() * ncols() - 1;
1293 cur.pos() = cur.lastpos();
1295 InsetMathGrid::doDispatch(cur, cmd);
1298 case LFUN_MATH_NUMBER_TOGGLE: {
1299 //lyxerr << "toggling all numbers" << endl;
1300 cur.recordUndoInset();
1301 bool old = numberedType();
1302 if (type_ == hullMultline)
1303 numbered(nrows() - 1, !old);
1305 for (row_type row = 0; row < nrows(); ++row)
1306 numbered(row, !old);
1308 cur.message(old ? _("No number") : _("Number"));
1309 cur.forceBufferUpdate();
1313 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1314 cur.recordUndoInset();
1315 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1316 bool old = numbered(r);
1317 cur.message(old ? _("No number") : _("Number"));
1319 cur.forceBufferUpdate();
1323 case LFUN_LABEL_INSERT: {
1324 cur.recordUndoInset();
1325 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1326 docstring old_label = label(r);
1328 // Allow customization of this separator
1329 docstring const default_label = from_ascii("eq:");
1330 if (old_label.empty())
1331 old_label = default_label;
1333 InsetCommandParams p(LABEL_CODE);
1334 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1335 string const data = InsetCommand::params2string(p);
1337 if (cmd.argument().empty())
1338 cur.bv().showDialog("label", data);
1340 FuncRequest fr(LFUN_INSET_INSERT, data);
1346 case LFUN_LABEL_COPY_AS_REF: {
1348 if (cmd.argument().empty() && &cur.inset() == this)
1349 // if there is no argument and we're inside math, we retrieve
1350 // the row number from the cursor position.
1351 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1353 // if there is an argument, find the corresponding label, else
1354 // check whether there is at least one label.
1355 for (row = 0; row != nrows(); ++row)
1356 if (numbered_[row] && label_[row]
1357 && (cmd.argument().empty() || label(row) == cmd.argument()))
1364 InsetCommandParams p(REF_CODE, "ref");
1365 p["reference"] = label(row);
1366 cap::clearSelection();
1367 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1371 case LFUN_WORD_DELETE_FORWARD:
1372 case LFUN_CHAR_DELETE_FORWARD:
1373 if (col(cur.idx()) + 1 == ncols()
1374 && cur.pos() == cur.lastpos()
1375 && !cur.selection()) {
1376 if (!label(row(cur.idx())).empty()) {
1377 cur.recordUndoInset();
1378 label(row(cur.idx()), docstring());
1379 } else if (numbered(row(cur.idx()))) {
1380 cur.recordUndoInset();
1381 numbered(row(cur.idx()), false);
1382 cur.forceBufferUpdate();
1384 InsetMathGrid::doDispatch(cur, cmd);
1388 InsetMathGrid::doDispatch(cur, cmd);
1393 case LFUN_INSET_INSERT: {
1394 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1395 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1396 string const name = cmd.getArg(0);
1397 if (name == "label") {
1398 InsetCommandParams p(LABEL_CODE);
1399 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1400 docstring str = p["name"];
1401 cur.recordUndoInset();
1402 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1406 docstring old = label(r);
1409 // The label will take care of the reference update.
1413 // Newly created inset so initialize it.
1414 label_[r]->initView();
1417 cur.forceBufferUpdate();
1420 InsetMathGrid::doDispatch(cur, cmd);
1424 case LFUN_MATH_EXTERN:
1425 cur.recordUndoInset();
1429 case LFUN_MATH_MUTATE: {
1430 cur.recordUndoInset();
1431 row_type row = cur.row();
1432 col_type col = cur.col();
1433 mutate(hullType(cmd.argument()));
1434 cur.idx() = row * ncols() + col;
1435 if (cur.idx() > cur.lastidx()) {
1436 cur.idx() = cur.lastidx();
1437 cur.pos() = cur.lastpos();
1439 if (cur.pos() > cur.lastpos())
1440 cur.pos() = cur.lastpos();
1442 cur.forceBufferUpdate();
1443 // FIXME: find some more clever handling of the selection,
1444 // i.e. preserve it.
1445 cur.clearSelection();
1446 //cur.dispatched(FINISHED);
1450 case LFUN_MATH_DISPLAY: {
1451 cur.recordUndoInset();
1452 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1454 cur.pos() = cur.lastpos();
1455 //cur.dispatched(FINISHED);
1460 InsetMathGrid::doDispatch(cur, cmd);
1466 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1467 FuncStatus & status) const
1469 switch (cmd.action()) {
1470 case LFUN_FINISHED_BACKWARD:
1471 case LFUN_FINISHED_FORWARD:
1472 case LFUN_FINISHED_RIGHT:
1473 case LFUN_FINISHED_LEFT:
1476 case LFUN_NEWLINE_INSERT:
1477 case LFUN_MATH_EXTERN:
1479 status.setEnabled(true);
1482 case LFUN_MATH_MUTATE: {
1483 HullType const ht = hullType(cmd.argument());
1484 status.setOnOff(type_ == ht);
1485 status.setEnabled(true);
1487 if (ht != hullSimple) {
1488 Cursor tmpcur = cur;
1489 while (!tmpcur.empty()) {
1490 InsetCode code = tmpcur.inset().lyxCode();
1491 if (code == BOX_CODE) {
1493 } else if (code == TABULAR_CODE) {
1494 FuncRequest tmpcmd(LFUN_MATH_DISPLAY);
1495 if (tmpcur.getStatus(tmpcmd, status) && !status.enabled())
1503 case LFUN_MATH_DISPLAY: {
1505 if (cur.depth() > 1) {
1506 Inset const & in = cur[cur.depth()-2].inset();
1507 if (in.lyxCode() == SCRIPT_CODE)
1508 enable = display() != Inline;
1510 status.setEnabled(enable);
1514 case LFUN_MATH_NUMBER_TOGGLE:
1515 // FIXME: what is the right test, this or the one of
1517 status.setEnabled(display() != Inline);
1518 status.setOnOff(numberedType());
1521 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1522 // FIXME: what is the right test, this or the one of
1524 bool const enable = (type_ == hullMultline)
1525 ? (nrows() - 1 == cur.row())
1526 : display() != Inline && nrows() > 1;
1527 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1528 status.setEnabled(enable);
1529 status.setOnOff(enable && numbered(r));
1533 case LFUN_LABEL_INSERT:
1534 status.setEnabled(type_ != hullSimple);
1537 case LFUN_LABEL_COPY_AS_REF: {
1538 bool enabled = false;
1540 if (cmd.argument().empty() && &cur.inset() == this) {
1541 // if there is no argument and we're inside math, we retrieve
1542 // the row number from the cursor position.
1543 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1544 enabled = numberedType() && label_[row] && numbered_[row];
1546 // if there is an argument, find the corresponding label, else
1547 // check whether there is at least one label.
1548 for (row_type row = 0; row != nrows(); ++row) {
1549 if (numbered_[row] && label_[row] &&
1550 (cmd.argument().empty() || label(row) == cmd.argument())) {
1556 status.setEnabled(enabled);
1560 case LFUN_INSET_INSERT:
1561 if (cmd.getArg(0) == "label") {
1562 status.setEnabled(type_ != hullSimple);
1565 return InsetMathGrid::getStatus(cur, cmd, status);
1567 case LFUN_INSET_MODIFY: {
1568 istringstream is(to_utf8(cmd.argument()));
1572 return InsetMathGrid::getStatus(cur, cmd, status);
1575 && (s == "append-row"
1576 || s == "delete-row"
1577 || s == "copy-row")) {
1578 status.message(bformat(
1579 from_utf8(N_("Can't change number of rows in '%1$s'")),
1581 status.setEnabled(false);
1585 && (s == "append-column"
1586 || s == "delete-column"
1587 || s == "copy-column")) {
1588 status.message(bformat(
1589 from_utf8(N_("Can't change number of columns in '%1$s'")),
1591 status.setEnabled(false);
1594 if ((type_ == hullSimple
1595 || type_ == hullEquation
1596 || type_ == hullNone) &&
1597 (s == "add-hline-above" || s == "add-hline-below")) {
1598 status.message(bformat(
1599 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1601 status.setEnabled(false);
1604 if (s == "add-vline-left" || s == "add-vline-right") {
1605 status.message(bformat(
1606 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1608 status.setEnabled(false);
1611 if (s == "valign-top" || s == "valign-middle"
1612 || s == "valign-bottom" || s == "align-left"
1613 || s == "align-center" || s == "align-right") {
1614 status.setEnabled(false);
1617 return InsetMathGrid::getStatus(cur, cmd, status);
1621 return InsetMathGrid::getStatus(cur, cmd, status);
1624 // This cannot really happen, but inserted to shut-up gcc
1625 return InsetMathGrid::getStatus(cur, cmd, status);
1629 /////////////////////////////////////////////////////////////////////
1633 // simply scrap this function if you want
1634 void InsetMathHull::mutateToText()
1637 // translate to latex
1639 latex(os, false, false);
1640 string str = os.str();
1643 Text * lt = view_->cursor().innerText();
1644 string::const_iterator cit = str.begin();
1645 string::const_iterator end = str.end();
1646 for (; cit != end; ++cit)
1647 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1650 //dispatch(LFUN_ESCAPE);
1655 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1656 docstring const & font)
1658 // this whole function is a hack and won't work for incremental font
1661 if (cur.inset().asInsetMath()->name() == font)
1662 cur.handleFont(to_utf8(font));
1664 cur.handleNest(createInsetMath(font, cur.buffer()));
1670 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1675 font.fromString(to_utf8(arg), b);
1676 if (font.fontInfo().color() != Color_inherit) {
1677 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1678 cur.handleNest(at, 0);
1683 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1686 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1687 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1688 enter_front ? idxFirst(cur) : idxLast(cur);
1689 // The inset formula dimension is not necessarily the same as the
1690 // one of the instant preview image, so we have to indicate to the
1691 // BufferView that a metrics update is needed.
1692 cur.screenUpdateFlags(Update::Force);
1696 void InsetMathHull::revealCodes(Cursor & cur) const
1698 if (!cur.inMathed())
1700 odocstringstream os;
1702 cur.message(os.str());
1704 // write something to the minibuffer
1705 // translate to latex
1709 string str = os.str();
1711 string::size_type pos = 0;
1713 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1716 else if (*it == '\0') {
1718 pos = it - str.begin();
1724 res = res.substr(pos - 30);
1725 if (res.size() > 60)
1726 res = res.substr(0, 60);
1732 /////////////////////////////////////////////////////////////////////
1736 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1739 // FIXME: completely broken
1740 static InsetMathHull * lastformula = 0;
1741 static CursorBase current = DocIterator(ibegin(nucleus()));
1743 static string laststr;
1745 if (lastformula != this || laststr != str) {
1746 //lyxerr << "reset lastformula to " << this << endl;
1749 current = ibegin(nucleus());
1751 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1755 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1757 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1758 CursorSlice & top = it.back();
1759 MathData const & a = top.asInsetMath()->cell(top.idx_);
1760 if (a.matchpart(ar, top.pos_)) {
1761 bv->cursor().setSelection(it, ar.size());
1763 top.pos_ += ar.size();
1769 //lyxerr << "not found!" << endl;
1776 void InsetMathHull::write(ostream & os) const
1778 odocstringstream oss;
1779 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1782 os << to_utf8(oss.str());
1786 void InsetMathHull::read(Lexer & lex)
1789 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1790 operator=(*at->asHullInset());
1794 bool InsetMathHull::readQuiet(Lexer & lex)
1797 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1799 operator=(*at->asHullInset());
1804 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1806 // disables ASCII-art for export of equations. See #2275.
1807 if (0 && display()) {
1811 TextPainter tpain(dim.width(), dim.height());
1812 drawT(tpain, 0, dim.ascent());
1814 // reset metrics cache to "real" values
1816 return tpain.textheight();
1818 odocstringstream oss;
1819 Encoding const * const enc = encodings.fromLyXName("utf8");
1820 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1822 if (type_ == hullRegexp)
1826 docstring const str = oss.str();
1833 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1838 if (getType() == hullSimple)
1839 name = from_ascii("inlineequation");
1841 name = from_ascii("informalequation");
1843 docstring bname = name;
1844 if (!label(0).empty())
1845 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1847 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1849 odocstringstream ls;
1850 if (runparams.flavor == OutputParams::XML) {
1851 ms << MTag("alt role='tex' ");
1852 // Workaround for db2latex: db2latex always includes equations with
1853 // \ensuremath{} or \begin{display}\end{display}
1854 // so we strip LyX' math environment
1855 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1856 InsetMathGrid::write(wi);
1857 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1862 InsetMathGrid::mathmlize(ms);
1865 ms << MTag("alt role='tex'");
1866 res = latex(ls, runparams);
1867 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1871 ms << from_ascii("<graphic fileref=\"eqn/");
1872 if (!label(0).empty())
1873 ms << sgml::cleanID(buffer(), runparams, label(0));
1875 ms << sgml::uniqueID(from_ascii("anon"));
1877 if (runparams.flavor == OutputParams::XML)
1878 ms << from_ascii("\"/>");
1880 ms << from_ascii("\">");
1882 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1884 return ms.line() + res;
1888 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
1890 BufferParams::MathOutput const mathtype =
1891 buffer().params().html_math_output;
1893 bool success = false;
1894 // FIXME Eventually we would like to do this inset by inset.
1895 if (mathtype == BufferParams::MathML) {
1896 odocstringstream os;
1899 InsetMathGrid::mathmlize(ms);
1901 } catch (MathExportException const &) {}
1903 if (getType() == hullSimple)
1904 xs << html::StartTag("math",
1905 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1907 xs << html::StartTag("math",
1908 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1909 xs << XHTMLStream::ESCAPE_NONE
1911 << html::EndTag("math");
1913 } else if (mathtype == BufferParams::HTML) {
1914 odocstringstream os;
1917 InsetMathGrid::htmlize(ms);
1919 } catch (MathExportException const &) {}
1921 string const tag = (getType() == hullSimple) ? "span" : "div";
1922 xs << html::StartTag(tag, "class='formula'", true)
1923 << XHTMLStream::ESCAPE_NONE
1925 << html::EndTag(tag);
1929 // what we actually want is this:
1931 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
1933 // || mathtype == BufferParams::Images
1935 // but what follows is equivalent, since we'll enter only if either (a) we
1936 // tried and failed with MathML or HTML or (b) didn't try yet at all but
1937 // aren't doing LaTeX, in which case we are doing Images.
1938 if (!success && mathtype != BufferParams::LaTeX) {
1939 loadPreview(docit_);
1940 graphics::PreviewImage const * pimage = preview_->getPreviewImage(buffer());
1942 // FIXME Do we always have png?
1943 string const tag = (getType() == hullSimple) ? "span" : "div";
1944 FileName const & mathimg = pimage->filename();
1945 xs << html::StartTag(tag)
1946 << html::CompTag("img", "src=\"" + mathimg.onlyFileName() + "\"")
1947 << html::EndTag(tag);
1949 // add the file to the list of files to be exported
1950 op.exportdata->addExternalFile("xhtml", mathimg);
1955 // so we'll pass this test if we've failed everything else, or
1956 // if mathtype was LaTeX, since we won't have entered any of the
1958 if (!success /* || mathtype != BufferParams::LaTeX */) {
1959 string const tag = (getType() == hullSimple) ? "span" : "div";
1960 // Unfortunately, we cannot use latexString() because we do not want
1961 // $...$ or whatever.
1962 odocstringstream ls;
1963 WriteStream wi(ls, false, true, WriteStream::wsPreview);
1964 ModeSpecifier specifier(wi, MATH_MODE);
1965 InsetMathGrid::write(wi);
1966 docstring const latex = ls.str();
1968 // class='math' allows for use of jsMath
1969 // http://www.math.union.edu/~dpvc/jsMath/
1971 // probably should allow for some kind of customization here
1972 xs << html::StartTag(tag, "class='math'")
1974 << html::EndTag(tag);
1981 void InsetMathHull::tocString(odocstream & os) const
1983 plaintext(os, OutputParams(0));
1987 docstring InsetMathHull::contextMenuName() const
1989 return from_ascii("context-math");
1993 void InsetMathHull::recordLocation(DocIterator const & di)