]> git.lyx.org Git - lyx.git/blob - src/mathed/math_hullinset.C
the DocIterator 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 void MathHullInset::priv_dispatch(LCursor & cur, FuncRequest const & cmd)
788 {
789         //lyxerr << "*** MathHullInset: request: " << cmd << endl;
790         switch (cmd.action) {
791
792         case LFUN_BREAKLINE:
793                 if (type_ == "simple" || type_ == "equation") {
794                         mutate("eqnarray");
795                         cur.idx() = 1;
796                         cur.pos() = 0;
797                         //cur.dispatched(FINISHED);
798                         return;
799                 }
800                 MathGridInset::priv_dispatch(cur, cmd);
801                 return;
802
803         case LFUN_MATH_NUMBER:
804                 //lyxerr << "toggling all numbers" << endl;
805                 if (display()) {
806                         ////recordUndo(cur, Undo::INSERT);
807                         bool old = numberedType();
808                         if (type_ == "multline")
809                                 numbered(nrows() - 1, !old);
810                         else
811                                 for (row_type row = 0; row < nrows(); ++row)
812                                         numbered(row, !old);
813                         cur.message(old ? _("No number") : _("Number"));
814                 }
815                 return;
816
817         case LFUN_MATH_NONUMBER:
818                 if (display()) {
819                         row_type r = (type_ == "multline") ? nrows() - 1 : cur.row();
820                         ////recordUndo(cur, Undo::INSERT);
821                         bool old = numbered(r);
822                         cur.message(old ? _("No number") : _("Number"));
823                         numbered(r, !old);
824                 }
825                 return;
826
827         case LFUN_INSERT_LABEL: {
828                 row_type r = (type_ == "multline") ? nrows() - 1 : cur.row();
829                 string old_label = label(r);
830                 string new_label = cmd.argument;
831
832                 if (new_label.empty()) {
833                         string const default_label =
834                                 (lyxrc.label_init_length >= 0) ? "eq:" : "";
835                         pair<bool, string> const res = old_label.empty()
836                                 ? Alert::askForText(_("Enter new label to insert:"), default_label)
837                                 : Alert::askForText(_("Enter label:"), old_label);
838                         new_label = lyx::support::trim(res.second);
839                 }
840
841                 if (!new_label.empty())
842                         numbered(r, true);
843                 label(r, new_label);
844                 return;
845         }
846
847         case LFUN_MATH_EXTERN:
848                 doExtern(cur, cmd);
849                 //cur.dispatched(FINISHED);
850                 return;
851
852         case LFUN_MATH_MUTATE: {
853                 lyxerr << "Hull: MUTATE: " << cmd.argument << endl;
854                 row_type row = cur.row();
855                 col_type col = cur.col();
856                 mutate(cmd.argument);
857                 cur.idx() = row * ncols() + col;
858                 if (cur.idx() > cur.lastidx()) {
859                         cur.idx() = cur.lastidx();
860                         cur.pos() = cur.lastpos();
861                 }
862                 if (cur.pos() > cur.lastpos())
863                         cur.pos() = cur.lastpos();
864                 //cur.dispatched(FINISHED);
865                 return;
866         }
867
868         case LFUN_MATH_DISPLAY: {
869                 mutate(type_ == "simple" ? "equation" : "simple");
870                 cur.idx() = 0;
871                 cur.pos() = cur.lastpos();
872                 //cur.dispatched(FINISHED);
873                 return;
874         }
875
876         default:
877                 MathGridInset::priv_dispatch(cur, cmd);
878                 return;
879         }
880 }
881
882
883 string MathHullInset::fileInsetLabel() const
884 {
885         return "Formula";
886 }
887
888
889 /////////////////////////////////////////////////////////////////////
890
891 #include "formulamacro.h"
892 #include "math_arrayinset.h"
893 #include "math_deliminset.h"
894 #include "math_factory.h"
895 #include "math_parser.h"
896 #include "math_spaceinset.h"
897 #include "ref_inset.h"
898
899 #include "bufferview_funcs.h"
900 #include "lyxtext.h"
901 #include "undo.h"
902
903 #include "frontends/LyXView.h"
904 #include "frontends/Dialogs.h"
905
906 #include "support/std_sstream.h"
907 #include "support/lstrings.h"
908 #include "support/lyxlib.h"
909
910
911 int MathHullInset::ylow() const
912 {
913         return yo_ - dim_.asc;
914 }
915
916
917 int MathHullInset::yhigh() const
918 {
919         return yo_ + dim_.des;
920 }
921
922
923 int MathHullInset::xlow() const
924 {
925         return xo_;
926 }
927
928
929 int MathHullInset::xhigh() const
930 {
931         return xo_ + dim_.wid;
932 }
933
934
935 // simply scrap this function if you want
936 void MathHullInset::mutateToText()
937 {
938 #if 0
939         // translate to latex
940         ostringstream os;
941         latex(NULL, os, false, false);
942         string str = os.str();
943
944         // insert this text
945         LyXText * lt = view_->getLyXText();
946         string::const_iterator cit = str.begin();
947         string::const_iterator end = str.end();
948         for (; cit != end; ++cit)
949                 view_->owner()->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
950
951         // remove ourselves
952         //view_->owner()->dispatch(LFUN_ESCAPE);
953 #endif
954 }
955
956
957 void MathHullInset::handleFont
958         (LCursor & cur, string const & arg, string const & font)
959 {
960         // this whole function is a hack and won't work for incremental font
961         // changes...
962         //recordUndo(cur, Undo::ATOMIC);
963
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, Undo::ATOMIC);
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 }