2 * \file math_hullinset.C
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 "math_charinset.h"
14 #include "math_data.h"
15 #include "math_extern.h"
16 #include "math_hullinset.h"
17 #include "math_mathmlstream.h"
18 #include "math_streamstr.h"
19 #include "math_support.h"
21 #include "BufferView.h"
23 #include "dispatchresult.h"
25 #include "funcrequest.h"
27 #include "LaTeXFeatures.h"
30 #include "outputparams.h"
31 #include "textpainter.h"
33 #include "frontends/Alert.h"
35 #include "support/std_sstream.h"
43 using std::istringstream;
45 using std::ostringstream;
53 int getCols(string const & type)
55 if (type == "eqnarray")
59 if (type == "flalign")
61 if (type == "alignat")
63 if (type == "xalignat")
65 if (type == "xxalignat")
71 // returns position of first relation operator in the array
72 // used for "intelligent splitting"
73 size_t firstRelOp(MathArray const & ar)
75 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
77 return it - ar.begin();
82 char const * star(bool numbered)
84 return numbered ? "" : "*";
88 int typecode(string const & s)
90 if (s == "none") return 0;
91 if (s == "simple") return 1;
92 if (s == "equation") return 2;
93 if (s == "eqnarray") return 3;
94 if (s == "align") return 4;
95 if (s == "alignat") return 5;
96 if (s == "xalignat") return 6;
97 if (s == "xxalignat") return 7;
98 if (s == "multline") return 8;
99 if (s == "gather") return 9;
100 if (s == "flalign") return 10;
101 lyxerr << "unknown hull type '" << s << "'" << endl;
105 bool smaller(string const & s, string const & t)
107 return typecode(s) < typecode(t);
111 } // end anon namespace
115 MathHullInset::MathHullInset()
116 : MathGridInset(1, 1), type_("none"), nonum_(1), label_(1)
118 // This is needed as long the math parser is not re-entrant
120 //lyxerr << "sizeof MathInset: " << sizeof(MathInset) << endl;
121 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
122 //lyxerr << "sizeof MathCharInset: " << sizeof(MathCharInset) << endl;
123 //lyxerr << "sizeof LyXFont: " << sizeof(LyXFont) << endl;
128 MathHullInset::MathHullInset(string const & type)
129 : MathGridInset(getCols(type), 1), type_(type), nonum_(1), label_(1)
135 auto_ptr<InsetBase> MathHullInset::clone() const
137 return auto_ptr<InsetBase>(new MathHullInset(*this));
141 MathInset::mode_type MathHullInset::currentMode() const
144 return UNDECIDED_MODE;
145 // definitely math mode ...
150 bool MathHullInset::idxFirst(LCursor & cur) const
158 bool MathHullInset::idxLast(LCursor & cur) const
160 cur.idx() = nargs() - 1;
161 cur.pos() = cur.lastpos();
166 char MathHullInset::defaultColAlign(col_type col)
168 if (type_ == "eqnarray")
170 if (typecode(type_) >= typecode("align"))
171 return "rl"[col & 1];
176 int MathHullInset::defaultColSpace(col_type col)
178 if (type_ == "align" || type_ == "alignat")
180 if (type_ == "xalignat")
181 return (col & 1) ? 20 : 0;
182 if (type_ == "xxalignat" || type_ == "flalign")
183 return (col & 1) ? 40 : 0;
188 char const * MathHullInset::standardFont() const
191 return "lyxnochange";
196 void MathHullInset::metrics(MetricsInfo & mi, Dimension & dim) const
198 FontSetChanger dummy1(mi.base, standardFont());
199 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
201 // let the cells adjust themselves
202 MathGridInset::metrics(mi, dim);
209 if (numberedType()) {
210 FontSetChanger dummy(mi.base, "mathbf");
212 for (row_type row = 0; row < nrows(); ++row)
213 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
219 // make it at least as high as the current font
222 math_font_max_dim(mi.base.font, asc, des);
223 dim.asc = max(dim.asc, asc);
224 dim.des = max(dim.des, des);
227 metricsMarkers2(dim);
232 void MathHullInset::draw(PainterInfo & pi, int x, int y) const
234 FontSetChanger dummy1(pi.base, standardFont());
235 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
236 MathGridInset::draw(pi, x + 1, y);
238 if (numberedType()) {
239 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
240 for (row_type row = 0; row < nrows(); ++row) {
241 int const yy = y + rowinfo_[row].offset_;
242 FontSetChanger dummy(pi.base, "mathrm");
243 drawStr(pi, pi.base.font, xx, yy, nicelabel(row));
247 drawMarkers2(pi, x, y);
251 void MathHullInset::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
254 MathGridInset::metricsT(mi, dim);
257 WriteStream wi(os, false, true);
259 dim.wid = os.str().size();
266 void MathHullInset::drawT(TextPainter & pain, int x, int y) const
269 MathGridInset::drawT(pain, x, y);
272 WriteStream wi(os, false, true);
274 pain.draw(x, y, os.str().c_str());
279 string MathHullInset::label(row_type row) const
281 row_type n = nrows();
282 BOOST_ASSERT(row < n);
287 void MathHullInset::label(row_type row, string const & label)
289 //lyxerr << "setting label '" << label << "' for row " << row << endl;
294 void MathHullInset::numbered(row_type row, bool num)
300 bool MathHullInset::numbered(row_type row) const
306 bool MathHullInset::ams() const
310 type_ == "flalign" ||
311 type_ == "multline" ||
313 type_ == "alignat" ||
314 type_ == "xalignat" ||
315 type_ == "xxalignat";
319 bool MathHullInset::display() const
321 return type_ != "simple" && type_ != "none";
325 void MathHullInset::getLabelList(Buffer const &, vector<string> & labels) const
327 for (row_type row = 0; row < nrows(); ++row)
328 if (!label_[row].empty() && nonum_[row] != 1)
329 labels.push_back(label_[row]);
333 bool MathHullInset::numberedType() const
337 if (type_ == "simple")
339 if (type_ == "xxalignat")
341 for (row_type row = 0; row < nrows(); ++row)
348 void MathHullInset::validate(LaTeXFeatures & features) const
351 features.require("amsmath");
354 // Validation is necessary only if not using AMS math.
355 // To be safe, we will always run mathedvalidate.
356 //if (features.amsstyle)
359 features.require("boldsymbol");
360 //features.binom = true;
362 MathGridInset::validate(features);
366 void MathHullInset::header_write(WriteStream & os) const
368 bool n = numberedType();
373 else if (type_ == "simple") {
379 else if (type_ == "equation") {
381 os << "\\begin{equation" << star(n) << "}\n";
386 else if (type_ == "eqnarray" || type_ == "align" || type_ == "flalign"
387 || type_ == "gather" || type_ == "multline")
388 os << "\\begin{" << type_ << star(n) << "}\n";
390 else if (type_ == "alignat" || type_ == "xalignat")
391 os << "\\begin{" << type_ << star(n) << '}'
392 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
394 else if (type_ == "xxalignat")
395 os << "\\begin{" << type_ << '}'
396 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
399 os << "\\begin{unknown" << star(n) << '}';
403 void MathHullInset::footer_write(WriteStream & os) const
405 bool n = numberedType();
410 else if (type_ == "simple")
413 else if (type_ == "equation")
415 os << "\\end{equation" << star(n) << "}\n";
419 else if (type_ == "eqnarray" || type_ == "align" || type_ == "flalign"
420 || type_ == "alignat" || type_ == "xalignat"
421 || type_ == "gather" || type_ == "multline")
422 os << "\\end{" << type_ << star(n) << "}\n";
424 else if (type_ == "xxalignat")
425 os << "\\end{" << type_ << "}\n";
428 os << "\\end{unknown" << star(n) << '}';
432 bool MathHullInset::colChangeOK() const
435 type_ == "align" || type_ == "flalign" ||type_ == "alignat" ||
436 type_ == "xalignat" || type_ == "xxalignat";
440 void MathHullInset::addRow(row_type row)
442 nonum_.insert(nonum_.begin() + row + 1, !numberedType());
443 label_.insert(label_.begin() + row + 1, string());
444 MathGridInset::addRow(row);
448 void MathHullInset::swapRow(row_type row)
452 if (row + 1 == nrows())
454 swap(nonum_[row], nonum_[row + 1]);
455 swap(label_[row], label_[row + 1]);
456 MathGridInset::swapRow(row);
460 void MathHullInset::delRow(row_type row)
464 MathGridInset::delRow(row);
465 nonum_.erase(nonum_.begin() + row);
466 label_.erase(label_.begin() + row);
470 void MathHullInset::addCol(col_type col)
473 MathGridInset::addCol(col);
475 lyxerr << "Can't change number of columns in '" << type_ << "'" << endl;
479 void MathHullInset::delCol(col_type col)
482 MathGridInset::delCol(col);
484 lyxerr << "Can't change number of columns in '" << type_ << "'" << endl;
488 string MathHullInset::nicelabel(row_type row) const
492 if (label_[row].empty())
493 return string("(#)");
494 return '(' + label_[row] + ')';
498 void MathHullInset::glueall()
501 for (idx_type i = 0; i < nargs(); ++i)
503 *this = MathHullInset("simple");
509 string const & MathHullInset::getType() const
515 void MathHullInset::setType(string const & type)
523 void MathHullInset::mutate(string const & newtype)
525 lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
527 // we try to move along the chain
528 // none <-> simple <-> equation <-> eqnarray
530 if (newtype == "dump") {
534 else if (newtype == type_) {
538 else if (type_ == "none") {
544 else if (type_ == "simple") {
545 if (newtype == "none") {
554 else if (type_ == "equation") {
555 if (smaller(newtype, type_)) {
558 } else if (newtype == "eqnarray") {
559 MathGridInset::addCol(1);
560 MathGridInset::addCol(1);
562 // split it "nicely" on the firest relop
563 pos_type pos = firstRelOp(cell(0));
564 cell(1) = MathArray(cell(0).begin() + pos, cell(0).end());
565 cell(0).erase(pos, cell(0).size());
567 if (cell(1).size()) {
568 cell(2) = MathArray(cell(1).begin() + 1, cell(1).end());
569 cell(1).erase(1, cell(1).size());
573 } else if (newtype == "multline" || newtype == "gather") {
577 MathGridInset::addCol(1);
579 pos_type pos = firstRelOp(cell(0));
581 cell(0).erase(pos, cell(0).size());
582 cell(1).erase(0, pos);
588 else if (type_ == "eqnarray") {
589 if (smaller(newtype, type_)) {
590 // set correct (no)numbering
591 bool allnonum = true;
592 for (row_type row = 0; row < nrows(); ++row)
596 // set first non-empty label
598 for (row_type row = 0; row < nrows(); ++row) {
599 if (!label_[row].empty()) {
606 nonum_[0] = allnonum;
609 } else { // align & Co.
610 for (row_type row = 0; row < nrows(); ++row) {
611 idx_type c = 3 * row + 1;
612 cell(c).append(cell(c + 1));
614 MathGridInset::delCol(2);
620 else if (type_ == "align") {
621 if (smaller(newtype, type_)) {
622 MathGridInset::addCol(1);
630 else if (type_ == "multline") {
631 if (newtype == "gather" || newtype == "align" ||
632 newtype == "xalignat" || newtype == "xxalignat" || newtype == "flalign")
634 else if (newtype == "eqnarray") {
635 MathGridInset::addCol(1);
636 MathGridInset::addCol(1);
639 lyxerr << "mutation from '" << type_
640 << "' to '" << newtype << "' not implemented" << endl;
644 else if (type_ == "gather") {
645 if (newtype == "multline") {
648 lyxerr << "mutation from '" << type_
649 << "' to '" << newtype << "' not implemented" << endl;
654 lyxerr << "mutation from '" << type_
655 << "' to '" << newtype << "' not implemented" << endl;
660 string MathHullInset::eolString(row_type row, bool fragile) const
663 if (numberedType()) {
664 if (!label_[row].empty() && !nonum_[row])
665 res += "\\label{" + label_[row] + '}';
666 if (nonum_[row] && (type_ != "multline"))
667 res += "\\nonumber ";
669 return res + MathGridInset::eolString(row, fragile);
673 void MathHullInset::write(WriteStream & os) const
676 MathGridInset::write(os);
681 void MathHullInset::normalize(NormalStream & os) const
683 os << "[formula " << type_ << ' ';
684 MathGridInset::normalize(os);
689 void MathHullInset::mathmlize(MathMLStream & os) const
691 MathGridInset::mathmlize(os);
695 void MathHullInset::infoize(ostream & os) const
697 os << "Type: " << type_;
701 void MathHullInset::check() const
703 BOOST_ASSERT(nonum_.size() == nrows());
704 BOOST_ASSERT(label_.size() == nrows());
708 void MathHullInset::doExtern(LCursor & cur, FuncRequest const & func)
712 istringstream iss(func.argument.c_str());
713 iss >> lang >> extra;
718 #warning temporarily disabled
719 //if (cur.selection()) {
722 // lyxerr << "use selection: " << ar << endl;
723 // insert(pipeThroughExtern(lang, extra, ar));
729 eq.push_back(MathAtom(new MathCharInset('=')));
731 // go to first item in line
732 cur.idx() -= cur.idx() % ncols();
735 if (getType() == "simple") {
736 size_type pos = cur.cell().find_last(eq);
738 if (cur.inMathed() && cur.selection()) {
739 asArray(cur.grabAndEraseSelection(), ar);
740 } else if (pos == cur.cell().size()) {
742 lyxerr << "use whole cell: " << ar << endl;
744 ar = MathArray(cur.cell().begin() + pos + 1, cur.cell().end());
745 lyxerr << "use partial cell form pos: " << pos << endl;
747 cur.cell().append(eq);
748 cur.cell().append(pipeThroughExtern(lang, extra, ar));
749 cur.pos() = cur.lastpos();
753 if (getType() == "equation") {
754 lyxerr << "use equation inset" << endl;
756 MathArray & ar = cur.cell();
757 lyxerr << "use cell: " << ar << endl;
761 cur.cell() = pipeThroughExtern(lang, extra, ar);
762 // move to end of line
763 cur.pos() = cur.lastpos();
768 lyxerr << "use eqnarray" << endl;
769 cur.idx() += 2 - cur.idx() % ncols();
771 MathArray ar = cur.cell();
772 lyxerr << "use cell: " << ar << endl;
774 #warning temporarily disabled
781 cur.cell() = pipeThroughExtern(lang, extra, ar);
782 cur.pos() = cur.lastpos();
787 void MathHullInset::priv_dispatch(LCursor & cur, FuncRequest const & cmd)
789 //lyxerr << "*** MathHullInset: request: " << cmd << endl;
790 switch (cmd.action) {
793 if (type_ == "simple" || type_ == "equation") {
797 //cur.dispatched(FINISHED);
800 MathGridInset::priv_dispatch(cur, cmd);
803 case LFUN_MATH_NUMBER:
804 //lyxerr << "toggling all numbers" << endl;
806 ////recordUndo(cur, Undo::INSERT);
807 bool old = numberedType();
808 if (type_ == "multline")
809 numbered(nrows() - 1, !old);
811 for (row_type row = 0; row < nrows(); ++row)
813 cur.message(old ? _("No number") : _("Number"));
817 case LFUN_MATH_NONUMBER:
819 row_type r = (type_ == "multline") ? nrows() - 1 : cur.row();
820 ////recordUndo(cur, Undo::INSERT);
821 bool old = numbered(r);
822 cur.message(old ? _("No number") : _("Number"));
827 case LFUN_INSERT_LABEL: {
828 row_type r = (type_ == "multline") ? nrows() - 1 : cur.row();
829 string old_label = label(r);
830 string new_label = cmd.argument;
832 if (new_label.empty()) {
833 string const default_label =
834 (lyxrc.label_init_length >= 0) ? "eq:" : "";
835 pair<bool, string> const res = old_label.empty()
836 ? Alert::askForText(_("Enter new label to insert:"), default_label)
837 : Alert::askForText(_("Enter label:"), old_label);
838 new_label = lyx::support::trim(res.second);
841 if (!new_label.empty())
847 case LFUN_MATH_EXTERN:
849 //cur.dispatched(FINISHED);
852 case LFUN_MATH_MUTATE: {
853 lyxerr << "Hull: MUTATE: " << cmd.argument << endl;
854 row_type r = cur.row();
855 col_type c = cur.col();
856 mutate(cmd.argument);
857 cur.idx() = r * ncols() + c;
858 if (cur.idx() >= nargs())
859 cur.idx() = nargs() - 1;
860 if (cur.pos() > cur.lastpos())
861 cur.pos() = cur.lastpos();
862 //cur.dispatched(FINISHED);
866 case LFUN_MATH_DISPLAY: {
867 mutate(type_ == "simple" ? "equation" : "simple");
869 cur.pos() = cur.lastpos();
870 //cur.dispatched(FINISHED);
875 MathGridInset::priv_dispatch(cur, cmd);
881 string MathHullInset::fileInsetLabel() const
887 /////////////////////////////////////////////////////////////////////
889 #include "formulamacro.h"
890 #include "math_arrayinset.h"
891 #include "math_deliminset.h"
892 #include "math_factory.h"
893 #include "math_parser.h"
894 #include "math_spaceinset.h"
895 #include "ref_inset.h"
897 #include "bufferview_funcs.h"
901 #include "frontends/LyXView.h"
902 #include "frontends/Dialogs.h"
904 #include "support/std_sstream.h"
905 #include "support/lstrings.h"
906 #include "support/lyxlib.h"
909 int MathHullInset::ylow() const
911 return yo_ - dim_.asc;
915 int MathHullInset::yhigh() const
917 return yo_ + dim_.des;
921 int MathHullInset::xlow() const
927 int MathHullInset::xhigh() const
929 return xo_ + dim_.wid;
933 // simply scrap this function if you want
934 void MathHullInset::mutateToText()
937 // translate to latex
939 latex(NULL, os, false, false);
940 string str = os.str();
943 LyXText * lt = view_->getLyXText();
944 string::const_iterator cit = str.begin();
945 string::const_iterator end = str.end();
946 for (; cit != end; ++cit)
947 view_->owner()->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
950 //view_->owner()->dispatch(LFUN_ESCAPE);
955 void MathHullInset::handleFont
956 (LCursor & cur, string const & arg, string const & font)
958 // this whole function is a hack and won't work for incremental font
960 //recordUndo(cur, Undo::ATOMIC);
962 if (cur.inset()->asMathInset()->name() == font)
963 cur.handleFont(font);
965 cur.handleNest(createMathInset(font));
971 void MathHullInset::handleFont2(LCursor & cur, string const & arg)
973 //recordUndo(cur, Undo::ATOMIC);
976 bv_funcs::string2font(arg, font, b);
977 if (font.color() != LColor::inherit) {
978 MathAtom at = createMathInset("color");
979 asArray(lcolor.getGUIName(font.color()), at.nucleus()->cell(0));
980 cur.handleNest(at, 1);
985 string const MathHullInset::editMessage() const
987 return _("Math editor mode");
991 void MathHullInset::insetUnlock(BufferView & bv)
993 if (bv.cursor().inMathed()) {
994 if (bv.cursor().inMacroMode())
995 bv.cursor().macroModeClose();
998 generatePreview(*bv.buffer());
1003 void MathHullInset::getCursorDim(int & asc, int & desc) const
1007 //math_font_max_dim(font_, asc, des);
1011 void MathHullInset::revealCodes(LCursor & cur) const
1013 if (!cur.inMathed())
1017 cur.message(os.str());
1019 // write something to the minibuffer
1020 // translate to latex
1024 string str = os.str();
1026 string::size_type pos = 0;
1028 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1031 else if (*it == '\0') {
1033 pos = it - str.begin();
1039 res = res.substr(pos - 30);
1040 if (res.size() > 60)
1041 res = res.substr(0, 60);
1047 InsetBase::Code MathHullInset::lyxCode() const
1053 /////////////////////////////////////////////////////////////////////
1057 bool MathHullInset::searchForward(BufferView *, string const &, bool, bool)
1063 bool MathHullInset::searchForward(BufferView * bv, string const & str,
1067 #ifdef WITH_WARNINGS
1068 #warning pretty ugly
1070 static MathHullInset * lastformula = 0;
1071 static CursorBase current = CursorBase(ibegin(nucleus()));
1072 static MathArray ar;
1073 static string laststr;
1075 if (lastformula != this || laststr != str) {
1076 //lyxerr << "reset lastformula to " << this << endl;
1079 current = ibegin(nucleus());
1081 mathed_parse_cell(ar, str);
1085 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1087 for (CursorBase it = current; it != iend(nucleus()); increment(it)) {
1088 CursorSlice & top = it.back();
1089 MathArray const & a = top.asMathInset()->cell(top.idx_);
1090 if (a.matchpart(ar, top.pos_)) {
1091 bv->cursor().setSelection(it, ar.size());
1093 top.pos_ += ar.size();
1099 //lyxerr << "not found!" << endl;
1106 bool MathHullInset::searchBackward(BufferView * bv, string const & what,
1109 lyxerr[Debug::MATHED]
1110 << "searching backward not implemented in mathed" << endl;
1111 return searchForward(bv, what, a, b);
1115 void MathHullInset::write(Buffer const &, std::ostream & os) const
1117 WriteStream wi(os, false, false);
1118 os << fileInsetLabel() << ' ';
1123 void MathHullInset::read(Buffer const &, LyXLex & lex)
1126 mathed_parse_normal(at, lex);
1127 operator=(*at->asHullInset());
1131 int MathHullInset::latex(Buffer const &, ostream & os,
1132 OutputParams const & runparams) const
1134 WriteStream wi(os, runparams.moving_arg, true);
1140 int MathHullInset::plaintext(Buffer const &, ostream & os,
1141 OutputParams const &) const
1143 if (0 && display()) {
1147 TextPainter tpain(dim.width(), dim.height());
1148 drawT(tpain, 0, dim.ascent());
1150 // reset metrics cache to "real" values
1152 return tpain.textheight();
1154 WriteStream wi(os, false, true);
1155 wi << ' ' << cell(0) << ' ';
1161 int MathHullInset::linuxdoc(Buffer const & buf, ostream & os,
1162 OutputParams const & runparams) const
1164 return docbook(buf, os, runparams);
1168 int MathHullInset::docbook(Buffer const & buf, ostream & os,
1169 OutputParams const & runparams) const
1171 MathMLStream ms(os);
1172 ms << MTag("equation");
1175 int res = plaintext(buf, ms.os(), runparams);
1179 MathGridInset::mathmlize(ms);
1181 ms << ETag("equation");
1182 return ms.line() + res;