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);
228 metricsMarkers2(dim);
233 void MathHullInset::draw(PainterInfo & pi, int x, int y) const
235 FontSetChanger dummy1(pi.base, standardFont());
236 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
237 MathGridInset::draw(pi, x + 1, y);
239 if (numberedType()) {
240 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
241 for (row_type row = 0; row < nrows(); ++row) {
242 int const yy = y + rowinfo_[row].offset_;
243 FontSetChanger dummy(pi.base, "mathrm");
244 drawStr(pi, pi.base.font, xx, yy, nicelabel(row));
248 drawMarkers2(pi, x, y);
252 void MathHullInset::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
255 MathGridInset::metricsT(mi, dim);
258 WriteStream wi(os, false, true);
260 dim.wid = os.str().size();
267 void MathHullInset::drawT(TextPainter & pain, int x, int y) const
270 MathGridInset::drawT(pain, x, y);
273 WriteStream wi(os, false, true);
275 pain.draw(x, y, os.str().c_str());
280 string MathHullInset::label(row_type row) const
282 row_type n = nrows();
283 BOOST_ASSERT(row < n);
288 void MathHullInset::label(row_type row, string const & label)
290 //lyxerr << "setting label '" << label << "' for row " << row << endl;
295 void MathHullInset::numbered(row_type row, bool num)
301 bool MathHullInset::numbered(row_type row) const
307 bool MathHullInset::ams() const
311 type_ == "flalign" ||
312 type_ == "multline" ||
314 type_ == "alignat" ||
315 type_ == "xalignat" ||
316 type_ == "xxalignat";
320 bool MathHullInset::display() const
322 return type_ != "simple" && type_ != "none";
326 void MathHullInset::getLabelList(Buffer const &, vector<string> & labels) const
328 for (row_type row = 0; row < nrows(); ++row)
329 if (!label_[row].empty() && nonum_[row] != 1)
330 labels.push_back(label_[row]);
334 bool MathHullInset::numberedType() const
338 if (type_ == "simple")
340 if (type_ == "xxalignat")
342 for (row_type row = 0; row < nrows(); ++row)
349 void MathHullInset::validate(LaTeXFeatures & features) const
352 features.require("amsmath");
355 // Validation is necessary only if not using AMS math.
356 // To be safe, we will always run mathedvalidate.
357 //if (features.amsstyle)
360 features.require("boldsymbol");
361 //features.binom = true;
363 MathGridInset::validate(features);
367 void MathHullInset::header_write(WriteStream & os) const
369 bool n = numberedType();
374 else if (type_ == "simple") {
380 else if (type_ == "equation") {
382 os << "\\begin{equation" << star(n) << "}\n";
387 else if (type_ == "eqnarray" || type_ == "align" || type_ == "flalign"
388 || type_ == "gather" || type_ == "multline")
389 os << "\\begin{" << type_ << star(n) << "}\n";
391 else if (type_ == "alignat" || type_ == "xalignat")
392 os << "\\begin{" << type_ << star(n) << '}'
393 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
395 else if (type_ == "xxalignat")
396 os << "\\begin{" << type_ << '}'
397 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
400 os << "\\begin{unknown" << star(n) << '}';
404 void MathHullInset::footer_write(WriteStream & os) const
406 bool n = numberedType();
411 else if (type_ == "simple")
414 else if (type_ == "equation")
416 os << "\\end{equation" << star(n) << "}\n";
420 else if (type_ == "eqnarray" || type_ == "align" || type_ == "flalign"
421 || type_ == "alignat" || type_ == "xalignat"
422 || type_ == "gather" || type_ == "multline")
423 os << "\\end{" << type_ << star(n) << "}\n";
425 else if (type_ == "xxalignat")
426 os << "\\end{" << type_ << "}\n";
429 os << "\\end{unknown" << star(n) << '}';
433 bool MathHullInset::colChangeOK() const
436 type_ == "align" || type_ == "flalign" ||type_ == "alignat" ||
437 type_ == "xalignat" || type_ == "xxalignat";
441 void MathHullInset::addRow(row_type row)
443 nonum_.insert(nonum_.begin() + row + 1, !numberedType());
444 label_.insert(label_.begin() + row + 1, string());
445 MathGridInset::addRow(row);
449 void MathHullInset::swapRow(row_type row)
453 if (row + 1 == nrows())
455 swap(nonum_[row], nonum_[row + 1]);
456 swap(label_[row], label_[row + 1]);
457 MathGridInset::swapRow(row);
461 void MathHullInset::delRow(row_type row)
465 MathGridInset::delRow(row);
466 nonum_.erase(nonum_.begin() + row);
467 label_.erase(label_.begin() + row);
471 void MathHullInset::addCol(col_type col)
474 MathGridInset::addCol(col);
476 lyxerr << "Can't change number of columns in '" << type_ << "'" << endl;
480 void MathHullInset::delCol(col_type col)
483 MathGridInset::delCol(col);
485 lyxerr << "Can't change number of columns in '" << type_ << "'" << endl;
489 string MathHullInset::nicelabel(row_type row) const
493 if (label_[row].empty())
494 return string("(#)");
495 return '(' + label_[row] + ')';
499 void MathHullInset::glueall()
502 for (idx_type i = 0; i < nargs(); ++i)
504 *this = MathHullInset("simple");
510 string const & MathHullInset::getType() const
516 void MathHullInset::setType(string const & type)
524 void MathHullInset::mutate(string const & newtype)
526 lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
528 // we try to move along the chain
529 // none <-> simple <-> equation <-> eqnarray
531 if (newtype == "dump") {
535 else if (newtype == type_) {
539 else if (type_ == "none") {
545 else if (type_ == "simple") {
546 if (newtype == "none") {
555 else if (type_ == "equation") {
556 if (smaller(newtype, type_)) {
559 } else if (newtype == "eqnarray") {
560 MathGridInset::addCol(1);
561 MathGridInset::addCol(1);
563 // split it "nicely" on the firest relop
564 pos_type pos = firstRelOp(cell(0));
565 cell(1) = MathArray(cell(0).begin() + pos, cell(0).end());
566 cell(0).erase(pos, cell(0).size());
568 if (cell(1).size()) {
569 cell(2) = MathArray(cell(1).begin() + 1, cell(1).end());
570 cell(1).erase(1, cell(1).size());
574 } else if (newtype == "multline" || newtype == "gather") {
578 MathGridInset::addCol(1);
580 pos_type pos = firstRelOp(cell(0));
582 cell(0).erase(pos, cell(0).size());
583 cell(1).erase(0, pos);
589 else if (type_ == "eqnarray") {
590 if (smaller(newtype, type_)) {
591 // set correct (no)numbering
592 bool allnonum = true;
593 for (row_type row = 0; row < nrows(); ++row)
597 // set first non-empty label
599 for (row_type row = 0; row < nrows(); ++row) {
600 if (!label_[row].empty()) {
607 nonum_[0] = allnonum;
610 } else { // align & Co.
611 for (row_type row = 0; row < nrows(); ++row) {
612 idx_type c = 3 * row + 1;
613 cell(c).append(cell(c + 1));
615 MathGridInset::delCol(2);
621 else if (type_ == "align") {
622 if (smaller(newtype, type_)) {
623 MathGridInset::addCol(1);
631 else if (type_ == "multline") {
632 if (newtype == "gather" || newtype == "align" ||
633 newtype == "xalignat" || newtype == "xxalignat" || newtype == "flalign")
635 else if (newtype == "eqnarray") {
636 MathGridInset::addCol(1);
637 MathGridInset::addCol(1);
640 lyxerr << "mutation from '" << type_
641 << "' to '" << newtype << "' not implemented" << endl;
645 else if (type_ == "gather") {
646 if (newtype == "multline") {
649 lyxerr << "mutation from '" << type_
650 << "' to '" << newtype << "' not implemented" << endl;
655 lyxerr << "mutation from '" << type_
656 << "' to '" << newtype << "' not implemented" << endl;
661 string MathHullInset::eolString(row_type row, bool fragile) const
664 if (numberedType()) {
665 if (!label_[row].empty() && !nonum_[row])
666 res += "\\label{" + label_[row] + '}';
667 if (nonum_[row] && (type_ != "multline"))
668 res += "\\nonumber ";
670 return res + MathGridInset::eolString(row, fragile);
674 void MathHullInset::write(WriteStream & os) const
677 MathGridInset::write(os);
682 void MathHullInset::normalize(NormalStream & os) const
684 os << "[formula " << type_ << ' ';
685 MathGridInset::normalize(os);
690 void MathHullInset::mathmlize(MathMLStream & os) const
692 MathGridInset::mathmlize(os);
696 void MathHullInset::infoize(ostream & os) const
698 os << "Type: " << type_;
702 void MathHullInset::check() const
704 BOOST_ASSERT(nonum_.size() == nrows());
705 BOOST_ASSERT(label_.size() == nrows());
709 void MathHullInset::doExtern(LCursor & cur, FuncRequest & func)
713 istringstream iss(func.argument.c_str());
714 iss >> lang >> extra;
719 #warning temporarily disabled
720 //if (cur.selection()) {
723 // lyxerr << "use selection: " << ar << endl;
724 // insert(pipeThroughExtern(lang, extra, ar));
730 eq.push_back(MathAtom(new MathCharInset('=')));
732 // go to first item in line
733 cur.idx() -= cur.idx() % ncols();
736 if (getType() == "simple") {
737 size_type pos = cur.cell().find_last(eq);
739 if (cur.inMathed() && cur.selection()) {
740 asArray(cur.grabAndEraseSelection(), ar);
741 } else if (pos == cur.cell().size()) {
743 lyxerr << "use whole cell: " << ar << endl;
745 ar = MathArray(cur.cell().begin() + pos + 1, cur.cell().end());
746 lyxerr << "use partial cell form pos: " << pos << endl;
748 cur.cell().append(eq);
749 cur.cell().append(pipeThroughExtern(lang, extra, ar));
750 cur.pos() = cur.lastpos();
754 if (getType() == "equation") {
755 lyxerr << "use equation inset" << endl;
757 MathArray & ar = cur.cell();
758 lyxerr << "use cell: " << ar << endl;
762 cur.cell() = pipeThroughExtern(lang, extra, ar);
763 // move to end of line
764 cur.pos() = cur.lastpos();
769 lyxerr << "use eqnarray" << endl;
770 cur.idx() += 2 - cur.idx() % ncols();
772 MathArray ar = cur.cell();
773 lyxerr << "use cell: " << ar << endl;
775 #warning temporarily disabled
782 cur.cell() = pipeThroughExtern(lang, extra, ar);
783 cur.pos() = cur.lastpos();
788 void MathHullInset::priv_dispatch(LCursor & cur, FuncRequest & cmd)
790 //lyxerr << "*** MathHullInset: request: " << cmd << endl;
791 switch (cmd.action) {
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 string MathHullInset::fileInsetLabel() const
890 /////////////////////////////////////////////////////////////////////
892 #include "formulamacro.h"
893 #include "math_arrayinset.h"
894 #include "math_deliminset.h"
895 #include "math_factory.h"
896 #include "math_parser.h"
897 #include "math_spaceinset.h"
898 #include "ref_inset.h"
900 #include "bufferview_funcs.h"
904 #include "frontends/LyXView.h"
905 #include "frontends/Dialogs.h"
907 #include "support/std_sstream.h"
908 #include "support/lstrings.h"
909 #include "support/lyxlib.h"
912 // simply scrap this function if you want
913 void MathHullInset::mutateToText()
916 // translate to latex
918 latex(NULL, os, false, false);
919 string str = os.str();
922 LyXText * lt = view_->getLyXText();
923 string::const_iterator cit = str.begin();
924 string::const_iterator end = str.end();
925 for (; cit != end; ++cit)
926 view_->owner()->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
929 //view_->owner()->dispatch(LFUN_ESCAPE);
934 void MathHullInset::handleFont(LCursor & cur, string const & arg,
937 // this whole function is a hack and won't work for incremental font
940 if (cur.inset().asMathInset()->name() == font)
941 cur.handleFont(font);
943 cur.handleNest(createMathInset(font));
949 void MathHullInset::handleFont2(LCursor & cur, string const & arg)
954 bv_funcs::string2font(arg, font, b);
955 if (font.color() != LColor::inherit) {
956 MathAtom at = createMathInset("color");
957 asArray(lcolor.getGUIName(font.color()), at.nucleus()->cell(0));
958 cur.handleNest(at, 1);
963 string const MathHullInset::editMessage() const
965 return _("Math editor mode");
969 void MathHullInset::getCursorDim(int & asc, int & desc) const
973 //math_font_max_dim(font_, asc, des);
977 void MathHullInset::revealCodes(LCursor & cur) const
983 cur.message(os.str());
985 // write something to the minibuffer
986 // translate to latex
990 string str = os.str();
992 string::size_type pos = 0;
994 for (string::iterator it = str.begin(); it != str.end(); ++it) {
997 else if (*it == '\0') {
999 pos = it - str.begin();
1005 res = res.substr(pos - 30);
1006 if (res.size() > 60)
1007 res = res.substr(0, 60);
1013 InsetBase::Code MathHullInset::lyxCode() const
1019 /////////////////////////////////////////////////////////////////////
1023 bool MathHullInset::searchForward(BufferView *, string const &, bool, bool)
1029 bool MathHullInset::searchForward(BufferView * bv, string const & str,
1033 #ifdef WITH_WARNINGS
1034 #warning pretty ugly
1036 static MathHullInset * lastformula = 0;
1037 static CursorBase current = DocumentIterator(ibegin(nucleus()));
1038 static MathArray ar;
1039 static string laststr;
1041 if (lastformula != this || laststr != str) {
1042 //lyxerr << "reset lastformula to " << this << endl;
1045 current = ibegin(nucleus());
1047 mathed_parse_cell(ar, str);
1051 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1053 for (DocumentIterator it = current; it != iend(nucleus()); increment(it)) {
1054 CursorSlice & top = it.back();
1055 MathArray const & a = top.asMathInset()->cell(top.idx_);
1056 if (a.matchpart(ar, top.pos_)) {
1057 bv->cursor().setSelection(it, ar.size());
1059 top.pos_ += ar.size();
1065 //lyxerr << "not found!" << endl;
1072 bool MathHullInset::searchBackward(BufferView * bv, string const & what,
1075 lyxerr[Debug::MATHED]
1076 << "searching backward not implemented in mathed" << endl;
1077 return searchForward(bv, what, a, b);
1081 void MathHullInset::write(Buffer const &, std::ostream & os) const
1083 WriteStream wi(os, false, false);
1084 os << fileInsetLabel() << ' ';
1089 void MathHullInset::read(Buffer const &, LyXLex & lex)
1092 mathed_parse_normal(at, lex);
1093 operator=(*at->asHullInset());
1097 int MathHullInset::latex(Buffer const &, ostream & os,
1098 OutputParams const & runparams) const
1100 WriteStream wi(os, runparams.moving_arg, true);
1106 int MathHullInset::plaintext(Buffer const &, ostream & os,
1107 OutputParams const &) const
1109 if (0 && display()) {
1113 TextPainter tpain(dim.width(), dim.height());
1114 drawT(tpain, 0, dim.ascent());
1116 // reset metrics cache to "real" values
1118 return tpain.textheight();
1120 WriteStream wi(os, false, true);
1121 wi << ' ' << cell(0) << ' ';
1127 int MathHullInset::linuxdoc(Buffer const & buf, ostream & os,
1128 OutputParams const & runparams) const
1130 return docbook(buf, os, runparams);
1134 int MathHullInset::docbook(Buffer const & buf, ostream & os,
1135 OutputParams const & runparams) const
1137 MathMLStream ms(os);
1138 ms << MTag("equation");
1141 int res = plaintext(buf, ms.os(), runparams);
1145 MathGridInset::mathmlize(ms);
1147 ms << ETag("equation");
1148 return ms.line() + res;