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"
34 #include "frontends/Alert.h"
36 #include "support/std_sstream.h"
44 using std::istringstream;
46 using std::ostringstream;
54 int getCols(string const & type)
56 if (type == "eqnarray")
60 if (type == "flalign")
62 if (type == "alignat")
64 if (type == "xalignat")
66 if (type == "xxalignat")
72 // returns position of first relation operator in the array
73 // used for "intelligent splitting"
74 size_t firstRelOp(MathArray const & ar)
76 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
78 return it - ar.begin();
83 char const * star(bool numbered)
85 return numbered ? "" : "*";
89 int typecode(string const & s)
91 if (s == "none") return 0;
92 if (s == "simple") return 1;
93 if (s == "equation") return 2;
94 if (s == "eqnarray") return 3;
95 if (s == "align") return 4;
96 if (s == "alignat") return 5;
97 if (s == "xalignat") return 6;
98 if (s == "xxalignat") return 7;
99 if (s == "multline") return 8;
100 if (s == "gather") return 9;
101 if (s == "flalign") return 10;
102 lyxerr << "unknown hull type '" << s << "'" << endl;
106 bool smaller(string const & s, string const & t)
108 return typecode(s) < typecode(t);
112 } // end anon namespace
116 MathHullInset::MathHullInset()
117 : MathGridInset(1, 1), type_("none"), nonum_(1), label_(1)
119 // This is needed as long the math parser is not re-entrant
121 //lyxerr << "sizeof MathInset: " << sizeof(MathInset) << endl;
122 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
123 //lyxerr << "sizeof MathCharInset: " << sizeof(MathCharInset) << endl;
124 //lyxerr << "sizeof LyXFont: " << sizeof(LyXFont) << endl;
129 MathHullInset::MathHullInset(string const & type)
130 : MathGridInset(getCols(type), 1), type_(type), nonum_(1), label_(1)
136 auto_ptr<InsetBase> MathHullInset::clone() const
138 return auto_ptr<InsetBase>(new MathHullInset(*this));
142 MathInset::mode_type MathHullInset::currentMode() const
145 return UNDECIDED_MODE;
146 // definitely math mode ...
151 bool MathHullInset::idxFirst(LCursor & cur) const
159 bool MathHullInset::idxLast(LCursor & cur) const
161 cur.idx() = nargs() - 1;
162 cur.pos() = cur.lastpos();
167 char MathHullInset::defaultColAlign(col_type col)
169 if (type_ == "eqnarray")
171 if (typecode(type_) >= typecode("align"))
172 return "rl"[col & 1];
177 int MathHullInset::defaultColSpace(col_type col)
179 if (type_ == "align" || type_ == "alignat")
181 if (type_ == "xalignat")
182 return (col & 1) ? 20 : 0;
183 if (type_ == "xxalignat" || type_ == "flalign")
184 return (col & 1) ? 40 : 0;
189 char const * MathHullInset::standardFont() const
192 return "lyxnochange";
197 void MathHullInset::metrics(MetricsInfo & mi, Dimension & dim) const
199 FontSetChanger dummy1(mi.base, standardFont());
200 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
202 // let the cells adjust themselves
203 MathGridInset::metrics(mi, dim);
210 if (numberedType()) {
211 FontSetChanger dummy(mi.base, "mathbf");
213 for (row_type row = 0; row < nrows(); ++row)
214 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
220 // make it at least as high as the current font
223 math_font_max_dim(mi.base.font, asc, des);
224 dim.asc = max(dim.asc, asc);
225 dim.des = max(dim.des, des);
231 void MathHullInset::draw(PainterInfo & pi, int x, int y) const
233 FontSetChanger dummy1(pi.base, standardFont());
234 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
235 MathGridInset::draw(pi, x + 1, y);
237 if (numberedType()) {
238 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
239 for (row_type row = 0; row < nrows(); ++row) {
240 int const yy = y + rowinfo_[row].offset_;
241 FontSetChanger dummy(pi.base, "mathrm");
242 drawStr(pi, pi.base.font, xx, yy, nicelabel(row));
245 setPosCache(pi, x, y);
249 void MathHullInset::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
252 MathGridInset::metricsT(mi, dim);
255 WriteStream wi(os, false, true);
257 dim.wid = os.str().size();
264 void MathHullInset::drawT(TextPainter & pain, int x, int y) const
267 MathGridInset::drawT(pain, x, y);
270 WriteStream wi(os, false, true);
272 pain.draw(x, y, os.str().c_str());
277 string MathHullInset::label(row_type row) const
279 row_type n = nrows();
280 BOOST_ASSERT(row < n);
285 void MathHullInset::label(row_type row, string const & label)
287 //lyxerr << "setting label '" << label << "' for row " << row << endl;
292 void MathHullInset::numbered(row_type row, bool num)
298 bool MathHullInset::numbered(row_type row) const
304 bool MathHullInset::ams() const
308 type_ == "flalign" ||
309 type_ == "multline" ||
311 type_ == "alignat" ||
312 type_ == "xalignat" ||
313 type_ == "xxalignat";
317 bool MathHullInset::display() const
319 return type_ != "simple" && type_ != "none";
323 void MathHullInset::getLabelList(Buffer const &, vector<string> & labels) const
325 for (row_type row = 0; row < nrows(); ++row)
326 if (!label_[row].empty() && nonum_[row] != 1)
327 labels.push_back(label_[row]);
331 bool MathHullInset::numberedType() const
335 if (type_ == "simple")
337 if (type_ == "xxalignat")
339 for (row_type row = 0; row < nrows(); ++row)
346 void MathHullInset::validate(LaTeXFeatures & features) const
349 features.require("amsmath");
352 // Validation is necessary only if not using AMS math.
353 // To be safe, we will always run mathedvalidate.
354 //if (features.amsstyle)
357 features.require("boldsymbol");
358 //features.binom = true;
360 MathGridInset::validate(features);
364 void MathHullInset::header_write(WriteStream & os) const
366 bool n = numberedType();
371 else if (type_ == "simple") {
377 else if (type_ == "equation") {
379 os << "\\begin{equation" << star(n) << "}\n";
384 else if (type_ == "eqnarray" || type_ == "align" || type_ == "flalign"
385 || type_ == "gather" || type_ == "multline")
386 os << "\\begin{" << type_ << star(n) << "}\n";
388 else if (type_ == "alignat" || type_ == "xalignat")
389 os << "\\begin{" << type_ << star(n) << '}'
390 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
392 else if (type_ == "xxalignat")
393 os << "\\begin{" << type_ << '}'
394 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
397 os << "\\begin{unknown" << star(n) << '}';
401 void MathHullInset::footer_write(WriteStream & os) const
403 bool n = numberedType();
408 else if (type_ == "simple")
411 else if (type_ == "equation")
413 os << "\\end{equation" << star(n) << "}\n";
417 else if (type_ == "eqnarray" || type_ == "align" || type_ == "flalign"
418 || type_ == "alignat" || type_ == "xalignat"
419 || type_ == "gather" || type_ == "multline")
420 os << "\\end{" << type_ << star(n) << "}\n";
422 else if (type_ == "xxalignat")
423 os << "\\end{" << type_ << "}\n";
426 os << "\\end{unknown" << star(n) << '}';
430 bool MathHullInset::colChangeOK() const
433 type_ == "align" || type_ == "flalign" ||type_ == "alignat" ||
434 type_ == "xalignat" || type_ == "xxalignat";
438 void MathHullInset::addRow(row_type row)
440 nonum_.insert(nonum_.begin() + row + 1, !numberedType());
441 label_.insert(label_.begin() + row + 1, string());
442 MathGridInset::addRow(row);
446 void MathHullInset::swapRow(row_type row)
450 if (row + 1 == nrows())
452 swap(nonum_[row], nonum_[row + 1]);
453 swap(label_[row], label_[row + 1]);
454 MathGridInset::swapRow(row);
458 void MathHullInset::delRow(row_type row)
462 MathGridInset::delRow(row);
463 nonum_.erase(nonum_.begin() + row);
464 label_.erase(label_.begin() + row);
468 void MathHullInset::addCol(col_type col)
471 MathGridInset::addCol(col);
473 lyxerr << "Can't change number of columns in '" << type_ << "'" << endl;
477 void MathHullInset::delCol(col_type col)
480 MathGridInset::delCol(col);
482 lyxerr << "Can't change number of columns in '" << type_ << "'" << endl;
486 string MathHullInset::nicelabel(row_type row) const
490 if (label_[row].empty())
491 return string("(#)");
492 return '(' + label_[row] + ')';
496 void MathHullInset::glueall()
499 for (idx_type i = 0; i < nargs(); ++i)
501 *this = MathHullInset("simple");
507 string const & MathHullInset::getType() const
513 void MathHullInset::setType(string const & type)
521 void MathHullInset::mutate(string const & newtype)
523 lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
525 // we try to move along the chain
526 // none <-> simple <-> equation <-> eqnarray
528 if (newtype == "dump") {
532 else if (newtype == type_) {
536 else if (type_ == "none") {
542 else if (type_ == "simple") {
543 if (newtype == "none") {
552 else if (type_ == "equation") {
553 if (smaller(newtype, type_)) {
556 } else if (newtype == "eqnarray") {
557 MathGridInset::addCol(1);
558 MathGridInset::addCol(1);
560 // split it "nicely" on the firest relop
561 pos_type pos = firstRelOp(cell(0));
562 cell(1) = MathArray(cell(0).begin() + pos, cell(0).end());
563 cell(0).erase(pos, cell(0).size());
565 if (cell(1).size()) {
566 cell(2) = MathArray(cell(1).begin() + 1, cell(1).end());
567 cell(1).erase(1, cell(1).size());
571 } else if (newtype == "multline" || newtype == "gather") {
575 MathGridInset::addCol(1);
577 pos_type pos = firstRelOp(cell(0));
579 cell(0).erase(pos, cell(0).size());
580 cell(1).erase(0, pos);
586 else if (type_ == "eqnarray") {
587 if (smaller(newtype, type_)) {
588 // set correct (no)numbering
589 bool allnonum = true;
590 for (row_type row = 0; row < nrows(); ++row)
594 // set first non-empty label
596 for (row_type row = 0; row < nrows(); ++row) {
597 if (!label_[row].empty()) {
604 nonum_[0] = allnonum;
607 } else { // align & Co.
608 for (row_type row = 0; row < nrows(); ++row) {
609 idx_type c = 3 * row + 1;
610 cell(c).append(cell(c + 1));
612 MathGridInset::delCol(2);
618 else if (type_ == "align") {
619 if (smaller(newtype, type_)) {
620 MathGridInset::addCol(1);
628 else if (type_ == "multline") {
629 if (newtype == "gather" || newtype == "align" ||
630 newtype == "xalignat" || newtype == "xxalignat" || newtype == "flalign")
632 else if (newtype == "eqnarray") {
633 MathGridInset::addCol(1);
634 MathGridInset::addCol(1);
637 lyxerr << "mutation from '" << type_
638 << "' to '" << newtype << "' not implemented" << endl;
642 else if (type_ == "gather") {
643 if (newtype == "multline") {
646 lyxerr << "mutation from '" << type_
647 << "' to '" << newtype << "' not implemented" << endl;
652 lyxerr << "mutation from '" << type_
653 << "' to '" << newtype << "' not implemented" << endl;
658 string MathHullInset::eolString(row_type row, bool fragile) const
661 if (numberedType()) {
662 if (!label_[row].empty() && !nonum_[row])
663 res += "\\label{" + label_[row] + '}';
664 if (nonum_[row] && (type_ != "multline"))
665 res += "\\nonumber ";
667 return res + MathGridInset::eolString(row, fragile);
671 void MathHullInset::write(WriteStream & os) const
674 MathGridInset::write(os);
679 void MathHullInset::normalize(NormalStream & os) const
681 os << "[formula " << type_ << ' ';
682 MathGridInset::normalize(os);
687 void MathHullInset::mathmlize(MathMLStream & os) const
689 MathGridInset::mathmlize(os);
693 void MathHullInset::infoize(ostream & os) const
695 os << "Type: " << type_;
699 void MathHullInset::check() const
701 BOOST_ASSERT(nonum_.size() == nrows());
702 BOOST_ASSERT(label_.size() == nrows());
706 void MathHullInset::doExtern(LCursor & cur, FuncRequest & func)
710 istringstream iss(func.argument.c_str());
711 iss >> lang >> extra;
716 #warning temporarily disabled
717 //if (cur.selection()) {
720 // lyxerr << "use selection: " << ar << endl;
721 // insert(pipeThroughExtern(lang, extra, ar));
727 eq.push_back(MathAtom(new MathCharInset('=')));
729 // go to first item in line
730 cur.idx() -= cur.idx() % ncols();
733 if (getType() == "simple") {
734 size_type pos = cur.cell().find_last(eq);
736 if (cur.inMathed() && cur.selection()) {
737 asArray(cur.grabAndEraseSelection(), ar);
738 } else if (pos == cur.cell().size()) {
740 lyxerr << "use whole cell: " << ar << endl;
742 ar = MathArray(cur.cell().begin() + pos + 1, cur.cell().end());
743 lyxerr << "use partial cell form pos: " << pos << endl;
745 cur.cell().append(eq);
746 cur.cell().append(pipeThroughExtern(lang, extra, ar));
747 cur.pos() = cur.lastpos();
751 if (getType() == "equation") {
752 lyxerr << "use equation inset" << endl;
754 MathArray & ar = cur.cell();
755 lyxerr << "use cell: " << ar << endl;
759 cur.cell() = pipeThroughExtern(lang, extra, ar);
760 // move to end of line
761 cur.pos() = cur.lastpos();
766 lyxerr << "use eqnarray" << endl;
767 cur.idx() += 2 - cur.idx() % ncols();
769 MathArray ar = cur.cell();
770 lyxerr << "use cell: " << ar << endl;
772 #warning temporarily disabled
779 cur.cell() = pipeThroughExtern(lang, extra, ar);
780 cur.pos() = cur.lastpos();
785 void MathHullInset::priv_dispatch(LCursor & cur, FuncRequest & cmd)
787 switch (cmd.action) {
789 case LFUN_BREAKPARAGRAPH:
794 if (type_ == "simple" || type_ == "equation") {
798 //cur.dispatched(FINISHED);
801 MathGridInset::priv_dispatch(cur, cmd);
804 case LFUN_MATH_NUMBER:
805 //lyxerr << "toggling all numbers" << endl;
808 bool old = numberedType();
809 if (type_ == "multline")
810 numbered(nrows() - 1, !old);
812 for (row_type row = 0; row < nrows(); ++row)
814 cur.message(old ? _("No number") : _("Number"));
818 case LFUN_MATH_NONUMBER:
820 row_type r = (type_ == "multline") ? nrows() - 1 : cur.row();
822 bool old = numbered(r);
823 cur.message(old ? _("No number") : _("Number"));
828 case LFUN_INSERT_LABEL: {
829 row_type r = (type_ == "multline") ? nrows() - 1 : cur.row();
830 string old_label = label(r);
831 string new_label = cmd.argument;
833 if (new_label.empty()) {
834 string const default_label =
835 (lyxrc.label_init_length >= 0) ? "eq:" : "";
836 pair<bool, string> const res = old_label.empty()
837 ? Alert::askForText(_("Enter new label to insert:"), default_label)
838 : Alert::askForText(_("Enter label:"), old_label);
839 new_label = lyx::support::trim(res.second);
842 if (!new_label.empty())
848 case LFUN_MATH_EXTERN:
850 //cur.dispatched(FINISHED);
853 case LFUN_MATH_MUTATE: {
854 lyxerr << "Hull: MUTATE: " << cmd.argument << endl;
855 row_type row = cur.row();
856 col_type col = cur.col();
857 mutate(cmd.argument);
858 cur.idx() = row * ncols() + col;
859 if (cur.idx() > cur.lastidx()) {
860 cur.idx() = cur.lastidx();
861 cur.pos() = cur.lastpos();
863 if (cur.pos() > cur.lastpos())
864 cur.pos() = cur.lastpos();
865 //cur.dispatched(FINISHED);
869 case LFUN_MATH_DISPLAY: {
870 mutate(type_ == "simple" ? "equation" : "simple");
872 cur.pos() = cur.lastpos();
873 //cur.dispatched(FINISHED);
878 MathGridInset::priv_dispatch(cur, cmd);
884 bool MathHullInset::getStatus(LCursor & cur, FuncRequest const & cmd,
885 FuncStatus & flag) const
887 switch (cmd.action) {
889 case LFUN_MATH_NUMBER:
890 case LFUN_MATH_NONUMBER:
891 case LFUN_INSERT_LABEL:
892 case LFUN_MATH_EXTERN:
893 case LFUN_MATH_MUTATE:
894 case LFUN_MATH_DISPLAY:
898 return MathGridInset::getStatus(cur, cmd, flag);
903 /////////////////////////////////////////////////////////////////////
905 #include "formulamacro.h"
906 #include "math_arrayinset.h"
907 #include "math_deliminset.h"
908 #include "math_factory.h"
909 #include "math_parser.h"
910 #include "math_spaceinset.h"
911 #include "ref_inset.h"
913 #include "bufferview_funcs.h"
917 #include "frontends/LyXView.h"
918 #include "frontends/Dialogs.h"
920 #include "support/std_sstream.h"
921 #include "support/lstrings.h"
922 #include "support/lyxlib.h"
925 // simply scrap this function if you want
926 void MathHullInset::mutateToText()
929 // translate to latex
931 latex(NULL, os, false, false);
932 string str = os.str();
935 LyXText * lt = view_->getLyXText();
936 string::const_iterator cit = str.begin();
937 string::const_iterator end = str.end();
938 for (; cit != end; ++cit)
939 view_->owner()->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
942 //view_->owner()->dispatch(LFUN_ESCAPE);
947 void MathHullInset::handleFont(LCursor & cur, string const & arg,
950 // this whole function is a hack and won't work for incremental font
953 if (cur.inset().asMathInset()->name() == font)
954 cur.handleFont(font);
956 cur.handleNest(createMathInset(font));
962 void MathHullInset::handleFont2(LCursor & cur, string const & arg)
967 bv_funcs::string2font(arg, font, b);
968 if (font.color() != LColor::inherit) {
969 MathAtom at = createMathInset("color");
970 asArray(lcolor.getGUIName(font.color()), at.nucleus()->cell(0));
971 cur.handleNest(at, 1);
976 void MathHullInset::edit(LCursor & cur, bool left)
978 lyxerr << "MathHullInset: edit left/right" << endl;
983 string const MathHullInset::editMessage() const
985 return _("Math editor mode");
989 void MathHullInset::getCursorDim(int & asc, int & desc) const
993 //math_font_max_dim(font_, asc, des);
997 void MathHullInset::revealCodes(LCursor & cur) const
1003 cur.message(os.str());
1005 // write something to the minibuffer
1006 // translate to latex
1010 string str = os.str();
1012 string::size_type pos = 0;
1014 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1017 else if (*it == '\0') {
1019 pos = it - str.begin();
1025 res = res.substr(pos - 30);
1026 if (res.size() > 60)
1027 res = res.substr(0, 60);
1033 InsetBase::Code MathHullInset::lyxCode() const
1039 /////////////////////////////////////////////////////////////////////
1043 bool MathHullInset::searchForward(BufferView *, string const &, bool, bool)
1049 bool MathHullInset::searchForward(BufferView * bv, string const & str,
1053 #ifdef WITH_WARNINGS
1054 #warning pretty ugly
1056 static MathHullInset * lastformula = 0;
1057 static CursorBase current = DocIterator(ibegin(nucleus()));
1058 static MathArray ar;
1059 static string laststr;
1061 if (lastformula != this || laststr != str) {
1062 //lyxerr << "reset lastformula to " << this << endl;
1065 current = ibegin(nucleus());
1067 mathed_parse_cell(ar, str);
1071 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1073 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1074 CursorSlice & top = it.back();
1075 MathArray const & a = top.asMathInset()->cell(top.idx_);
1076 if (a.matchpart(ar, top.pos_)) {
1077 bv->cursor().setSelection(it, ar.size());
1079 top.pos_ += ar.size();
1085 //lyxerr << "not found!" << endl;
1092 bool MathHullInset::searchBackward(BufferView * bv, string const & what,
1095 lyxerr[Debug::MATHED]
1096 << "searching backward not implemented in mathed" << endl;
1097 return searchForward(bv, what, a, b);
1101 void MathHullInset::write(Buffer const &, std::ostream & os) const
1103 WriteStream wi(os, false, false);
1109 void MathHullInset::read(Buffer const &, LyXLex & lex)
1112 mathed_parse_normal(at, lex);
1113 operator=(*at->asHullInset());
1117 int MathHullInset::plaintext(Buffer const &, ostream & os,
1118 OutputParams const &) const
1120 if (0 && display()) {
1124 TextPainter tpain(dim.width(), dim.height());
1125 drawT(tpain, 0, dim.ascent());
1127 // reset metrics cache to "real" values
1129 return tpain.textheight();
1131 WriteStream wi(os, false, true);
1132 wi << ' ' << cell(0) << ' ';
1138 int MathHullInset::linuxdoc(Buffer const & buf, ostream & os,
1139 OutputParams const & runparams) const
1141 return docbook(buf, os, runparams);
1145 int MathHullInset::docbook(Buffer const & buf, ostream & os,
1146 OutputParams const & runparams) const
1148 MathMLStream ms(os);
1149 ms << MTag("equation");
1152 int res = plaintext(buf, ms.os(), runparams);
1156 MathGridInset::mathmlize(ms);
1158 ms << ETag("equation");
1159 return ms.line() + res;