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));
248 void MathHullInset::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
251 MathGridInset::metricsT(mi, dim);
254 WriteStream wi(os, false, true);
256 dim.wid = os.str().size();
263 void MathHullInset::drawT(TextPainter & pain, int x, int y) const
266 MathGridInset::drawT(pain, x, y);
269 WriteStream wi(os, false, true);
271 pain.draw(x, y, os.str().c_str());
276 string MathHullInset::label(row_type row) const
278 row_type n = nrows();
279 BOOST_ASSERT(row < n);
284 void MathHullInset::label(row_type row, string const & label)
286 //lyxerr << "setting label '" << label << "' for row " << row << endl;
291 void MathHullInset::numbered(row_type row, bool num)
297 bool MathHullInset::numbered(row_type row) const
303 bool MathHullInset::ams() const
307 type_ == "flalign" ||
308 type_ == "multline" ||
310 type_ == "alignat" ||
311 type_ == "xalignat" ||
312 type_ == "xxalignat";
316 bool MathHullInset::display() const
318 return type_ != "simple" && type_ != "none";
322 void MathHullInset::getLabelList(Buffer const &, vector<string> & labels) const
324 for (row_type row = 0; row < nrows(); ++row)
325 if (!label_[row].empty() && nonum_[row] != 1)
326 labels.push_back(label_[row]);
330 bool MathHullInset::numberedType() const
334 if (type_ == "simple")
336 if (type_ == "xxalignat")
338 for (row_type row = 0; row < nrows(); ++row)
345 void MathHullInset::validate(LaTeXFeatures & features) const
348 features.require("amsmath");
351 // Validation is necessary only if not using AMS math.
352 // To be safe, we will always run mathedvalidate.
353 //if (features.amsstyle)
356 features.require("boldsymbol");
357 //features.binom = true;
359 MathGridInset::validate(features);
363 void MathHullInset::header_write(WriteStream & os) const
365 bool n = numberedType();
370 else if (type_ == "simple") {
376 else if (type_ == "equation") {
378 os << "\\begin{equation" << star(n) << "}\n";
383 else if (type_ == "eqnarray" || type_ == "align" || type_ == "flalign"
384 || type_ == "gather" || type_ == "multline")
385 os << "\\begin{" << type_ << star(n) << "}\n";
387 else if (type_ == "alignat" || type_ == "xalignat")
388 os << "\\begin{" << type_ << star(n) << '}'
389 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
391 else if (type_ == "xxalignat")
392 os << "\\begin{" << type_ << '}'
393 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
396 os << "\\begin{unknown" << star(n) << '}';
400 void MathHullInset::footer_write(WriteStream & os) const
402 bool n = numberedType();
407 else if (type_ == "simple")
410 else if (type_ == "equation")
412 os << "\\end{equation" << star(n) << "}\n";
416 else if (type_ == "eqnarray" || type_ == "align" || type_ == "flalign"
417 || type_ == "alignat" || type_ == "xalignat"
418 || type_ == "gather" || type_ == "multline")
419 os << "\\end{" << type_ << star(n) << "}\n";
421 else if (type_ == "xxalignat")
422 os << "\\end{" << type_ << "}\n";
425 os << "\\end{unknown" << star(n) << '}';
429 bool MathHullInset::colChangeOK() const
432 type_ == "align" || type_ == "flalign" ||type_ == "alignat" ||
433 type_ == "xalignat" || type_ == "xxalignat";
437 void MathHullInset::addRow(row_type row)
439 nonum_.insert(nonum_.begin() + row + 1, !numberedType());
440 label_.insert(label_.begin() + row + 1, string());
441 MathGridInset::addRow(row);
445 void MathHullInset::swapRow(row_type row)
449 if (row + 1 == nrows())
451 swap(nonum_[row], nonum_[row + 1]);
452 swap(label_[row], label_[row + 1]);
453 MathGridInset::swapRow(row);
457 void MathHullInset::delRow(row_type row)
461 MathGridInset::delRow(row);
462 nonum_.erase(nonum_.begin() + row);
463 label_.erase(label_.begin() + row);
467 void MathHullInset::addCol(col_type col)
470 MathGridInset::addCol(col);
472 lyxerr << "Can't change number of columns in '" << type_ << "'" << endl;
476 void MathHullInset::delCol(col_type col)
479 MathGridInset::delCol(col);
481 lyxerr << "Can't change number of columns in '" << type_ << "'" << endl;
485 string MathHullInset::nicelabel(row_type row) const
489 if (label_[row].empty())
490 return string("(#)");
491 return '(' + label_[row] + ')';
495 void MathHullInset::glueall()
498 for (idx_type i = 0; i < nargs(); ++i)
500 *this = MathHullInset("simple");
506 string const & MathHullInset::getType() const
512 void MathHullInset::setType(string const & type)
520 void MathHullInset::mutate(string const & newtype)
522 lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
524 // we try to move along the chain
525 // none <-> simple <-> equation <-> eqnarray
527 if (newtype == "dump") {
531 else if (newtype == type_) {
535 else if (type_ == "none") {
541 else if (type_ == "simple") {
542 if (newtype == "none") {
551 else if (type_ == "equation") {
552 if (smaller(newtype, type_)) {
555 } else if (newtype == "eqnarray") {
556 MathGridInset::addCol(1);
557 MathGridInset::addCol(1);
559 // split it "nicely" on the firest relop
560 pos_type pos = firstRelOp(cell(0));
561 cell(1) = MathArray(cell(0).begin() + pos, cell(0).end());
562 cell(0).erase(pos, cell(0).size());
564 if (cell(1).size()) {
565 cell(2) = MathArray(cell(1).begin() + 1, cell(1).end());
566 cell(1).erase(1, cell(1).size());
570 } else if (newtype == "multline" || newtype == "gather") {
574 MathGridInset::addCol(1);
576 pos_type pos = firstRelOp(cell(0));
578 cell(0).erase(pos, cell(0).size());
579 cell(1).erase(0, pos);
585 else if (type_ == "eqnarray") {
586 if (smaller(newtype, type_)) {
587 // set correct (no)numbering
588 bool allnonum = true;
589 for (row_type row = 0; row < nrows(); ++row)
593 // set first non-empty label
595 for (row_type row = 0; row < nrows(); ++row) {
596 if (!label_[row].empty()) {
603 nonum_[0] = allnonum;
606 } else { // align & Co.
607 for (row_type row = 0; row < nrows(); ++row) {
608 idx_type c = 3 * row + 1;
609 cell(c).append(cell(c + 1));
611 MathGridInset::delCol(2);
617 else if (type_ == "align") {
618 if (smaller(newtype, type_)) {
619 MathGridInset::addCol(1);
627 else if (type_ == "multline") {
628 if (newtype == "gather" || newtype == "align" ||
629 newtype == "xalignat" || newtype == "xxalignat" || newtype == "flalign")
631 else if (newtype == "eqnarray") {
632 MathGridInset::addCol(1);
633 MathGridInset::addCol(1);
636 lyxerr << "mutation from '" << type_
637 << "' to '" << newtype << "' not implemented" << endl;
641 else if (type_ == "gather") {
642 if (newtype == "multline") {
645 lyxerr << "mutation from '" << type_
646 << "' to '" << newtype << "' not implemented" << endl;
651 lyxerr << "mutation from '" << type_
652 << "' to '" << newtype << "' not implemented" << endl;
657 string MathHullInset::eolString(row_type row, bool fragile) const
660 if (numberedType()) {
661 if (!label_[row].empty() && !nonum_[row])
662 res += "\\label{" + label_[row] + '}';
663 if (nonum_[row] && (type_ != "multline"))
664 res += "\\nonumber ";
666 return res + MathGridInset::eolString(row, fragile);
670 void MathHullInset::write(WriteStream & os) const
673 MathGridInset::write(os);
678 void MathHullInset::normalize(NormalStream & os) const
680 os << "[formula " << type_ << ' ';
681 MathGridInset::normalize(os);
686 void MathHullInset::mathmlize(MathMLStream & os) const
688 MathGridInset::mathmlize(os);
692 void MathHullInset::infoize(ostream & os) const
694 os << "Type: " << type_;
698 void MathHullInset::check() const
700 BOOST_ASSERT(nonum_.size() == nrows());
701 BOOST_ASSERT(label_.size() == nrows());
705 void MathHullInset::doExtern(LCursor & cur, FuncRequest & func)
709 istringstream iss(func.argument.c_str());
710 iss >> lang >> extra;
715 #warning temporarily disabled
716 //if (cur.selection()) {
719 // lyxerr << "use selection: " << ar << endl;
720 // insert(pipeThroughExtern(lang, extra, ar));
726 eq.push_back(MathAtom(new MathCharInset('=')));
728 // go to first item in line
729 cur.idx() -= cur.idx() % ncols();
732 if (getType() == "simple") {
733 size_type pos = cur.cell().find_last(eq);
735 if (cur.inMathed() && cur.selection()) {
736 asArray(cur.grabAndEraseSelection(), ar);
737 } else if (pos == cur.cell().size()) {
739 lyxerr << "use whole cell: " << ar << endl;
741 ar = MathArray(cur.cell().begin() + pos + 1, cur.cell().end());
742 lyxerr << "use partial cell form pos: " << pos << endl;
744 cur.cell().append(eq);
745 cur.cell().append(pipeThroughExtern(lang, extra, ar));
746 cur.pos() = cur.lastpos();
750 if (getType() == "equation") {
751 lyxerr << "use equation inset" << endl;
753 MathArray & ar = cur.cell();
754 lyxerr << "use cell: " << ar << endl;
758 cur.cell() = pipeThroughExtern(lang, extra, ar);
759 // move to end of line
760 cur.pos() = cur.lastpos();
765 lyxerr << "use eqnarray" << endl;
766 cur.idx() += 2 - cur.idx() % ncols();
768 MathArray ar = cur.cell();
769 lyxerr << "use cell: " << ar << endl;
771 #warning temporarily disabled
778 cur.cell() = pipeThroughExtern(lang, extra, ar);
779 cur.pos() = cur.lastpos();
784 void MathHullInset::priv_dispatch(LCursor & cur, FuncRequest & cmd)
786 //lyxerr << "*** MathHullInset: request: " << cmd << endl;
787 switch (cmd.action) {
790 if (type_ == "simple" || type_ == "equation") {
794 //cur.dispatched(FINISHED);
797 MathGridInset::priv_dispatch(cur, cmd);
800 case LFUN_MATH_NUMBER:
801 //lyxerr << "toggling all numbers" << endl;
804 bool old = numberedType();
805 if (type_ == "multline")
806 numbered(nrows() - 1, !old);
808 for (row_type row = 0; row < nrows(); ++row)
810 cur.message(old ? _("No number") : _("Number"));
814 case LFUN_MATH_NONUMBER:
816 row_type r = (type_ == "multline") ? nrows() - 1 : cur.row();
818 bool old = numbered(r);
819 cur.message(old ? _("No number") : _("Number"));
824 case LFUN_INSERT_LABEL: {
825 row_type r = (type_ == "multline") ? nrows() - 1 : cur.row();
826 string old_label = label(r);
827 string new_label = cmd.argument;
829 if (new_label.empty()) {
830 string const default_label =
831 (lyxrc.label_init_length >= 0) ? "eq:" : "";
832 pair<bool, string> const res = old_label.empty()
833 ? Alert::askForText(_("Enter new label to insert:"), default_label)
834 : Alert::askForText(_("Enter label:"), old_label);
835 new_label = lyx::support::trim(res.second);
838 if (!new_label.empty())
844 case LFUN_MATH_EXTERN:
846 //cur.dispatched(FINISHED);
849 case LFUN_MATH_MUTATE: {
850 lyxerr << "Hull: MUTATE: " << cmd.argument << endl;
851 row_type row = cur.row();
852 col_type col = cur.col();
853 mutate(cmd.argument);
854 cur.idx() = row * ncols() + col;
855 if (cur.idx() > cur.lastidx()) {
856 cur.idx() = cur.lastidx();
857 cur.pos() = cur.lastpos();
859 if (cur.pos() > cur.lastpos())
860 cur.pos() = cur.lastpos();
861 //cur.dispatched(FINISHED);
865 case LFUN_MATH_DISPLAY: {
866 mutate(type_ == "simple" ? "equation" : "simple");
868 cur.pos() = cur.lastpos();
869 //cur.dispatched(FINISHED);
874 MathGridInset::priv_dispatch(cur, cmd);
880 bool MathHullInset::getStatus(LCursor & cur, FuncRequest const & cmd,
881 FuncStatus & flag) const
883 switch (cmd.action) {
885 case LFUN_MATH_NUMBER:
886 case LFUN_MATH_NONUMBER:
887 case LFUN_INSERT_LABEL:
888 case LFUN_MATH_EXTERN:
889 case LFUN_MATH_MUTATE:
890 case LFUN_MATH_DISPLAY:
894 return MathGridInset::getStatus(cur, cmd, flag);
899 string MathHullInset::fileInsetLabel() const
905 /////////////////////////////////////////////////////////////////////
907 #include "formulamacro.h"
908 #include "math_arrayinset.h"
909 #include "math_deliminset.h"
910 #include "math_factory.h"
911 #include "math_parser.h"
912 #include "math_spaceinset.h"
913 #include "ref_inset.h"
915 #include "bufferview_funcs.h"
919 #include "frontends/LyXView.h"
920 #include "frontends/Dialogs.h"
922 #include "support/std_sstream.h"
923 #include "support/lstrings.h"
924 #include "support/lyxlib.h"
927 // simply scrap this function if you want
928 void MathHullInset::mutateToText()
931 // translate to latex
933 latex(NULL, os, false, false);
934 string str = os.str();
937 LyXText * lt = view_->getLyXText();
938 string::const_iterator cit = str.begin();
939 string::const_iterator end = str.end();
940 for (; cit != end; ++cit)
941 view_->owner()->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
944 //view_->owner()->dispatch(LFUN_ESCAPE);
949 void MathHullInset::handleFont(LCursor & cur, string const & arg,
952 // this whole function is a hack and won't work for incremental font
955 if (cur.inset().asMathInset()->name() == font)
956 cur.handleFont(font);
958 cur.handleNest(createMathInset(font));
964 void MathHullInset::handleFont2(LCursor & cur, string const & arg)
969 bv_funcs::string2font(arg, font, b);
970 if (font.color() != LColor::inherit) {
971 MathAtom at = createMathInset("color");
972 asArray(lcolor.getGUIName(font.color()), at.nucleus()->cell(0));
973 cur.handleNest(at, 1);
978 void MathHullInset::edit(LCursor & cur, bool left)
980 lyxerr << "MathHullInset: edit left/right" << endl;
985 string const MathHullInset::editMessage() const
987 return _("Math editor mode");
991 void MathHullInset::getCursorDim(int & asc, int & desc) const
995 //math_font_max_dim(font_, asc, des);
999 void MathHullInset::revealCodes(LCursor & cur) const
1001 if (!cur.inMathed())
1005 cur.message(os.str());
1007 // write something to the minibuffer
1008 // translate to latex
1012 string str = os.str();
1014 string::size_type pos = 0;
1016 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1019 else if (*it == '\0') {
1021 pos = it - str.begin();
1027 res = res.substr(pos - 30);
1028 if (res.size() > 60)
1029 res = res.substr(0, 60);
1035 InsetBase::Code MathHullInset::lyxCode() const
1041 /////////////////////////////////////////////////////////////////////
1045 bool MathHullInset::searchForward(BufferView *, string const &, bool, bool)
1051 bool MathHullInset::searchForward(BufferView * bv, string const & str,
1055 #ifdef WITH_WARNINGS
1056 #warning pretty ugly
1058 static MathHullInset * lastformula = 0;
1059 static CursorBase current = DocIterator(ibegin(nucleus()));
1060 static MathArray ar;
1061 static string laststr;
1063 if (lastformula != this || laststr != str) {
1064 //lyxerr << "reset lastformula to " << this << endl;
1067 current = ibegin(nucleus());
1069 mathed_parse_cell(ar, str);
1073 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1075 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1076 CursorSlice & top = it.back();
1077 MathArray const & a = top.asMathInset()->cell(top.idx_);
1078 if (a.matchpart(ar, top.pos_)) {
1079 bv->cursor().setSelection(it, ar.size());
1081 top.pos_ += ar.size();
1087 //lyxerr << "not found!" << endl;
1094 bool MathHullInset::searchBackward(BufferView * bv, string const & what,
1097 lyxerr[Debug::MATHED]
1098 << "searching backward not implemented in mathed" << endl;
1099 return searchForward(bv, what, a, b);
1103 void MathHullInset::write(Buffer const &, std::ostream & os) const
1105 WriteStream wi(os, false, false);
1106 os << fileInsetLabel() << ' ';
1111 void MathHullInset::read(Buffer const &, LyXLex & lex)
1114 mathed_parse_normal(at, lex);
1115 operator=(*at->asHullInset());
1119 int MathHullInset::latex(Buffer const &, ostream & os,
1120 OutputParams const & runparams) const
1122 WriteStream wi(os, runparams.moving_arg, true);
1128 int MathHullInset::plaintext(Buffer const &, ostream & os,
1129 OutputParams const &) const
1131 if (0 && display()) {
1135 TextPainter tpain(dim.width(), dim.height());
1136 drawT(tpain, 0, dim.ascent());
1138 // reset metrics cache to "real" values
1140 return tpain.textheight();
1142 WriteStream wi(os, false, true);
1143 wi << ' ' << cell(0) << ' ';
1149 int MathHullInset::linuxdoc(Buffer const & buf, ostream & os,
1150 OutputParams const & runparams) const
1152 return docbook(buf, os, runparams);
1156 int MathHullInset::docbook(Buffer const & buf, ostream & os,
1157 OutputParams const & runparams) const
1159 MathMLStream ms(os);
1160 ms << MTag("equation");
1163 int res = plaintext(buf, ms.os(), runparams);
1167 MathGridInset::mathmlize(ms);
1169 ms << ETag("equation");
1170 return ms.line() + res;