]> git.lyx.org Git - lyx.git/blob - src/mathed/math_hullinset.C
bug + spped fixes + small stuff
[lyx.git] / src / mathed / math_hullinset.C
1 /**
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.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
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"
20
21 #include "BufferView.h"
22 #include "cursor.h"
23 #include "dispatchresult.h"
24 #include "debug.h"
25 #include "funcrequest.h"
26 #include "gettext.h"
27 #include "LaTeXFeatures.h"
28 #include "LColor.h"
29 #include "lyxrc.h"
30 #include "outputparams.h"
31 #include "textpainter.h"
32
33 #include "frontends/Alert.h"
34
35 #include "support/std_sstream.h"
36
37
38 using std::endl;
39 using std::max;
40 using std::string;
41 using std::ostream;
42 using std::auto_ptr;
43 using std::istringstream;
44 using std::ostream;
45 using std::ostringstream;
46 using std::pair;
47 using std::swap;
48 using std::vector;
49
50
51 namespace {
52
53         int getCols(string const & type)
54         {
55                 if (type == "eqnarray")
56                         return 3;
57                 if (type == "align")
58                         return 2;
59                 if (type == "flalign")
60                         return 2;
61                 if (type == "alignat")
62                         return 2;
63                 if (type == "xalignat")
64                         return 2;
65                 if (type == "xxalignat")
66                         return 2;
67                 return 1;
68         }
69
70
71         // returns position of first relation operator in the array
72         // used for "intelligent splitting"
73         size_t firstRelOp(MathArray const & ar)
74         {
75                 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
76                         if ((*it)->isRelOp())
77                                 return it - ar.begin();
78                 return ar.size();
79         }
80
81
82         char const * star(bool numbered)
83         {
84                 return numbered ? "" : "*";
85         }
86
87
88         int typecode(string const & s)
89         {
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;
102                 return 0;
103         }
104
105         bool smaller(string const & s, string const & t)
106         {
107                 return typecode(s) < typecode(t);
108         }
109
110
111 } // end anon namespace
112
113
114
115 MathHullInset::MathHullInset()
116         : MathGridInset(1, 1), type_("none"), nonum_(1), label_(1)
117 {
118         // This is needed as long the math parser is not re-entrant
119         initMath();
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;
124         setDefaults();
125 }
126
127
128 MathHullInset::MathHullInset(string const & type)
129         : MathGridInset(getCols(type), 1), type_(type), nonum_(1), label_(1)
130 {
131         setDefaults();
132 }
133
134
135 auto_ptr<InsetBase> MathHullInset::clone() const
136 {
137         return auto_ptr<InsetBase>(new MathHullInset(*this));
138 }
139
140
141 MathInset::mode_type MathHullInset::currentMode() const
142 {
143         if (type_ == "none")
144                 return UNDECIDED_MODE;
145         // definitely math mode ...
146         return MATH_MODE;
147 }
148
149
150 bool MathHullInset::idxFirst(LCursor & cur) const
151 {
152         cur.idx() = 0;
153         cur.pos() = 0;
154         return true;
155 }
156
157
158 bool MathHullInset::idxLast(LCursor & cur) const
159 {
160         cur.idx() = nargs() - 1;
161         cur.pos() = cur.lastpos();
162         return true;
163 }
164
165
166 char MathHullInset::defaultColAlign(col_type col)
167 {
168         if (type_ == "eqnarray")
169                 return "rcl"[col];
170         if (typecode(type_) >= typecode("align"))
171                 return "rl"[col & 1];
172         return 'c';
173 }
174
175
176 int MathHullInset::defaultColSpace(col_type col)
177 {
178         if (type_ == "align" || type_ == "alignat")
179                 return 0;
180         if (type_ == "xalignat")
181                 return (col & 1) ? 20 : 0;
182         if (type_ == "xxalignat" || type_ == "flalign")
183                 return (col & 1) ? 40 : 0;
184         return 0;
185 }
186
187
188 char const * MathHullInset::standardFont() const
189 {
190         if (type_ == "none")
191                 return "lyxnochange";
192         return "mathnormal";
193 }
194
195
196 void MathHullInset::metrics(MetricsInfo & mi, Dimension & dim) const
197 {
198         FontSetChanger dummy1(mi.base, standardFont());
199         StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
200
201         // let the cells adjust themselves
202         MathGridInset::metrics(mi, dim);
203
204         if (display()) {
205                 dim.asc += 12;
206                 dim.des += 12;
207         }
208
209         if (numberedType()) {
210                 FontSetChanger dummy(mi.base, "mathbf");
211                 int l = 0;
212                 for (row_type row = 0; row < nrows(); ++row)
213                         l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
214
215                 if (l)
216                         dim.wid += 30 + l;
217         }
218
219         // make it at least as high as the current font
220         int asc = 0;
221         int des = 0;
222         math_font_max_dim(mi.base.font, asc, des);
223         dim.asc = max(dim.asc, asc);
224         dim.des = max(dim.des, des);
225
226         // for markers
227         metricsMarkers2(dim);
228         dim_ = dim;
229 }
230
231
232 void MathHullInset::draw(PainterInfo & pi, int x, int y) const
233 {
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);
237
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));
244                 }
245         }
246
247         drawMarkers2(pi, x, y);
248 }
249
250
251 void MathHullInset::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
252 {
253         if (display()) {
254                 MathGridInset::metricsT(mi, dim);
255         } else {
256                 ostringstream os;
257                 WriteStream wi(os, false, true);
258                 write(wi);
259                 dim.wid = os.str().size();
260                 dim.asc = 1;
261                 dim.des = 0;
262         }
263 }
264
265
266 void MathHullInset::drawT(TextPainter & pain, int x, int y) const
267 {
268         if (display()) {
269                 MathGridInset::drawT(pain, x, y);
270         } else {
271                 ostringstream os;
272                 WriteStream wi(os, false, true);
273                 write(wi);
274                 pain.draw(x, y, os.str().c_str());
275         }
276 }
277
278
279 string MathHullInset::label(row_type row) const
280 {
281         row_type n = nrows();
282         BOOST_ASSERT(row < n);
283         return label_[row];
284 }
285
286
287 void MathHullInset::label(row_type row, string const & label)
288 {
289         //lyxerr << "setting label '" << label << "' for row " << row << endl;
290         label_[row] = label;
291 }
292
293
294 void MathHullInset::numbered(row_type row, bool num)
295 {
296         nonum_[row] = !num;
297 }
298
299
300 bool MathHullInset::numbered(row_type row) const
301 {
302         return !nonum_[row];
303 }
304
305
306 bool MathHullInset::ams() const
307 {
308         return
309                 type_ == "align" ||
310                 type_ == "flalign" ||
311                 type_ == "multline" ||
312                 type_ == "gather" ||
313                 type_ == "alignat" ||
314                 type_ == "xalignat" ||
315                 type_ == "xxalignat";
316 }
317
318
319 bool MathHullInset::display() const
320 {
321         return type_ != "simple" && type_ != "none";
322 }
323
324
325 void MathHullInset::getLabelList(Buffer const &, vector<string> & labels) const
326 {
327         for (row_type row = 0; row < nrows(); ++row)
328                 if (!label_[row].empty() && nonum_[row] != 1)
329                         labels.push_back(label_[row]);
330 }
331
332
333 bool MathHullInset::numberedType() const
334 {
335         if (type_ == "none")
336                 return false;
337         if (type_ == "simple")
338                 return false;
339         if (type_ == "xxalignat")
340                 return false;
341         for (row_type row = 0; row < nrows(); ++row)
342                 if (!nonum_[row])
343                         return true;
344         return false;
345 }
346
347
348 void MathHullInset::validate(LaTeXFeatures & features) const
349 {
350         if (ams())
351                 features.require("amsmath");
352
353
354         // Validation is necessary only if not using AMS math.
355         // To be safe, we will always run mathedvalidate.
356         //if (features.amsstyle)
357         //  return;
358
359         features.require("boldsymbol");
360         //features.binom      = true;
361
362         MathGridInset::validate(features);
363 }
364
365
366 void MathHullInset::header_write(WriteStream & os) const
367 {
368         bool n = numberedType();
369
370         if (type_ == "none")
371                 ;
372
373         else if (type_ == "simple") {
374                 os << '$';
375                 if (cell(0).empty())
376                         os << ' ';
377         }
378
379         else if (type_ == "equation") {
380                 if (n)
381                         os << "\\begin{equation" << star(n) << "}\n";
382                 else
383                         os << "\\[\n";
384         }
385
386         else if (type_ == "eqnarray" || type_ == "align" || type_ == "flalign"
387                  || type_ == "gather" || type_ == "multline")
388                         os << "\\begin{" << type_ << star(n) << "}\n";
389
390         else if (type_ == "alignat" || type_ == "xalignat")
391                 os << "\\begin{" << type_ << star(n) << '}'
392                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
393
394         else if (type_ == "xxalignat")
395                 os << "\\begin{" << type_ << '}'
396                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
397
398         else
399                 os << "\\begin{unknown" << star(n) << '}';
400 }
401
402
403 void MathHullInset::footer_write(WriteStream & os) const
404 {
405         bool n = numberedType();
406
407         if (type_ == "none")
408                 os << "\n";
409
410         else if (type_ == "simple")
411                 os << '$';
412
413         else if (type_ == "equation")
414                 if (n)
415                         os << "\\end{equation" << star(n) << "}\n";
416                 else
417                         os << "\\]\n";
418
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";
423
424         else if (type_ == "xxalignat")
425                 os << "\\end{" << type_ << "}\n";
426
427         else
428                 os << "\\end{unknown" << star(n) << '}';
429 }
430
431
432 bool MathHullInset::colChangeOK() const
433 {
434         return
435                 type_ == "align" || type_ == "flalign" ||type_ == "alignat" ||
436                 type_ == "xalignat" || type_ == "xxalignat";
437 }
438
439
440 void MathHullInset::addRow(row_type row)
441 {
442         nonum_.insert(nonum_.begin() + row + 1, !numberedType());
443         label_.insert(label_.begin() + row + 1, string());
444         MathGridInset::addRow(row);
445 }
446
447
448 void MathHullInset::swapRow(row_type row)
449 {
450         if (nrows() == 1)
451                 return;
452         if (row + 1 == nrows())
453                 --row;
454         swap(nonum_[row], nonum_[row + 1]);
455         swap(label_[row], label_[row + 1]);
456         MathGridInset::swapRow(row);
457 }
458
459
460 void MathHullInset::delRow(row_type row)
461 {
462         if (nrows() <= 1)
463                 return;
464         MathGridInset::delRow(row);
465         nonum_.erase(nonum_.begin() + row);
466         label_.erase(label_.begin() + row);
467 }
468
469
470 void MathHullInset::addCol(col_type col)
471 {
472         if (colChangeOK())
473                 MathGridInset::addCol(col);
474         else
475                 lyxerr << "Can't change number of columns in '" << type_ << "'" << endl;
476 }
477
478
479 void MathHullInset::delCol(col_type col)
480 {
481         if (colChangeOK())
482                 MathGridInset::delCol(col);
483         else
484                 lyxerr << "Can't change number of columns in '" << type_ << "'" << endl;
485 }
486
487
488 string MathHullInset::nicelabel(row_type row) const
489 {
490         if (nonum_[row])
491                 return string();
492         if (label_[row].empty())
493                 return string("(#)");
494         return '(' + label_[row] + ')';
495 }
496
497
498 void MathHullInset::glueall()
499 {
500         MathArray ar;
501         for (idx_type i = 0; i < nargs(); ++i)
502                 ar.append(cell(i));
503         *this = MathHullInset("simple");
504         cell(0) = ar;
505         setDefaults();
506 }
507
508
509 string const & MathHullInset::getType() const
510 {
511         return type_;
512 }
513
514
515 void MathHullInset::setType(string const & type)
516 {
517         type_ = type;
518         setDefaults();
519 }
520
521
522
523 void MathHullInset::mutate(string const & newtype)
524 {
525         lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
526
527         // we try to move along the chain
528         // none <-> simple <-> equation <-> eqnarray
529
530         if (newtype == "dump") {
531                 dump();
532         }
533
534         else if (newtype == type_) {
535                 // done
536         }
537
538         else if (type_ == "none") {
539                 setType("simple");
540                 numbered(0, false);
541                 mutate(newtype);
542         }
543
544         else if (type_ == "simple") {
545                 if (newtype == "none") {
546                         setType("none");
547                 } else {
548                         setType("equation");
549                         numbered(0, false);
550                         mutate(newtype);
551                 }
552         }
553
554         else if (type_ == "equation") {
555                 if (smaller(newtype, type_)) {
556                         setType("simple");
557                         mutate(newtype);
558                 } else if (newtype == "eqnarray") {
559                         MathGridInset::addCol(1);
560                         MathGridInset::addCol(1);
561
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());
566
567                         if (cell(1).size()) {
568                                 cell(2) = MathArray(cell(1).begin() + 1, cell(1).end());
569                                 cell(1).erase(1, cell(1).size());
570                         }
571                         setType("eqnarray");
572                         mutate(newtype);
573                 } else if (newtype == "multline" || newtype == "gather") {
574                         setType(newtype);
575                         numbered(0, false);
576                 } else {
577                         MathGridInset::addCol(1);
578                         // split it "nicely"
579                         pos_type pos = firstRelOp(cell(0));
580                         cell(1) = cell(0);
581                         cell(0).erase(pos, cell(0).size());
582                         cell(1).erase(0, pos);
583                         setType("align");
584                         mutate(newtype);
585                 }
586         }
587
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)
593                                 if (!nonum_[row])
594                                         allnonum = false;
595
596                         // set first non-empty label
597                         string label;
598                         for (row_type row = 0; row < nrows(); ++row) {
599                                 if (!label_[row].empty()) {
600                                         label = label_[row];
601                                         break;
602                                 }
603                         }
604
605                         glueall();
606                         nonum_[0] = allnonum;
607                         label_[0] = label;
608                         mutate(newtype);
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));
613                         }
614                         MathGridInset::delCol(2);
615                         setType("align");
616                         mutate(newtype);
617                 }
618         }
619
620         else if (type_ == "align") {
621                 if (smaller(newtype, type_)) {
622                         MathGridInset::addCol(1);
623                         setType("eqnarray");
624                         mutate(newtype);
625                 } else {
626                         setType(newtype);
627                 }
628         }
629
630         else if (type_ == "multline") {
631                 if (newtype == "gather" || newtype == "align" ||
632                     newtype == "xalignat" || newtype == "xxalignat" || newtype == "flalign")
633                         setType(newtype);
634                 else if (newtype == "eqnarray") {
635                         MathGridInset::addCol(1);
636                         MathGridInset::addCol(1);
637                         setType("eqnarray");
638                 } else {
639                         lyxerr << "mutation from '" << type_
640                                 << "' to '" << newtype << "' not implemented" << endl;
641                 }
642         }
643
644         else if (type_ == "gather") {
645                 if (newtype == "multline") {
646                         setType("multline");
647                 } else {
648                         lyxerr << "mutation from '" << type_
649                                 << "' to '" << newtype << "' not implemented" << endl;
650                 }
651         }
652
653         else {
654                 lyxerr << "mutation from '" << type_
655                                          << "' to '" << newtype << "' not implemented" << endl;
656         }
657 }
658
659
660 string MathHullInset::eolString(row_type row, bool fragile) const
661 {
662         string res;
663         if (numberedType()) {
664                 if (!label_[row].empty() && !nonum_[row])
665                         res += "\\label{" + label_[row] + '}';
666                 if (nonum_[row] && (type_ != "multline"))
667                         res += "\\nonumber ";
668         }
669         return res + MathGridInset::eolString(row, fragile);
670 }
671
672
673 void MathHullInset::write(WriteStream & os) const
674 {
675         header_write(os);
676         MathGridInset::write(os);
677         footer_write(os);
678 }
679
680
681 void MathHullInset::normalize(NormalStream & os) const
682 {
683         os << "[formula " << type_ << ' ';
684         MathGridInset::normalize(os);
685         os << "] ";
686 }
687
688
689 void MathHullInset::mathmlize(MathMLStream & os) const
690 {
691         MathGridInset::mathmlize(os);
692 }
693
694
695 void MathHullInset::infoize(ostream & os) const
696 {
697         os << "Type: " << type_;
698 }
699
700
701 void MathHullInset::check() const
702 {
703         BOOST_ASSERT(nonum_.size() == nrows());
704         BOOST_ASSERT(label_.size() == nrows());
705 }
706
707
708 void MathHullInset::doExtern(LCursor & cur, FuncRequest const & func)
709 {
710         string lang;
711         string extra;
712         istringstream iss(func.argument.c_str());
713         iss >> lang >> extra;
714         if (extra.empty())
715                 extra = "noextra";
716
717 #ifdef WITH_WARNINGS
718 #warning temporarily disabled
719         //if (cur.selection()) {
720         //      MathArray ar;
721         //      selGet(cur.ar);
722         //      lyxerr << "use selection: " << ar << endl;
723         //      insert(pipeThroughExtern(lang, extra, ar));
724         //      return;
725         //}
726 #endif
727
728         MathArray eq;
729         eq.push_back(MathAtom(new MathCharInset('=')));
730
731         // go to first item in line
732         cur.idx() -= cur.idx() % ncols();
733         cur.pos() = 0;
734
735         if (getType() == "simple") {
736                 size_type pos = cur.cell().find_last(eq);
737                 MathArray ar;
738                 if (cur.inMathed() && cur.selection()) {
739                         asArray(cur.grabAndEraseSelection(), ar);
740                 } else if (pos == cur.cell().size()) {
741                         ar = cur.cell();
742                         lyxerr << "use whole cell: " << ar << endl;
743                 } else {
744                         ar = MathArray(cur.cell().begin() + pos + 1, cur.cell().end());
745                         lyxerr << "use partial cell form pos: " << pos << endl;
746                 }
747                 cur.cell().append(eq);
748                 cur.cell().append(pipeThroughExtern(lang, extra, ar));
749                 cur.pos() = cur.lastpos();
750                 return;
751         }
752
753         if (getType() == "equation") {
754                 lyxerr << "use equation inset" << endl;
755                 mutate("eqnarray");
756                 MathArray & ar = cur.cell();
757                 lyxerr << "use cell: " << ar << endl;
758                 ++cur.idx();
759                 cur.cell() = eq;
760                 ++cur.idx();
761                 cur.cell() = pipeThroughExtern(lang, extra, ar);
762                 // move to end of line
763                 cur.pos() = cur.lastpos();
764                 return;
765         }
766
767         {
768                 lyxerr << "use eqnarray" << endl;
769                 cur.idx() += 2 - cur.idx() % ncols();
770                 cur.pos() = 0;
771                 MathArray ar = cur.cell();
772                 lyxerr << "use cell: " << ar << endl;
773 #ifdef WITH_WARNINGS
774 #warning temporarily disabled
775 #endif
776                 addRow(cur.row());
777                 ++cur.idx();
778                 ++cur.idx();
779                 cur.cell() = eq;
780                 ++cur.idx();
781                 cur.cell() = pipeThroughExtern(lang, extra, ar);
782                 cur.pos() = cur.lastpos();
783         }
784 }
785
786
787 DispatchResult
788 MathHullInset::priv_dispatch(LCursor & cur, FuncRequest const & cmd)
789 {
790         //lyxerr << "*** MathHullInset: request: " << cmd << endl;
791         switch (cmd.action) {
792
793                 case LFUN_BREAKLINE:
794                         if (type_ == "simple" || type_ == "equation") {
795                                 mutate("eqnarray");
796                                 cur.idx() = 1;
797                                 cur.pos() = 0;
798                                 return DispatchResult(true, FINISHED);
799                         }
800                         return MathGridInset::priv_dispatch(cur, cmd);
801
802                 case LFUN_MATH_NUMBER:
803                         //lyxerr << "toggling all numbers" << endl;
804                         if (display()) {
805                                 ////recordUndo(cur, Undo::INSERT);
806                                 bool old = numberedType();
807                                 if (type_ == "multline")
808                                         numbered(nrows() - 1, !old);
809                                 else
810                                         for (row_type row = 0; row < nrows(); ++row)
811                                                 numbered(row, !old);
812                                 cur.message(old ? _("No number") : _("Number"));
813                         }
814                         return DispatchResult(true, true);
815
816                 case LFUN_MATH_NONUMBER:
817                         if (display()) {
818                                 row_type r = (type_ == "multline") ? nrows() - 1 : cur.row();
819                                 ////recordUndo(cur, Undo::INSERT);
820                                 bool old = numbered(r);
821                                 cur.message(old ? _("No number") : _("Number"));
822                                 numbered(r, !old);
823                         }
824                         return DispatchResult(true, true);
825
826                 case LFUN_INSERT_LABEL: {
827                         row_type r = (type_ == "multline") ? nrows() - 1 : cur.row();
828                         string old_label = label(r);
829                         string new_label = cmd.argument;
830
831                         if (new_label.empty()) {
832                                 string const default_label =
833                                         (lyxrc.label_init_length >= 0) ? "eq:" : "";
834                                 pair<bool, string> const res = old_label.empty()
835                                         ? Alert::askForText(_("Enter new label to insert:"), default_label)
836                                         : Alert::askForText(_("Enter label:"), old_label);
837                                 if (!res.first)
838                                         return DispatchResult(false);
839                                 new_label = lyx::support::trim(res.second);
840                         }
841
842                         //if (new_label == old_label)
843                         //      break;  // Nothing to do
844
845                         if (!new_label.empty())
846                                 numbered(r, true);
847                         label(r, new_label);
848                         return DispatchResult(true, true);
849                 }
850
851                 case LFUN_MATH_EXTERN:
852                         doExtern(cur, cmd);
853                         return DispatchResult(true, FINISHED);
854
855                 case LFUN_MATH_MUTATE: {
856                         lyxerr << "Hull: MUTATE: " << cmd.argument << endl;
857                         row_type r = cur.row();
858                         col_type c = cur.col();
859                         mutate(cmd.argument);
860                         cur.idx() = r * ncols() + c;
861                         if (cur.idx() >= nargs())
862                                 cur.idx() = nargs() - 1;
863                         if (cur.pos() > cur.lastpos())
864                                 cur.pos() = cur.lastpos();
865                         return DispatchResult(true, FINISHED);
866                 }
867
868                 case LFUN_MATH_DISPLAY: {
869                         mutate(type_ == "simple" ? "equation" : "simple");
870                         cur.idx() = 0;
871                         cur.pos() = cur.lastpos();
872                         return DispatchResult(true, FINISHED);
873                 }
874
875                 default:
876                         return MathGridInset::priv_dispatch(cur, cmd);
877         }
878 }
879
880
881 string MathHullInset::fileInsetLabel() const
882 {
883         return "Formula";
884 }
885
886
887 /////////////////////////////////////////////////////////////////////
888
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"
896
897 #include "bufferview_funcs.h"
898 #include "lyxtext.h"
899 #include "undo.h"
900
901 #include "frontends/LyXView.h"
902 #include "frontends/Dialogs.h"
903
904 #include "support/std_sstream.h"
905 #include "support/lstrings.h"
906 #include "support/lyxlib.h"
907
908
909 int MathHullInset::ylow() const
910 {
911         return yo_ - dim_.asc;
912 }
913
914
915 int MathHullInset::yhigh() const
916 {
917         return yo_ + dim_.des;
918 }
919
920
921 int MathHullInset::xlow() const
922 {
923         return xo_;
924 }
925
926
927 int MathHullInset::xhigh() const
928 {
929         return xo_ + dim_.wid;
930 }
931
932
933 // simply scrap this function if you want
934 void MathHullInset::mutateToText()
935 {
936 #if 0
937         // translate to latex
938         ostringstream os;
939         latex(NULL, os, false, false);
940         string str = os.str();
941
942         // insert this text
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);
948
949         // remove ourselves
950         //view_->owner()->dispatch(LFUN_ESCAPE);
951 #endif
952 }
953
954
955 void MathHullInset::handleFont
956         (LCursor & cur, string const & arg, string const & font)
957 {
958         // this whole function is a hack and won't work for incremental font
959         // changes...
960         //recordUndo(cur, Undo::ATOMIC);
961
962         if (cur.inset()->asMathInset()->name() == font)
963                 cur.handleFont(font);
964         else {
965                 cur.handleNest(createMathInset(font));
966                 cur.insert(arg);
967         }
968 }
969
970
971 void MathHullInset::handleFont2(LCursor & cur, string const & arg)
972 {
973         //recordUndo(cur, Undo::ATOMIC);
974         LyXFont font;
975         bool b;
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);
981         }
982 }
983
984
985 string const MathHullInset::editMessage() const
986 {
987         return _("Math editor mode");
988 }
989
990
991 void MathHullInset::insetUnlock(BufferView & bv)
992 {
993         if (bv.cursor().inMathed()) {
994                 if (bv.cursor().inMacroMode())
995                         bv.cursor().macroModeClose();
996                 bv.cursor().releaseMathCursor();
997         }
998         if (bv.buffer())
999                 generatePreview(*bv.buffer());
1000         bv.update();
1001 }
1002
1003
1004 void MathHullInset::getCursorDim(int & asc, int & desc) const
1005 {
1006         asc = 10;
1007         desc = 2;
1008         //math_font_max_dim(font_, asc, des);
1009 }
1010
1011
1012 void MathHullInset::revealCodes(LCursor & cur) const
1013 {
1014         if (!cur.inMathed())
1015                 return;
1016         ostringstream os;
1017         cur.info(os);
1018         cur.message(os.str());
1019 /*
1020         // write something to the minibuffer
1021         // translate to latex
1022         cur.markInsert(bv);
1023         ostringstream os;
1024         write(NULL, os);
1025         string str = os.str();
1026         cur.markErase(bv);
1027         string::size_type pos = 0;
1028         string res;
1029         for (string::iterator it = str.begin(); it != str.end(); ++it) {
1030                 if (*it == '\n')
1031                         res += ' ';
1032                 else if (*it == '\0') {
1033                         res += "  -X-  ";
1034                         pos = it - str.begin();
1035                 }
1036                 else
1037                         res += *it;
1038         }
1039         if (pos > 30)
1040                 res = res.substr(pos - 30);
1041         if (res.size() > 60)
1042                 res = res.substr(0, 60);
1043         cur.message(res);
1044 */
1045 }
1046
1047
1048 InsetBase::Code MathHullInset::lyxCode() const
1049 {
1050         return MATH_CODE;
1051 }
1052
1053
1054 /////////////////////////////////////////////////////////////////////
1055
1056
1057 #if 1
1058 bool MathHullInset::searchForward(BufferView *, string const &, bool, bool)
1059 {
1060         return false;
1061 }
1062
1063 #else
1064 bool MathHullInset::searchForward(BufferView * bv, string const & str,
1065                                      bool, bool)
1066 {
1067         return false;
1068 #ifdef WITH_WARNINGS
1069 #warning pretty ugly
1070 #endif
1071         static MathHullInset * lastformula = 0;
1072         static CursorBase current = CursorBase(ibegin(nucleus()));
1073         static MathArray ar;
1074         static string laststr;
1075
1076         if (lastformula != this || laststr != str) {
1077                 //lyxerr << "reset lastformula to " << this << endl;
1078                 lastformula = this;
1079                 laststr = str;
1080                 current = ibegin(nucleus());
1081                 ar.clear();
1082                 mathed_parse_cell(ar, str);
1083         } else {
1084                 increment(current);
1085         }
1086         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1087
1088         for (CursorBase it = current; it != iend(nucleus()); increment(it)) {
1089                 CursorSlice & top = it.back();
1090                 MathArray const & a = top.asMathInset()->cell(top.idx_);
1091                 if (a.matchpart(ar, top.pos_)) {
1092                         bv->cursor().setSelection(it, ar.size());
1093                         current = it;
1094                         top.pos_ += ar.size();
1095                         bv->update();
1096                         return true;
1097                 }
1098         }
1099
1100         //lyxerr << "not found!" << endl;
1101         lastformula = 0;
1102         return false;
1103 }
1104 #endif
1105
1106
1107 bool MathHullInset::searchBackward(BufferView * bv, string const & what,
1108                                       bool a, bool b)
1109 {
1110         lyxerr[Debug::MATHED]
1111                 << "searching backward not implemented in mathed" << endl;
1112         return searchForward(bv, what, a, b);
1113 }
1114
1115
1116 void MathHullInset::write(Buffer const &, std::ostream & os) const
1117 {
1118         WriteStream wi(os, false, false);
1119         os << fileInsetLabel() << ' ';
1120         write(wi);
1121 }
1122
1123
1124 void MathHullInset::read(Buffer const &, LyXLex & lex)
1125 {
1126         MathAtom at;
1127         mathed_parse_normal(at, lex);
1128         operator=(*at->asHullInset());
1129 }
1130
1131
1132 int MathHullInset::latex(Buffer const &, ostream & os,
1133                         OutputParams const & runparams) const
1134 {
1135         WriteStream wi(os, runparams.moving_arg, true);
1136         write(wi);
1137         return wi.line();
1138 }
1139
1140
1141 int MathHullInset::plaintext(Buffer const &, ostream & os,
1142                         OutputParams const &) const
1143 {
1144         if (0 && display()) {
1145                 Dimension dim;
1146                 TextMetricsInfo mi;
1147                 metricsT(mi, dim);
1148                 TextPainter tpain(dim.width(), dim.height());
1149                 drawT(tpain, 0, dim.ascent());
1150                 tpain.show(os, 3);
1151                 // reset metrics cache to "real" values
1152                 //metrics();
1153                 return tpain.textheight();
1154         } else {
1155                 WriteStream wi(os, false, true);
1156                 wi << ' ' << cell(0) << ' ';
1157                 return wi.line();
1158         }
1159 }
1160
1161
1162 int MathHullInset::linuxdoc(Buffer const & buf, ostream & os,
1163                            OutputParams const & runparams) const
1164 {
1165         return docbook(buf, os, runparams);
1166 }
1167
1168
1169 int MathHullInset::docbook(Buffer const & buf, ostream & os,
1170                           OutputParams const & runparams) const
1171 {
1172         MathMLStream ms(os);
1173         ms << MTag("equation");
1174         ms <<   MTag("alt");
1175         ms <<    "<[CDATA[";
1176         int res = plaintext(buf, ms.os(), runparams);
1177         ms <<    "]]>";
1178         ms <<   ETag("alt");
1179         ms <<   MTag("math");
1180         MathGridInset::mathmlize(ms);
1181         ms <<   ETag("math");
1182         ms << ETag("equation");
1183         return ms.line() + res;
1184 }