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 "InsetMathFrac.h"
18 #include "InsetMathGrid.h"
19 #include "InsetMathNest.h"
20 #include "InsetMathScript.h"
21 #include "MathExtern.h"
22 #include "MathFactory.h"
23 #include "MathStream.h"
24 #include "MathSupport.h"
27 #include "BufferParams.h"
28 #include "BufferView.h"
30 #include "CutAndPaste.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
36 #include "LaTeXFeatures.h"
38 #include "MacroTable.h"
39 #include "MathMacro.h"
40 #include "MathMacroTemplate.h"
41 #include "output_xhtml.h"
42 #include "Paragraph.h"
43 #include "ParIterator.h"
45 #include "TextClass.h"
46 #include "TextPainter.h"
47 #include "TocBackend.h"
49 #include "insets/InsetLabel.h"
50 #include "insets/InsetRef.h"
51 #include "insets/RenderPreview.h"
53 #include "graphics/GraphicsImage.h"
54 #include "graphics/PreviewImage.h"
55 #include "graphics/PreviewLoader.h"
57 #include "frontends/alert.h"
58 #include "frontends/Painter.h"
60 #include "support/convert.h"
61 #include "support/lassert.h"
62 #include "support/debug.h"
63 #include "support/filetools.h"
64 #include "support/gettext.h"
65 #include "support/lstrings.h"
70 using namespace lyx::support;
74 using cap::grabAndEraseSelection;
75 using cap::reduceSelectionToOneCell;
79 int getCols(HullType type)
96 // returns position of first relation operator in the array
97 // used for "intelligent splitting"
98 size_t firstRelOp(MathData const & ar)
100 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
101 if ((*it)->isRelOp())
102 return it - ar.begin();
107 char const * star(bool numbered)
109 return numbered ? "" : "*";
113 } // end anon namespace
116 HullType hullType(docstring const & s)
118 if (s == "none") return hullNone;
119 if (s == "simple") return hullSimple;
120 if (s == "equation") return hullEquation;
121 if (s == "eqnarray") return hullEqnArray;
122 if (s == "align") return hullAlign;
123 if (s == "alignat") return hullAlignAt;
124 if (s == "xalignat") return hullXAlignAt;
125 if (s == "xxalignat") return hullXXAlignAt;
126 if (s == "multline") return hullMultline;
127 if (s == "gather") return hullGather;
128 if (s == "flalign") return hullFlAlign;
129 if (s == "regexp") return hullRegexp;
130 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
135 docstring hullName(HullType type)
138 case hullNone: return from_ascii("none");
139 case hullSimple: return from_ascii("simple");
140 case hullEquation: return from_ascii("equation");
141 case hullEqnArray: return from_ascii("eqnarray");
142 case hullAlign: return from_ascii("align");
143 case hullAlignAt: return from_ascii("alignat");
144 case hullXAlignAt: return from_ascii("xalignat");
145 case hullXXAlignAt: return from_ascii("xxalignat");
146 case hullMultline: return from_ascii("multline");
147 case hullGather: return from_ascii("gather");
148 case hullFlAlign: return from_ascii("flalign");
149 case hullRegexp: return from_ascii("regexp");
151 lyxerr << "unknown hull type '" << type << "'" << endl;
152 return from_ascii("none");
156 static InsetLabel * dummy_pointer = 0;
158 InsetMathHull::InsetMathHull(Buffer * buf)
159 : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, NUMBER),
160 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
161 preview_(new RenderPreview(this)), use_preview_(false)
163 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
164 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
165 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
166 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
173 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
174 : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, NUMBER),
175 numbers_(1, empty_docstring()), label_(1, dummy_pointer),
176 preview_(new RenderPreview(this)), use_preview_(false)
184 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
190 InsetMathHull::~InsetMathHull()
192 for (size_t i = 0; i < label_.size(); ++i)
197 Inset * InsetMathHull::clone() const
199 return new InsetMathHull(*this);
203 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
207 InsetMathGrid::operator=(other);
209 numbered_ = other.numbered_;
210 numbers_ = other.numbers_;
211 buffer_ = other.buffer_;
212 for (size_t i = 0; i < label_.size(); ++i)
214 label_ = other.label_;
215 for (size_t i = 0; i != label_.size(); ++i) {
217 label_[i] = new InsetLabel(*label_[i]);
219 preview_.reset(new RenderPreview(*other.preview_, this));
225 void InsetMathHull::setBuffer(Buffer & buffer)
227 InsetMathGrid::setBuffer(buffer);
229 for (size_t i = 0; i != label_.size(); ++i) {
231 label_[i]->setBuffer(buffer);
236 // FIXME This should really be controlled by the TOC level, or
237 // something of the sort.
239 const char * counters_to_save[] = {"section", "chapter"};
240 unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
244 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
247 //FIXME: buffer_ should be set at creation for this inset! Problem is
248 // This inset is created at too many places (see Parser::parse1() in
253 // if any of the equations are numbered, then we want to save the values
254 // of some of the counters.
256 BufferParams const & bp = buffer_->params();
257 string const & lang = it->getParLanguage(bp)->code();
259 buffer_->masterBuffer()->params().documentClass().counters();
261 // right now, we only need to do this at export time
262 if (utype == OutputUpdate) {
263 for (size_t i = 0; i < numcnts; ++i) {
264 docstring const cnt = from_ascii(counters_to_save[i]);
265 if (cnts.hasCounter(cnt))
266 counter_map[cnt] = cnts.value(cnt);
270 // this has to be done separately
271 docstring const eqstr = from_ascii("equation");
272 if (cnts.hasCounter(eqstr)) {
273 if (utype == OutputUpdate)
274 counter_map[eqstr] = cnts.value(eqstr);
275 for (size_t i = 0; i != label_.size(); ++i) {
277 cnts.step(eqstr, utype);
278 numbers_[i] = cnts.theCounter(eqstr, lang);
280 numbers_[i] = empty_docstring();
286 for (size_t i = 0; i != label_.size(); ++i) {
288 label_[i]->updateBuffer(it, utype);
291 InsetMathGrid::updateBuffer(it, utype);
295 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active,
296 UpdateType utype) const
299 //FIXME: buffer_ should be set at creation for this inset! Problem is
300 // This inset is created at too many places (see Parser::parse1() in
305 shared_ptr<Toc> toc = buffer().tocBackend().toc("equation");
307 for (row_type row = 0; row != nrows(); ++row) {
311 label_[row]->addToToc(pit, output_active, utype);
312 toc->push_back(TocItem(pit, 0, nicelabel(row), output_active));
317 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
323 return InsetMathNest::editXY(cur, x, y);
327 InsetMath::mode_type InsetMathHull::currentMode() const
329 if (type_ == hullNone)
330 return UNDECIDED_MODE;
331 // definitely math mode ...
336 bool InsetMathHull::idxFirst(Cursor & cur) const
344 bool InsetMathHull::idxLast(Cursor & cur) const
346 cur.idx() = nargs() - 1;
347 cur.pos() = cur.lastpos();
352 char InsetMathHull::defaultColAlign(col_type col)
354 if (type_ == hullEqnArray)
356 if (type_ == hullMultline)
358 if (type_ == hullGather)
360 if (type_ >= hullAlign)
361 return "rl"[col & 1];
366 char InsetMathHull::displayColAlign(idx_type idx) const
368 if (type_ == hullMultline) {
369 row_type const r = row(idx);
372 if (r == nrows() - 1)
375 return InsetMathGrid::displayColAlign(idx);
379 int InsetMathHull::defaultColSpace(col_type col)
381 if (type_ == hullAlign || type_ == hullAlignAt)
383 if (type_ == hullXAlignAt)
384 return (col & 1) ? 20 : 0;
385 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
386 return (col & 1) ? 40 : 0;
391 docstring InsetMathHull::standardFont() const
396 font_name = from_ascii("texttt");
399 font_name = from_ascii("lyxnochange");
402 font_name = from_ascii("mathnormal");
408 ColorCode InsetMathHull::standardColor() const
414 color = Color_foreground;
423 bool InsetMathHull::previewState(const BufferView *const bv) const
425 if (!editing(bv) && RenderPreview::previewMath()
426 && type_ != hullRegexp)
428 graphics::PreviewImage const * pimage =
429 preview_->getPreviewImage(bv->buffer());
430 return pimage && pimage->image();
437 static const int ERROR_FRAME_WIDTH = 2;
440 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
442 if (previewState(mi.base.bv)) {
443 preview_->metrics(mi, dim);
444 if (previewTooSmall(dim)) {
445 // preview image is too small
446 dim.wid += 2 * ERROR_FRAME_WIDTH;
447 dim.asc += 2 * ERROR_FRAME_WIDTH;
449 // insert a one pixel gap in front of the formula
452 dim.des += displayMargin();
454 // Cache the inset dimension.
455 setDimCache(mi, dim);
459 FontSetChanger dummy1(mi.base, standardFont());
460 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
462 // let the cells adjust themselves
463 InsetMathGrid::metrics(mi, dim);
466 dim.asc += displayMargin();
467 dim.des += displayMargin();
470 if (numberedType()) {
471 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
473 for (row_type row = 0; row < nrows(); ++row)
474 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
480 if (type_ == hullRegexp)
482 // make it at least as high as the current font
485 math_font_max_dim(mi.base.font, asc, des);
486 dim.asc = max(dim.asc, asc);
487 dim.des = max(dim.des, des);
488 // Cache the inset dimension.
489 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
490 setDimCache(mi, dim);
494 bool InsetMathHull::previewTooSmall(Dimension const & dim) const
496 return dim.width() <= 10 && dim.height() <= 10;
500 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
502 BufferView const * const bv = pi.base.bv;
503 if (previewState(bv)) {
504 Dimension const dim = dimension(*pi.base.bv);
505 if (previewTooSmall(dim))
507 return graphics::PreviewLoader::backgroundColor();
513 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
515 Dimension const dim = dimension(*pi.base.bv);
516 if (previewTooSmall(dim)) {
517 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
518 dim.wid, dim.asc + dim.des, backgroundColor(pi));
521 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
522 dim.asc + dim.des - 1, pi.backgroundColor(this));
526 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
528 BufferView const * const bv = pi.base.bv;
529 use_preview_ = previewState(bv);
531 if (type_ == hullRegexp) {
532 Dimension const dim = dimension(*bv);
533 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
534 dim.width() - 2, dim.height() - 2, Color_regexpframe);
538 Dimension const dim = dimension(*bv);
539 if (previewTooSmall(dim)) {
540 // we have an extra frame
541 preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
543 // one pixel gap in front
544 preview_->draw(pi, x + 1, y);
546 setPosCache(pi, x, y);
550 ColorCode color = pi.selected && lyxrc.use_system_colors
551 ? Color_selectiontext : standardColor();
552 bool const really_change_color = pi.base.font.color() == Color_none;
553 ColorChanger dummy0(pi.base.font, color, really_change_color);
554 FontSetChanger dummy1(pi.base, standardFont());
555 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
557 InsetMathGrid::draw(pi, x + 1, y);
559 if (numberedType()) {
560 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
561 for (row_type row = 0; row < nrows(); ++row) {
562 int const yy = y + rowinfo_[row].offset_;
563 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
564 docstring const nl = nicelabel(row);
568 setPosCache(pi, x, y);
572 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
575 InsetMathGrid::metricsT(mi, dim);
578 TexRow texrow(false);
579 otexrowstream ots(os,texrow);
580 WriteStream wi(ots, false, true, WriteStream::wsDefault);
582 dim.wid = os.str().size();
589 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
592 InsetMathGrid::drawT(pain, x, y);
595 TexRow texrow(false);
596 otexrowstream ots(os,texrow);
597 WriteStream wi(ots, false, true, WriteStream::wsDefault);
599 pain.draw(x, y, os.str().c_str());
604 static docstring latexString(InsetMathHull const & inset)
607 // This has to be static, because a preview snippet or a math
608 // macro containing math in text mode (such as $\text{$\phi$}$ or
609 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
610 // first time as a whole, and the second time only the inner math.
611 // In this last case inset.buffer() would be invalid.
612 static Encoding const * encoding = 0;
613 if (inset.isBufferValid())
614 encoding = &(inset.buffer().params().encoding());
615 TexRow texrow(false);
616 otexrowstream ots(ls,texrow);
617 WriteStream wi(ots, false, true, WriteStream::wsPreview, encoding);
623 void InsetMathHull::initUnicodeMath() const
625 // Trigger classification of the unicode symbols in this inset
626 docstring const dummy = latexString(*this);
630 void InsetMathHull::addPreview(DocIterator const & inset_pos,
631 graphics::PreviewLoader & /*ploader*/) const
633 if (RenderPreview::previewMath()) {
634 preparePreview(inset_pos);
639 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
640 MacroNameSet & macros, MacroNameSet & defs) const
642 MacroNameSet::iterator const end = macros.end();
644 for (size_t i = 0; i < md.size(); ++i) {
645 MathMacro const * mi = md[i].nucleus()->asMacro();
646 MathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
647 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
648 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
649 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
650 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
652 // Look for macros in the arguments of this macro.
653 for (idx_type idx = 0; idx < mi->nargs(); ++idx)
654 usedMacros(mi->cell(idx), pos, macros, defs);
655 // Make sure this is a macro defined in the document
656 // (as we also spot the macros in the symbols file)
657 // or that we have not already accounted for it.
658 docstring const name = mi->name();
659 if (macros.find(name) == end)
662 // Look for macros in the definition of this macro.
663 MathData ar(pos.buffer());
664 MacroData const * data =
665 pos.buffer()->getMacro(name, pos, true);
667 odocstringstream macro_def;
668 data->write(macro_def, true);
670 defs.insert(macro_def.str());
671 asArray(data->definition(), ar);
673 usedMacros(ar, pos, macros, defs);
675 MathData ar(pos.buffer());
676 asArray(mt->definition(), ar);
677 usedMacros(ar, pos, macros, defs);
679 if (!si->nuc().empty())
680 usedMacros(si->nuc(), pos, macros, defs);
682 usedMacros(si->down(), pos, macros, defs);
684 usedMacros(si->up(), pos, macros, defs);
685 } else if (fi || gi) {
686 idx_type nidx = fi ? fi->nargs() : gi->nargs();
687 for (idx_type idx = 0; idx < nidx; ++idx)
688 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
691 usedMacros(ni->cell(0), pos, macros, defs);
697 void InsetMathHull::preparePreview(DocIterator const & pos,
698 bool forexport) const
700 // there is no need to do all the macro stuff if we're not
701 // actually going to generate the preview.
702 if (!RenderPreview::previewMath() && !forexport)
705 Buffer const * buffer = pos.buffer();
707 // collect macros at this position
709 buffer->listMacroNames(macros);
711 // collect definitions only for the macros used in this inset
713 for (idx_type idx = 0; idx < nargs(); ++idx)
714 usedMacros(cell(idx), pos, macros, defs);
716 MacroNameSet::iterator it = defs.begin();
717 MacroNameSet::iterator end = defs.end();
718 docstring macro_preamble;
719 for (; it != end; ++it)
720 macro_preamble.append(*it);
722 // set the font series and size for this snippet
723 DocIterator dit = pos;
724 while (dit.inMathed())
726 Paragraph const & par = dit.paragraph();
727 Font font = par.getFontSettings(buffer->params(), dit.pos());
728 font.fontInfo().realize(par.layout().font);
729 string const lsize = font.latexSize();
732 if (font.fontInfo().series() == BOLD_SERIES) {
733 setfont += from_ascii("\\textbf{");
736 if (lsize != "normalsize" && !prefixIs(lsize, "error"))
737 setfont += from_ascii("\\" + lsize + '\n');
740 if (forexport && haveNumbers()) {
741 docstring eqstr = from_ascii("equation");
742 CounterMap::const_iterator it = counter_map.find(eqstr);
743 if (it != counter_map.end()) {
744 int num = it->second;
746 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
747 '{' + convert<docstring>(num) + '}' + '\n';
749 for (size_t i = 0; i != numcnts; ++i) {
750 docstring cnt = from_ascii(counters_to_save[i]);
751 it = counter_map.find(cnt);
752 if (it == counter_map.end())
754 int num = it->second;
756 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
757 '{' + convert<docstring>(num) + '}';
760 docstring const snippet = macro_preamble + setfont + setcnt
761 + latexString(*this) + endfont;
762 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
763 preview_->addPreview(snippet, *buffer, forexport);
767 void InsetMathHull::reloadPreview(DocIterator const & pos) const
770 preview_->startLoading(*pos.buffer());
774 void InsetMathHull::loadPreview(DocIterator const & pos) const
776 bool const forexport = true;
777 preparePreview(pos, forexport);
778 preview_->startLoading(*pos.buffer(), forexport);
782 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
784 if (RenderPreview::previewMath()) {
786 cur.screenUpdateFlags(Update::Force);
792 docstring InsetMathHull::label(row_type row) const
794 LASSERT(row < nrows(), return docstring());
795 if (InsetLabel * il = label_[row])
796 return il->screenLabel();
801 void InsetMathHull::label(row_type row, docstring const & label)
803 //lyxerr << "setting label '" << label << "' for row " << row << endl;
807 label_[row] = dummy_pointer;
810 label_[row]->updateLabelAndRefs(label);
812 label_[row]->setParam("name", label);
816 InsetCommandParams p(LABEL_CODE);
818 label_[row] = new InsetLabel(buffer_, p);
820 label_[row]->setBuffer(buffer());
824 void InsetMathHull::numbered(row_type row, Numbered num)
826 numbered_[row] = num;
827 if (!numbered(row) && label_[row]) {
834 bool InsetMathHull::numbered(row_type row) const
836 return numbered_[row] == NUMBER;
840 bool InsetMathHull::ams() const
858 for (size_t row = 0; row < numbered_.size(); ++row)
859 if (numbered_[row] == NOTAG)
865 Inset::DisplayType InsetMathHull::display() const
867 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
872 bool InsetMathHull::numberedType() const
874 if (type_ == hullNone)
876 if (type_ == hullSimple)
878 if (type_ == hullXXAlignAt)
880 if (type_ == hullRegexp)
882 for (row_type row = 0; row < nrows(); ++row)
889 void InsetMathHull::validate(LaTeXFeatures & features) const
891 if (features.runparams().isLaTeX()) {
893 features.require("amsmath");
895 if (type_ == hullRegexp) {
896 features.require("color");
897 string frcol = lcolor.getLaTeXName(Color_regexpframe);
898 string bgcol = "white";
899 features.addPreambleSnippet(
900 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
901 + frcol + string("}{")
902 + bgcol + string("}{\\ensuremath{\\mathtt{#1}}}}"));
903 features.addPreambleSnippet(
904 string("\\newcommand{\\endregexp}{}"));
907 // Validation is necessary only if not using AMS math.
908 // To be safe, we will always run mathedvalidate.
909 //if (features.amsstyle)
912 //features.binom = true;
913 } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
914 // it would be better to do this elsewhere, but we can't validate in
915 // InsetMathMatrix and we have no way, outside MathExtern, to know if
916 // we even have any matrices.
917 features.addCSSSnippet(
918 "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
919 "table.matrix td{padding: 0.25px;}\n"
920 "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
921 "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
923 InsetMathGrid::validate(features);
927 void InsetMathHull::header_write(WriteStream & os) const
929 bool n = numberedType();
946 os << "\\begin{equation" << star(n) << "}\n";
958 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
965 os << "\\begin{" << hullName(type_) << star(n) << '}'
966 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
972 os << "\\begin{" << hullName(type_) << '}'
973 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
983 os << "\\begin{unknown" << star(n) << "}\n";
989 void InsetMathHull::footer_write(WriteStream & os) const
991 bool n = numberedType();
1006 os << "\\end{equation" << star(n) << "}\n";
1020 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1026 os << "\\end{" << hullName(type_) << "}\n";
1030 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1031 os << "\\endregexp{}}";
1037 os << "\\end{unknown" << star(n) << "}\n";
1043 bool InsetMathHull::isTable() const
1065 bool InsetMathHull::rowChangeOK() const
1068 type_ == hullEqnArray || type_ == hullAlign ||
1069 type_ == hullFlAlign || type_ == hullAlignAt ||
1070 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1071 type_ == hullGather || type_ == hullMultline;
1075 bool InsetMathHull::colChangeOK() const
1078 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1079 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1083 void InsetMathHull::addRow(row_type row)
1088 bool numbered = numberedType();
1089 // Move the number and raw pointer, do not call label() (bug 7511)
1090 InsetLabel * label = dummy_pointer;
1091 docstring number = empty_docstring();
1092 if (type_ == hullMultline) {
1093 if (row + 1 == nrows()) {
1094 numbered_[row] = NONUMBER;
1095 swap(label, label_[row]);
1096 swap(number, numbers_[row]);
1101 numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1102 numbers_.insert(numbers_.begin() + row + 1, number);
1103 label_.insert(label_.begin() + row + 1, label);
1104 InsetMathGrid::addRow(row);
1108 void InsetMathHull::swapRow(row_type row)
1112 if (row + 1 == nrows())
1114 swap(numbered_[row], numbered_[row + 1]);
1115 swap(numbers_[row], numbers_[row + 1]);
1116 swap(label_[row], label_[row + 1]);
1117 InsetMathGrid::swapRow(row);
1121 void InsetMathHull::delRow(row_type row)
1123 if (nrows() <= 1 || !rowChangeOK())
1125 if (row + 1 == nrows() && type_ == hullMultline) {
1126 swap(numbered_[row - 1], numbered_[row]);
1127 swap(numbers_[row - 1], numbers_[row]);
1128 swap(label_[row - 1], label_[row]);
1129 InsetMathGrid::delRow(row);
1132 InsetMathGrid::delRow(row);
1133 // The last dummy row has no number info nor a label.
1134 // Test nrows() + 1 because we have already erased the row.
1135 if (row == nrows() + 1)
1137 numbered_.erase(numbered_.begin() + row);
1138 numbers_.erase(numbers_.begin() + row);
1140 label_.erase(label_.begin() + row);
1144 void InsetMathHull::addCol(col_type col)
1148 InsetMathGrid::addCol(col);
1152 void InsetMathHull::delCol(col_type col)
1154 if (ncols() <= 1 || !colChangeOK())
1156 InsetMathGrid::delCol(col);
1160 docstring InsetMathHull::nicelabel(row_type row) const
1164 docstring const & val = numbers_[row];
1166 return '(' + val + ')';
1167 return '(' + val + ',' + label_[row]->screenLabel() + ')';
1171 void InsetMathHull::glueall(HullType type)
1174 for (idx_type i = 0; i < nargs(); ++i)
1176 InsetLabel * label = 0;
1177 if (type == hullEquation) {
1178 // preserve first non-empty label
1179 for (row_type row = 0; row < nrows(); ++row) {
1181 label = label_[row];
1187 *this = InsetMathHull(buffer_, hullSimple);
1194 void InsetMathHull::splitTo2Cols()
1196 LASSERT(ncols() == 1, return);
1197 InsetMathGrid::addCol(1);
1198 for (row_type row = 0; row < nrows(); ++row) {
1199 idx_type const i = 2 * row;
1200 pos_type pos = firstRelOp(cell(i));
1201 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1202 cell(i).erase(pos, cell(i).size());
1207 void InsetMathHull::splitTo3Cols()
1209 LASSERT(ncols() < 3, return);
1212 InsetMathGrid::addCol(2);
1213 for (row_type row = 0; row < nrows(); ++row) {
1214 idx_type const i = 3 * row + 1;
1215 if (!cell(i).empty()) {
1216 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1217 cell(i).erase(1, cell(i).size());
1223 void InsetMathHull::changeCols(col_type cols)
1225 if (ncols() == cols)
1227 else if (ncols() < cols) {
1233 while (ncols() < cols)
1234 InsetMathGrid::addCol(ncols());
1240 for (row_type row = 0; row < nrows(); ++row) {
1241 idx_type const i = row * ncols();
1242 for (col_type col = cols; col < ncols(); ++col) {
1243 cell(i + cols - 1).append(cell(i + col));
1247 while (ncols() > cols) {
1248 InsetMathGrid::delCol(ncols() - 1);
1253 HullType InsetMathHull::getType() const
1259 void InsetMathHull::setType(HullType type)
1266 void InsetMathHull::mutate(HullType newtype)
1268 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1270 // we try to move along the chain
1271 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1273 // +-------------------------------------+
1274 // we use eqnarray as intermediate type for mutations that are not
1275 // directly supported because it handles labels and numbering for
1278 if (newtype == type_) {
1282 else if (newtype < hullNone) {
1287 else if (type_ == hullNone) {
1288 setType(hullSimple);
1293 else if (type_ == hullSimple) {
1294 if (newtype == hullNone) {
1298 setType(hullEquation);
1299 numbered(0, label_[0] ? true : false);
1304 else if (type_ == hullEquation) {
1305 if (newtype < type_) {
1306 setType(hullSimple);
1309 } else if (newtype == hullEqnArray) {
1310 // split it "nicely" on the first relop
1312 setType(hullEqnArray);
1313 } else if (newtype == hullMultline || newtype == hullGather) {
1316 // split it "nicely"
1323 else if (type_ == hullEqnArray) {
1324 if (newtype < type_) {
1327 } else { // align & Co.
1334 else if (type_ == hullAlign || type_ == hullAlignAt ||
1335 type_ == hullXAlignAt || type_ == hullFlAlign) {
1336 if (newtype < hullAlign) {
1338 setType(hullEqnArray);
1340 } else if (newtype == hullGather || newtype == hullMultline) {
1343 } else if (newtype == hullXXAlignAt) {
1344 for (row_type row = 0; row < nrows(); ++row)
1345 numbered(row, false);
1352 else if (type_ == hullXXAlignAt) {
1353 for (row_type row = 0; row < nrows(); ++row)
1354 numbered(row, false);
1355 if (newtype < hullAlign) {
1357 setType(hullEqnArray);
1359 } else if (newtype == hullGather || newtype == hullMultline) {
1367 else if (type_ == hullMultline || type_ == hullGather) {
1368 if (newtype == hullGather || newtype == hullMultline)
1370 else if (newtype == hullAlign || newtype == hullFlAlign ||
1371 newtype == hullAlignAt || newtype == hullXAlignAt) {
1374 } else if (newtype == hullXXAlignAt) {
1376 for (row_type row = 0; row < nrows(); ++row)
1377 numbered(row, false);
1381 setType(hullEqnArray);
1387 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1388 << "' to '" << to_utf8(hullName(newtype))
1389 << "' not implemented" << endl;
1394 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1395 bool last_eoln) const
1398 if (numberedType()) {
1399 if (label_[row] && numbered(row)) {
1400 docstring const name =
1401 latex ? escape(label_[row]->getParam("name"))
1402 : label_[row]->getParam("name");
1403 res += "\\label{" + name + '}';
1405 if (type_ != hullMultline) {
1406 if (numbered_[row] == NONUMBER)
1407 res += "\\nonumber ";
1408 else if (numbered_[row] == NOTAG)
1412 // Never add \\ on the last empty line of eqnarray and friends
1414 return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1417 void InsetMathHull::write(WriteStream & os) const
1419 ModeSpecifier specifier(os, MATH_MODE);
1421 InsetMathGrid::write(os);
1426 void InsetMathHull::normalize(NormalStream & os) const
1428 os << "[formula " << hullName(type_) << ' ';
1429 InsetMathGrid::normalize(os);
1434 void InsetMathHull::infoize(odocstream & os) const
1436 os << bformat(_("Type: %1$s"), hullName(type_));
1440 void InsetMathHull::check() const
1442 LATTEST(numbered_.size() == nrows());
1443 LATTEST(numbers_.size() == nrows());
1444 LATTEST(label_.size() == nrows());
1448 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1452 idocstringstream iss(func.argument());
1453 iss >> dlang >> extra;
1455 extra = from_ascii("noextra");
1456 string const lang = to_ascii(dlang);
1458 // replace selection with result of computation
1459 if (reduceSelectionToOneCell(cur)) {
1461 asArray(grabAndEraseSelection(cur), ar);
1462 lyxerr << "use selection: " << ar << endl;
1463 cur.insert(pipeThroughExtern(lang, extra, ar));
1467 // only inline, display or eqnarray math is allowed
1468 if (getType() > hullEqnArray) {
1469 frontend::Alert::warning(_("Bad math environment"),
1470 _("Computation cannot be performed for AMS "
1471 "math environments.\nChange the math "
1472 "formula type and try again."));
1477 eq.push_back(MathAtom(new InsetMathChar('=')));
1479 // go to first item in line
1480 cur.idx() -= cur.idx() % ncols();
1483 if (getType() == hullSimple) {
1484 size_type pos = cur.cell().find_last(eq);
1486 if (pos == cur.cell().size()) {
1488 lyxerr << "use whole cell: " << ar << endl;
1490 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1491 lyxerr << "use partial cell form pos: " << pos << endl;
1493 cur.cell().append(eq);
1494 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1495 cur.pos() = cur.lastpos();
1499 if (getType() == hullEquation) {
1500 lyxerr << "use equation inset" << endl;
1501 mutate(hullEqnArray);
1502 MathData & ar = cur.cell();
1503 lyxerr << "use cell: " << ar << endl;
1507 cur.cell() = pipeThroughExtern(lang, extra, ar);
1508 // move to end of line
1509 cur.pos() = cur.lastpos();
1514 lyxerr << "use eqnarray" << endl;
1515 cur.idx() += 2 - cur.idx() % ncols();
1517 MathData ar = cur.cell();
1518 lyxerr << "use cell: " << ar << endl;
1519 // FIXME: temporarily disabled
1525 cur.cell() = pipeThroughExtern(lang, extra, ar);
1526 cur.pos() = cur.lastpos();
1531 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1533 //lyxerr << "action: " << cmd.action() << endl;
1534 switch (cmd.action()) {
1536 case LFUN_FINISHED_BACKWARD:
1537 case LFUN_FINISHED_FORWARD:
1538 case LFUN_FINISHED_RIGHT:
1539 case LFUN_FINISHED_LEFT:
1540 //lyxerr << "action: " << cmd.action() << endl;
1541 InsetMathGrid::doDispatch(cur, cmd);
1544 case LFUN_PARAGRAPH_BREAK:
1545 // just swallow this
1548 case LFUN_NEWLINE_INSERT:
1549 // some magic for the common case
1550 if (type_ == hullSimple || type_ == hullEquation) {
1551 cur.recordUndoInset();
1553 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1554 mutate(align ? hullAlign : hullEqnArray);
1555 // mutate() may change labels and such.
1556 cur.forceBufferUpdate();
1557 cur.idx() = nrows() * ncols() - 1;
1558 cur.pos() = cur.lastpos();
1560 InsetMathGrid::doDispatch(cur, cmd);
1563 case LFUN_MATH_NUMBER_TOGGLE: {
1564 //lyxerr << "toggling all numbers" << endl;
1565 cur.recordUndoInset();
1566 bool old = numberedType();
1567 if (type_ == hullMultline)
1568 numbered(nrows() - 1, !old);
1570 for (row_type row = 0; row < nrows(); ++row)
1571 numbered(row, !old);
1573 cur.message(old ? _("No number") : _("Number"));
1574 cur.forceBufferUpdate();
1578 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1579 cur.recordUndoInset();
1580 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1581 bool old = numbered(r);
1582 cur.message(old ? _("No number") : _("Number"));
1584 cur.forceBufferUpdate();
1588 case LFUN_LABEL_INSERT: {
1589 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1590 docstring old_label = label(r);
1591 docstring const default_label = from_ascii("eq:");
1592 if (old_label.empty())
1593 old_label = default_label;
1595 InsetCommandParams p(LABEL_CODE);
1596 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1597 string const data = InsetCommand::params2string(p);
1599 if (cmd.argument().empty())
1600 cur.bv().showDialog("label", data);
1602 FuncRequest fr(LFUN_INSET_INSERT, data);
1608 case LFUN_LABEL_COPY_AS_REFERENCE: {
1610 if (cmd.argument().empty() && &cur.inset() == this)
1611 // if there is no argument and we're inside math, we retrieve
1612 // the row number from the cursor position.
1613 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1615 // if there is an argument, find the corresponding label, else
1616 // check whether there is at least one label.
1617 for (row = 0; row != nrows(); ++row)
1618 if (numbered(row) && label_[row]
1619 && (cmd.argument().empty() || label(row) == cmd.argument()))
1626 InsetCommandParams p(REF_CODE, "ref");
1627 p["reference"] = label(row);
1628 cap::clearSelection();
1629 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1633 case LFUN_WORD_DELETE_FORWARD:
1634 case LFUN_CHAR_DELETE_FORWARD:
1635 if (col(cur.idx()) + 1 == ncols()
1636 && cur.pos() == cur.lastpos()
1637 && !cur.selection()) {
1638 if (!label(row(cur.idx())).empty()) {
1639 cur.recordUndoInset();
1640 label(row(cur.idx()), docstring());
1641 } else if (numbered(row(cur.idx()))) {
1642 cur.recordUndoInset();
1643 numbered(row(cur.idx()), false);
1644 cur.forceBufferUpdate();
1646 InsetMathGrid::doDispatch(cur, cmd);
1650 InsetMathGrid::doDispatch(cur, cmd);
1655 case LFUN_INSET_INSERT: {
1656 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1657 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1658 string const name = cmd.getArg(0);
1659 if (name == "label") {
1660 InsetCommandParams p(LABEL_CODE);
1661 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1662 docstring str = p["name"];
1663 cur.recordUndoInset();
1664 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1668 docstring old = label(r);
1671 // The label will take care of the reference update.
1675 // Newly created inset so initialize it.
1676 label_[r]->initView();
1679 cur.forceBufferUpdate();
1682 InsetMathGrid::doDispatch(cur, cmd);
1686 case LFUN_MATH_EXTERN:
1687 cur.recordUndoInset();
1691 case LFUN_MATH_MUTATE: {
1692 cur.recordUndoInset();
1693 row_type row = cur.row();
1694 col_type col = cur.col();
1695 mutate(hullType(cmd.argument()));
1696 cur.idx() = row * ncols() + col;
1697 if (cur.idx() > cur.lastidx()) {
1698 cur.idx() = cur.lastidx();
1699 cur.pos() = cur.lastpos();
1701 if (cur.pos() > cur.lastpos())
1702 cur.pos() = cur.lastpos();
1704 cur.forceBufferUpdate();
1705 // FIXME: find some more clever handling of the selection,
1706 // i.e. preserve it.
1707 cur.clearSelection();
1708 //cur.dispatched(FINISHED);
1712 case LFUN_MATH_DISPLAY: {
1713 cur.recordUndoInset();
1714 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1715 // if the cursor is in a cell that got merged, move it to
1716 // start of the hull inset.
1717 if (cur.idx() > 0) {
1721 if (cur.pos() > cur.lastpos())
1722 cur.pos() = cur.lastpos();
1727 case LFUN_TABULAR_FEATURE:
1731 InsetMathGrid::doDispatch(cur, cmd);
1735 InsetMathGrid::doDispatch(cur, cmd);
1741 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1742 FuncStatus & status) const
1744 switch (cmd.action()) {
1745 case LFUN_FINISHED_BACKWARD:
1746 case LFUN_FINISHED_FORWARD:
1747 case LFUN_FINISHED_RIGHT:
1748 case LFUN_FINISHED_LEFT:
1751 case LFUN_NEWLINE_INSERT:
1752 case LFUN_MATH_EXTERN:
1754 status.setEnabled(true);
1757 // we never allow this in math, and we want to bind enter
1758 // to another actions in command-alternatives
1759 case LFUN_PARAGRAPH_BREAK:
1760 status.setEnabled(false);
1762 case LFUN_MATH_MUTATE: {
1763 HullType const ht = hullType(cmd.argument());
1764 status.setOnOff(type_ == ht);
1765 status.setEnabled(true);
1767 if (ht != hullSimple) {
1768 Cursor tmpcur = cur;
1769 while (!tmpcur.empty()) {
1770 InsetCode code = tmpcur.inset().lyxCode();
1771 if (code == BOX_CODE) {
1773 } else if (code == TABULAR_CODE) {
1774 FuncRequest tmpcmd(LFUN_MATH_DISPLAY);
1775 if (tmpcur.getStatus(tmpcmd, status) && !status.enabled())
1783 case LFUN_MATH_DISPLAY: {
1785 if (cur.depth() > 1) {
1786 Inset const & in = cur[cur.depth()-2].inset();
1787 if (in.lyxCode() == SCRIPT_CODE)
1788 enable = display() != Inline;
1790 status.setEnabled(enable);
1791 status.setOnOff(display() != Inline);
1795 case LFUN_MATH_NUMBER_TOGGLE:
1796 // FIXME: what is the right test, this or the one of
1798 status.setEnabled(display() != Inline);
1799 status.setOnOff(numberedType());
1802 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1803 // FIXME: what is the right test, this or the one of
1805 bool const enable = (type_ == hullMultline)
1806 ? (nrows() - 1 == cur.row())
1807 : display() != Inline;
1808 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1809 status.setEnabled(enable);
1810 status.setOnOff(enable && numbered(r));
1814 case LFUN_LABEL_INSERT:
1815 status.setEnabled(type_ != hullSimple);
1818 case LFUN_LABEL_COPY_AS_REFERENCE: {
1819 bool enabled = false;
1821 if (cmd.argument().empty() && &cur.inset() == this) {
1822 // if there is no argument and we're inside math, we retrieve
1823 // the row number from the cursor position.
1824 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1825 enabled = numberedType() && label_[row] && numbered(row);
1827 // if there is an argument, find the corresponding label, else
1828 // check whether there is at least one label.
1829 for (row_type row = 0; row != nrows(); ++row) {
1830 if (numbered(row) && label_[row] &&
1831 (cmd.argument().empty() || label(row) == cmd.argument())) {
1837 status.setEnabled(enabled);
1841 case LFUN_INSET_INSERT:
1842 if (cmd.getArg(0) == "label") {
1843 status.setEnabled(type_ != hullSimple);
1846 return InsetMathGrid::getStatus(cur, cmd, status);
1848 case LFUN_TABULAR_FEATURE: {
1851 string s = cmd.getArg(0);
1853 && (s == "append-row"
1854 || s == "delete-row"
1855 || s == "copy-row")) {
1856 status.message(bformat(
1857 from_utf8(N_("Can't change number of rows in '%1$s'")),
1859 status.setEnabled(false);
1863 && (s == "append-column"
1864 || s == "delete-column"
1865 || s == "copy-column")) {
1866 status.message(bformat(
1867 from_utf8(N_("Can't change number of columns in '%1$s'")),
1869 status.setEnabled(false);
1872 if (s == "add-vline-left" || s == "add-vline-right") {
1873 status.message(bformat(
1874 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1876 status.setEnabled(false);
1879 if (s == "valign-top" || s == "valign-middle"
1880 || s == "valign-bottom" || s == "align-left"
1881 || s == "align-center" || s == "align-right") {
1882 status.setEnabled(false);
1885 return InsetMathGrid::getStatus(cur, cmd, status);
1889 return InsetMathGrid::getStatus(cur, cmd, status);
1892 // This cannot really happen, but inserted to shut-up gcc
1893 return InsetMathGrid::getStatus(cur, cmd, status);
1897 /////////////////////////////////////////////////////////////////////
1901 // simply scrap this function if you want
1902 void InsetMathHull::mutateToText()
1905 // translate to latex
1907 latex(os, false, false);
1908 string str = os.str();
1911 Text * lt = view_->cursor().innerText();
1912 string::const_iterator cit = str.begin();
1913 string::const_iterator end = str.end();
1914 for (; cit != end; ++cit)
1915 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1918 //dispatch(LFUN_ESCAPE);
1923 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1924 docstring const & font)
1926 // this whole function is a hack and won't work for incremental font
1929 if (cur.inset().asInsetMath()->name() == font)
1930 cur.handleFont(to_utf8(font));
1932 cur.handleNest(createInsetMath(font, cur.buffer()));
1938 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1943 font.fromString(to_utf8(arg), b);
1944 if (font.fontInfo().color() != Color_inherit) {
1945 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1946 cur.handleNest(at, 0);
1951 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1954 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1955 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1956 enter_front ? idxFirst(cur) : idxLast(cur);
1957 // The inset formula dimension is not necessarily the same as the
1958 // one of the instant preview image, so we have to indicate to the
1959 // BufferView that a metrics update is needed.
1960 cur.screenUpdateFlags(Update::Force);
1964 void InsetMathHull::revealCodes(Cursor & cur) const
1966 if (!cur.inMathed())
1968 odocstringstream os;
1970 cur.message(os.str());
1972 // write something to the minibuffer
1973 // translate to latex
1977 string str = os.str();
1979 string::size_type pos = 0;
1981 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1984 else if (*it == '\0') {
1986 pos = it - str.begin();
1992 res = res.substr(pos - 30);
1993 if (res.size() > 60)
1994 res = res.substr(0, 60);
2000 /////////////////////////////////////////////////////////////////////
2004 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2007 // FIXME: completely broken
2008 static InsetMathHull * lastformula = 0;
2009 static CursorBase current = DocIterator(ibegin(nucleus()));
2011 static string laststr;
2013 if (lastformula != this || laststr != str) {
2014 //lyxerr << "reset lastformula to " << this << endl;
2017 current = ibegin(nucleus());
2019 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2023 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2025 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2026 CursorSlice & top = it.back();
2027 MathData const & a = top.asInsetMath()->cell(top.idx_);
2028 if (a.matchpart(ar, top.pos_)) {
2029 bv->cursor().setSelection(it, ar.size());
2031 top.pos_ += ar.size();
2037 //lyxerr << "not found!" << endl;
2044 void InsetMathHull::write(ostream & os) const
2046 odocstringstream oss;
2047 TexRow texrow(false);
2048 otexrowstream ots(oss,texrow);
2049 WriteStream wi(ots, false, false, WriteStream::wsDefault);
2052 os << to_utf8(oss.str());
2056 void InsetMathHull::read(Lexer & lex)
2059 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2060 operator=(*at->asHullInset());
2064 bool InsetMathHull::readQuiet(Lexer & lex)
2067 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2069 operator=(*at->asHullInset());
2074 int InsetMathHull::plaintext(odocstringstream & os,
2075 OutputParams const & op, size_t max_length) const
2077 // disables ASCII-art for export of equations. See #2275.
2078 if (0 && display()) {
2082 TextPainter tpain(dim.width(), dim.height());
2083 drawT(tpain, 0, dim.ascent());
2085 // reset metrics cache to "real" values
2087 return tpain.textheight();
2090 odocstringstream oss;
2091 TexRow texrow(false);
2092 otexrowstream ots(oss,texrow);
2093 Encoding const * const enc = encodings.fromLyXName("utf8");
2094 WriteStream wi(ots, false, true, WriteStream::wsDefault, enc);
2097 if (type_ == hullRegexp)
2100 for (row_type r = 0; r < nrows(); ++r) {
2101 for (col_type c = 0; c < ncols(); ++c)
2102 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2103 // if it's for the TOC, we write just the first line
2104 // and do not include the newline.
2105 if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2107 if (r < nrows() - 1)
2111 docstring const str = oss.str();
2117 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
2122 if (getType() == hullSimple)
2123 name = from_ascii("inlineequation");
2125 name = from_ascii("informalequation");
2127 docstring bname = name;
2128 if (!label(0).empty())
2129 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
2131 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
2133 odocstringstream ls;
2135 otexstream ols(ls, texrow);
2136 if (runparams.flavor == OutputParams::XML) {
2137 ms << MTag("alt role='tex' ");
2138 // Workaround for db2latex: db2latex always includes equations with
2139 // \ensuremath{} or \begin{display}\end{display}
2140 // so we strip LyX' math environment
2141 WriteStream wi(ols, false, false, WriteStream::wsDefault, runparams.encoding);
2142 InsetMathGrid::write(wi);
2143 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2148 InsetMathGrid::mathmlize(ms);
2151 ms << MTag("alt role='tex'");
2152 latex(ols, runparams);
2153 res = texrow.rows();
2154 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
2158 ms << from_ascii("<graphic fileref=\"eqn/");
2159 if (!label(0).empty())
2160 ms << sgml::cleanID(buffer(), runparams, label(0));
2162 ms << sgml::uniqueID(from_ascii("anon"));
2164 if (runparams.flavor == OutputParams::XML)
2165 ms << from_ascii("\"/>");
2167 ms << from_ascii("\">");
2169 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2171 return ms.line() + res;
2175 bool InsetMathHull::haveNumbers() const
2177 bool havenumbers = false;
2178 // inline formulas are never numbered (bug 7351 part 3)
2179 if (getType() == hullSimple)
2181 for (size_t i = 0; i != numbered_.size(); ++i) {
2192 // We need to do something about alignment here.
2194 // This duplicates code from InsetMathGrid, but
2195 // we need access here to number information,
2196 // and we simply do not have that in InsetMathGrid.
2197 void InsetMathHull::htmlize(HtmlStream & os) const
2199 bool const havenumbers = haveNumbers();
2200 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2203 os << cell(index(0, 0));
2207 os << MTag("table", "class='mathtable'");
2208 for (row_type row = 0; row < nrows(); ++row) {
2210 for (col_type col = 0; col < ncols(); ++col) {
2212 os << cell(index(row, col));
2217 docstring const & num = numbers_[row];
2219 os << '(' << num << ')';
2224 os << ETag("table");
2228 // this duplicates code from InsetMathGrid, but
2229 // we need access here to number information,
2230 // and we simply do not have that in InsetMathGrid.
2231 void InsetMathHull::mathmlize(MathStream & os) const
2233 bool const havenumbers = haveNumbers();
2234 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2237 os << MTag("mtable");
2238 char const * const celltag = havetable ? "mtd" : "mrow";
2239 // FIXME There does not seem to be wide support at the moment
2240 // for mlabeledtr, so we have to use just mtr for now.
2241 // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2242 char const * const rowtag = "mtr";
2243 for (row_type row = 0; row < nrows(); ++row) {
2246 for (col_type col = 0; col < ncols(); ++col) {
2248 << cell(index(row, col))
2254 docstring const & num = numbers_[row];
2256 os << '(' << num << ')';
2263 os << ETag("mtable");
2267 void InsetMathHull::mathAsLatex(WriteStream & os) const
2269 MathEnsurer ensurer(os, false);
2270 bool havenumbers = haveNumbers();
2271 bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2274 os << cell(index(0, 0));
2278 os << "<table class='mathtable'>";
2279 for (row_type row = 0; row < nrows(); ++row) {
2281 for (col_type col = 0; col < ncols(); ++col) {
2282 os << "<td class='math'>";
2283 os << cell(index(row, col));
2288 docstring const & num = numbers_[row];
2290 os << '(' << num << ')';
2299 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2301 BufferParams::MathOutput const mathtype =
2302 buffer().masterBuffer()->params().html_math_output;
2304 bool success = false;
2306 // we output all the labels just at the beginning of the equation.
2307 // this should be fine.
2308 for (size_t i = 0; i != label_.size(); ++i) {
2309 InsetLabel const * const il = label_[i];
2315 // FIXME Eventually we would like to do this inset by inset.
2316 if (mathtype == BufferParams::MathML) {
2317 odocstringstream os;
2322 } catch (MathExportException const &) {}
2324 if (getType() == hullSimple)
2325 xs << html::StartTag("math",
2326 "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2328 xs << html::StartTag("math",
2329 "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2330 xs << XHTMLStream::ESCAPE_NONE
2332 << html::EndTag("math");
2334 } else if (mathtype == BufferParams::HTML) {
2335 odocstringstream os;
2340 } catch (MathExportException const &) {}
2342 string const tag = (getType() == hullSimple) ? "span" : "div";
2343 xs << html::StartTag(tag, "class='formula'", true)
2344 << XHTMLStream::ESCAPE_NONE
2346 << html::EndTag(tag);
2350 // what we actually want is this:
2352 // ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2354 // || mathtype == BufferParams::Images
2356 // but what follows is equivalent, since we'll enter only if either (a) we
2357 // tried and failed with MathML or HTML or (b) didn't try yet at all but
2358 // aren't doing LaTeX, in which case we are doing Images.
2359 if (!success && mathtype != BufferParams::LaTeX) {
2360 graphics::PreviewImage const * pimage = 0;
2362 loadPreview(docit_);
2363 pimage = preview_->getPreviewImage(buffer());
2364 // FIXME Do we always have png?
2367 if (pimage || op.dryrun) {
2368 string const filename = pimage ? pimage->filename().onlyFileName()
2369 : "previewimage.png";
2371 // if we are not in the master buffer, then we need to see that the
2372 // generated image is copied there; otherwise, preview fails.
2373 Buffer const * mbuf = buffer().masterBuffer();
2374 if (mbuf != &buffer()) {
2375 string mbtmp = mbuf->temppath();
2376 FileName const mbufimg(support::addName(mbtmp, filename));
2377 pimage->filename().copyTo(mbufimg);
2379 // add the file to the list of files to be exported
2380 op.exportdata->addExternalFile("xhtml", pimage->filename());
2383 string const tag = (getType() == hullSimple) ? "span" : "div";
2385 << html::StartTag(tag)
2386 << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2387 << html::EndTag(tag)
2393 // so we'll pass this test if we've failed everything else, or
2394 // if mathtype was LaTeX, since we won't have entered any of the
2396 if (!success /* || mathtype != BufferParams::LaTeX */) {
2397 // Unfortunately, we cannot use latexString() because we do not want
2398 // $...$ or whatever.
2399 odocstringstream ls;
2400 TexRow texrow(false);
2401 otexrowstream ots(ls,texrow);
2402 WriteStream wi(ots, false, true, WriteStream::wsPreview);
2403 ModeSpecifier specifier(wi, MATH_MODE);
2405 docstring const latex = ls.str();
2407 // class='math' allows for use of jsMath
2408 // http://www.math.union.edu/~dpvc/jsMath/
2410 // probably should allow for some kind of customization here
2411 string const tag = (getType() == hullSimple) ? "span" : "div";
2412 xs << html::StartTag(tag, "class='math'")
2414 << html::EndTag(tag)
2421 void InsetMathHull::toString(odocstream & os) const
2423 odocstringstream ods;
2424 plaintext(ods, OutputParams(0));
2429 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2431 odocstringstream ods;
2434 // FIXME: this results in spilling TeX into the LyXHTML output since the
2435 // outliner is used to generate the LyXHTML list of figures/etc.
2441 string InsetMathHull::contextMenuName() const
2443 return "context-math";
2447 void InsetMathHull::recordLocation(DocIterator const & di)