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