]> git.lyx.org Git - lyx.git/blob - src/mathed/math_hullinset.C
fix table crash;
[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         dim_ = dim;
228 }
229
230
231 void MathHullInset::draw(PainterInfo & pi, int x, int y) const
232 {
233         FontSetChanger dummy1(pi.base, standardFont());
234         StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
235         MathGridInset::draw(pi, x + 1, y);
236
237         if (numberedType()) {
238                 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
239                 for (row_type row = 0; row < nrows(); ++row) {
240                         int const yy = y + rowinfo_[row].offset_;
241                         FontSetChanger dummy(pi.base, "mathrm");
242                         drawStr(pi, pi.base.font, xx, yy, nicelabel(row));
243                 }
244         }
245 }
246
247
248 void MathHullInset::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
249 {
250         if (display()) {
251                 MathGridInset::metricsT(mi, dim);
252         } else {
253                 ostringstream os;
254                 WriteStream wi(os, false, true);
255                 write(wi);
256                 dim.wid = os.str().size();
257                 dim.asc = 1;
258                 dim.des = 0;
259         }
260 }
261
262
263 void MathHullInset::drawT(TextPainter & pain, int x, int y) const
264 {
265         if (display()) {
266                 MathGridInset::drawT(pain, x, y);
267         } else {
268                 ostringstream os;
269                 WriteStream wi(os, false, true);
270                 write(wi);
271                 pain.draw(x, y, os.str().c_str());
272         }
273 }
274
275
276 string MathHullInset::label(row_type row) const
277 {
278         row_type n = nrows();
279         BOOST_ASSERT(row < n);
280         return label_[row];
281 }
282
283
284 void MathHullInset::label(row_type row, string const & label)
285 {
286         //lyxerr << "setting label '" << label << "' for row " << row << endl;
287         label_[row] = label;
288 }
289
290
291 void MathHullInset::numbered(row_type row, bool num)
292 {
293         nonum_[row] = !num;
294 }
295
296
297 bool MathHullInset::numbered(row_type row) const
298 {
299         return !nonum_[row];
300 }
301
302
303 bool MathHullInset::ams() const
304 {
305         return
306                 type_ == "align" ||
307                 type_ == "flalign" ||
308                 type_ == "multline" ||
309                 type_ == "gather" ||
310                 type_ == "alignat" ||
311                 type_ == "xalignat" ||
312                 type_ == "xxalignat";
313 }
314
315
316 bool MathHullInset::display() const
317 {
318         return type_ != "simple" && type_ != "none";
319 }
320
321
322 void MathHullInset::getLabelList(Buffer const &, vector<string> & labels) const
323 {
324         for (row_type row = 0; row < nrows(); ++row)
325                 if (!label_[row].empty() && nonum_[row] != 1)
326                         labels.push_back(label_[row]);
327 }
328
329
330 bool MathHullInset::numberedType() const
331 {
332         if (type_ == "none")
333                 return false;
334         if (type_ == "simple")
335                 return false;
336         if (type_ == "xxalignat")
337                 return false;
338         for (row_type row = 0; row < nrows(); ++row)
339                 if (!nonum_[row])
340                         return true;
341         return false;
342 }
343
344
345 void MathHullInset::validate(LaTeXFeatures & features) const
346 {
347         if (ams())
348                 features.require("amsmath");
349
350
351         // Validation is necessary only if not using AMS math.
352         // To be safe, we will always run mathedvalidate.
353         //if (features.amsstyle)
354         //  return;
355
356         features.require("boldsymbol");
357         //features.binom      = true;
358
359         MathGridInset::validate(features);
360 }
361
362
363 void MathHullInset::header_write(WriteStream & os) const
364 {
365         bool n = numberedType();
366
367         if (type_ == "none")
368                 ;
369
370         else if (type_ == "simple") {
371                 os << '$';
372                 if (cell(0).empty())
373                         os << ' ';
374         }
375
376         else if (type_ == "equation") {
377                 if (n)
378                         os << "\\begin{equation" << star(n) << "}\n";
379                 else
380                         os << "\\[\n";
381         }
382
383         else if (type_ == "eqnarray" || type_ == "align" || type_ == "flalign"
384                  || type_ == "gather" || type_ == "multline")
385                         os << "\\begin{" << type_ << star(n) << "}\n";
386
387         else if (type_ == "alignat" || type_ == "xalignat")
388                 os << "\\begin{" << type_ << star(n) << '}'
389                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
390
391         else if (type_ == "xxalignat")
392                 os << "\\begin{" << type_ << '}'
393                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
394
395         else
396                 os << "\\begin{unknown" << star(n) << '}';
397 }
398
399
400 void MathHullInset::footer_write(WriteStream & os) const
401 {
402         bool n = numberedType();
403
404         if (type_ == "none")
405                 os << "\n";
406
407         else if (type_ == "simple")
408                 os << '$';
409
410         else if (type_ == "equation")
411                 if (n)
412                         os << "\\end{equation" << star(n) << "}\n";
413                 else
414                         os << "\\]\n";
415
416         else if (type_ == "eqnarray" || type_ == "align" || type_ == "flalign"
417                  || type_ == "alignat" || type_ == "xalignat"
418                  || type_ == "gather" || type_ == "multline")
419                 os << "\\end{" << type_ << star(n) << "}\n";
420
421         else if (type_ == "xxalignat")
422                 os << "\\end{" << type_ << "}\n";
423
424         else
425                 os << "\\end{unknown" << star(n) << '}';
426 }
427
428
429 bool MathHullInset::colChangeOK() const
430 {
431         return
432                 type_ == "align" || type_ == "flalign" ||type_ == "alignat" ||
433                 type_ == "xalignat" || type_ == "xxalignat";
434 }
435
436
437 void MathHullInset::addRow(row_type row)
438 {
439         nonum_.insert(nonum_.begin() + row + 1, !numberedType());
440         label_.insert(label_.begin() + row + 1, string());
441         MathGridInset::addRow(row);
442 }
443
444
445 void MathHullInset::swapRow(row_type row)
446 {
447         if (nrows() == 1)
448                 return;
449         if (row + 1 == nrows())
450                 --row;
451         swap(nonum_[row], nonum_[row + 1]);
452         swap(label_[row], label_[row + 1]);
453         MathGridInset::swapRow(row);
454 }
455
456
457 void MathHullInset::delRow(row_type row)
458 {
459         if (nrows() <= 1)
460                 return;
461         MathGridInset::delRow(row);
462         nonum_.erase(nonum_.begin() + row);
463         label_.erase(label_.begin() + row);
464 }
465
466
467 void MathHullInset::addCol(col_type col)
468 {
469         if (colChangeOK())
470                 MathGridInset::addCol(col);
471         else
472                 lyxerr << "Can't change number of columns in '" << type_ << "'" << endl;
473 }
474
475
476 void MathHullInset::delCol(col_type col)
477 {
478         if (colChangeOK())
479                 MathGridInset::delCol(col);
480         else
481                 lyxerr << "Can't change number of columns in '" << type_ << "'" << endl;
482 }
483
484
485 string MathHullInset::nicelabel(row_type row) const
486 {
487         if (nonum_[row])
488                 return string();
489         if (label_[row].empty())
490                 return string("(#)");
491         return '(' + label_[row] + ')';
492 }
493
494
495 void MathHullInset::glueall()
496 {
497         MathArray ar;
498         for (idx_type i = 0; i < nargs(); ++i)
499                 ar.append(cell(i));
500         *this = MathHullInset("simple");
501         cell(0) = ar;
502         setDefaults();
503 }
504
505
506 string const & MathHullInset::getType() const
507 {
508         return type_;
509 }
510
511
512 void MathHullInset::setType(string const & type)
513 {
514         type_ = type;
515         setDefaults();
516 }
517
518
519
520 void MathHullInset::mutate(string const & newtype)
521 {
522         lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
523
524         // we try to move along the chain
525         // none <-> simple <-> equation <-> eqnarray
526
527         if (newtype == "dump") {
528                 dump();
529         }
530
531         else if (newtype == type_) {
532                 // done
533         }
534
535         else if (type_ == "none") {
536                 setType("simple");
537                 numbered(0, false);
538                 mutate(newtype);
539         }
540
541         else if (type_ == "simple") {
542                 if (newtype == "none") {
543                         setType("none");
544                 } else {
545                         setType("equation");
546                         numbered(0, false);
547                         mutate(newtype);
548                 }
549         }
550
551         else if (type_ == "equation") {
552                 if (smaller(newtype, type_)) {
553                         setType("simple");
554                         mutate(newtype);
555                 } else if (newtype == "eqnarray") {
556                         MathGridInset::addCol(1);
557                         MathGridInset::addCol(1);
558
559                         // split it "nicely" on the firest relop
560                         pos_type pos = firstRelOp(cell(0));
561                         cell(1) = MathArray(cell(0).begin() + pos, cell(0).end());
562                         cell(0).erase(pos, cell(0).size());
563
564                         if (cell(1).size()) {
565                                 cell(2) = MathArray(cell(1).begin() + 1, cell(1).end());
566                                 cell(1).erase(1, cell(1).size());
567                         }
568                         setType("eqnarray");
569                         mutate(newtype);
570                 } else if (newtype == "multline" || newtype == "gather") {
571                         setType(newtype);
572                         numbered(0, false);
573                 } else {
574                         MathGridInset::addCol(1);
575                         // split it "nicely"
576                         pos_type pos = firstRelOp(cell(0));
577                         cell(1) = cell(0);
578                         cell(0).erase(pos, cell(0).size());
579                         cell(1).erase(0, pos);
580                         setType("align");
581                         mutate(newtype);
582                 }
583         }
584
585         else if (type_ == "eqnarray") {
586                 if (smaller(newtype, type_)) {
587                         // set correct (no)numbering
588                         bool allnonum = true;
589                         for (row_type row = 0; row < nrows(); ++row)
590                                 if (!nonum_[row])
591                                         allnonum = false;
592
593                         // set first non-empty label
594                         string label;
595                         for (row_type row = 0; row < nrows(); ++row) {
596                                 if (!label_[row].empty()) {
597                                         label = label_[row];
598                                         break;
599                                 }
600                         }
601
602                         glueall();
603                         nonum_[0] = allnonum;
604                         label_[0] = label;
605                         mutate(newtype);
606                 } else { // align & Co.
607                         for (row_type row = 0; row < nrows(); ++row) {
608                                 idx_type c = 3 * row + 1;
609                                 cell(c).append(cell(c + 1));
610                         }
611                         MathGridInset::delCol(2);
612                         setType("align");
613                         mutate(newtype);
614                 }
615         }
616
617         else if (type_ == "align") {
618                 if (smaller(newtype, type_)) {
619                         MathGridInset::addCol(1);
620                         setType("eqnarray");
621                         mutate(newtype);
622                 } else {
623                         setType(newtype);
624                 }
625         }
626
627         else if (type_ == "multline") {
628                 if (newtype == "gather" || newtype == "align" ||
629                     newtype == "xalignat" || newtype == "xxalignat" || newtype == "flalign")
630                         setType(newtype);
631                 else if (newtype == "eqnarray") {
632                         MathGridInset::addCol(1);
633                         MathGridInset::addCol(1);
634                         setType("eqnarray");
635                 } else {
636                         lyxerr << "mutation from '" << type_
637                                 << "' to '" << newtype << "' not implemented" << endl;
638                 }
639         }
640
641         else if (type_ == "gather") {
642                 if (newtype == "multline") {
643                         setType("multline");
644                 } else {
645                         lyxerr << "mutation from '" << type_
646                                 << "' to '" << newtype << "' not implemented" << endl;
647                 }
648         }
649
650         else {
651                 lyxerr << "mutation from '" << type_
652                                          << "' to '" << newtype << "' not implemented" << endl;
653         }
654 }
655
656
657 string MathHullInset::eolString(row_type row, bool fragile) const
658 {
659         string res;
660         if (numberedType()) {
661                 if (!label_[row].empty() && !nonum_[row])
662                         res += "\\label{" + label_[row] + '}';
663                 if (nonum_[row] && (type_ != "multline"))
664                         res += "\\nonumber ";
665         }
666         return res + MathGridInset::eolString(row, fragile);
667 }
668
669
670 void MathHullInset::write(WriteStream & os) const
671 {
672         header_write(os);
673         MathGridInset::write(os);
674         footer_write(os);
675 }
676
677
678 void MathHullInset::normalize(NormalStream & os) const
679 {
680         os << "[formula " << type_ << ' ';
681         MathGridInset::normalize(os);
682         os << "] ";
683 }
684
685
686 void MathHullInset::mathmlize(MathMLStream & os) const
687 {
688         MathGridInset::mathmlize(os);
689 }
690
691
692 void MathHullInset::infoize(ostream & os) const
693 {
694         os << "Type: " << type_;
695 }
696
697
698 void MathHullInset::check() const
699 {
700         BOOST_ASSERT(nonum_.size() == nrows());
701         BOOST_ASSERT(label_.size() == nrows());
702 }
703
704
705 void MathHullInset::doExtern(LCursor & cur, FuncRequest & func)
706 {
707         string lang;
708         string extra;
709         istringstream iss(func.argument.c_str());
710         iss >> lang >> extra;
711         if (extra.empty())
712                 extra = "noextra";
713
714 #ifdef WITH_WARNINGS
715 #warning temporarily disabled
716         //if (cur.selection()) {
717         //      MathArray ar;
718         //      selGet(cur.ar);
719         //      lyxerr << "use selection: " << ar << endl;
720         //      insert(pipeThroughExtern(lang, extra, ar));
721         //      return;
722         //}
723 #endif
724
725         MathArray eq;
726         eq.push_back(MathAtom(new MathCharInset('=')));
727
728         // go to first item in line
729         cur.idx() -= cur.idx() % ncols();
730         cur.pos() = 0;
731
732         if (getType() == "simple") {
733                 size_type pos = cur.cell().find_last(eq);
734                 MathArray ar;
735                 if (cur.inMathed() && cur.selection()) {
736                         asArray(cur.grabAndEraseSelection(), ar);
737                 } else if (pos == cur.cell().size()) {
738                         ar = cur.cell();
739                         lyxerr << "use whole cell: " << ar << endl;
740                 } else {
741                         ar = MathArray(cur.cell().begin() + pos + 1, cur.cell().end());
742                         lyxerr << "use partial cell form pos: " << pos << endl;
743                 }
744                 cur.cell().append(eq);
745                 cur.cell().append(pipeThroughExtern(lang, extra, ar));
746                 cur.pos() = cur.lastpos();
747                 return;
748         }
749
750         if (getType() == "equation") {
751                 lyxerr << "use equation inset" << endl;
752                 mutate("eqnarray");
753                 MathArray & ar = cur.cell();
754                 lyxerr << "use cell: " << ar << endl;
755                 ++cur.idx();
756                 cur.cell() = eq;
757                 ++cur.idx();
758                 cur.cell() = pipeThroughExtern(lang, extra, ar);
759                 // move to end of line
760                 cur.pos() = cur.lastpos();
761                 return;
762         }
763
764         {
765                 lyxerr << "use eqnarray" << endl;
766                 cur.idx() += 2 - cur.idx() % ncols();
767                 cur.pos() = 0;
768                 MathArray ar = cur.cell();
769                 lyxerr << "use cell: " << ar << endl;
770 #ifdef WITH_WARNINGS
771 #warning temporarily disabled
772 #endif
773                 addRow(cur.row());
774                 ++cur.idx();
775                 ++cur.idx();
776                 cur.cell() = eq;
777                 ++cur.idx();
778                 cur.cell() = pipeThroughExtern(lang, extra, ar);
779                 cur.pos() = cur.lastpos();
780         }
781 }
782
783
784 void MathHullInset::priv_dispatch(LCursor & cur, FuncRequest & cmd)
785 {
786         //lyxerr << "*** MathHullInset: request: " << cmd << endl;
787         switch (cmd.action) {
788
789         case LFUN_BREAKLINE:
790                 if (type_ == "simple" || type_ == "equation") {
791                         mutate("eqnarray");
792                         cur.idx() = 1;
793                         cur.pos() = 0;
794                         //cur.dispatched(FINISHED);
795                         break;
796                 }
797                 MathGridInset::priv_dispatch(cur, cmd);
798                 break;
799
800         case LFUN_MATH_NUMBER:
801                 //lyxerr << "toggling all numbers" << endl;
802                 if (display()) {
803                         recordUndo(cur);
804                         bool old = numberedType();
805                         if (type_ == "multline")
806                                 numbered(nrows() - 1, !old);
807                         else
808                                 for (row_type row = 0; row < nrows(); ++row)
809                                         numbered(row, !old);
810                         cur.message(old ? _("No number") : _("Number"));
811                 }
812                 break;
813
814         case LFUN_MATH_NONUMBER:
815                 if (display()) {
816                         row_type r = (type_ == "multline") ? nrows() - 1 : cur.row();
817                         recordUndo(cur);
818                         bool old = numbered(r);
819                         cur.message(old ? _("No number") : _("Number"));
820                         numbered(r, !old);
821                 }
822                 break;
823
824         case LFUN_INSERT_LABEL: {
825                 row_type r = (type_ == "multline") ? nrows() - 1 : cur.row();
826                 string old_label = label(r);
827                 string new_label = cmd.argument;
828
829                 if (new_label.empty()) {
830                         string const default_label =
831                                 (lyxrc.label_init_length >= 0) ? "eq:" : "";
832                         pair<bool, string> const res = old_label.empty()
833                                 ? Alert::askForText(_("Enter new label to insert:"), default_label)
834                                 : Alert::askForText(_("Enter label:"), old_label);
835                         new_label = lyx::support::trim(res.second);
836                 }
837
838                 if (!new_label.empty())
839                         numbered(r, true);
840                 label(r, new_label);
841                 break;
842         }
843
844         case LFUN_MATH_EXTERN:
845                 doExtern(cur, cmd);
846                 //cur.dispatched(FINISHED);
847                 break;
848
849         case LFUN_MATH_MUTATE: {
850                 lyxerr << "Hull: MUTATE: " << cmd.argument << endl;
851                 row_type row = cur.row();
852                 col_type col = cur.col();
853                 mutate(cmd.argument);
854                 cur.idx() = row * ncols() + col;
855                 if (cur.idx() > cur.lastidx()) {
856                         cur.idx() = cur.lastidx();
857                         cur.pos() = cur.lastpos();
858                 }
859                 if (cur.pos() > cur.lastpos())
860                         cur.pos() = cur.lastpos();
861                 //cur.dispatched(FINISHED);
862                 break;
863         }
864
865         case LFUN_MATH_DISPLAY: {
866                 mutate(type_ == "simple" ? "equation" : "simple");
867                 cur.idx() = 0;
868                 cur.pos() = cur.lastpos();
869                 //cur.dispatched(FINISHED);
870                 break;
871         }
872
873         default:
874                 MathGridInset::priv_dispatch(cur, cmd);
875                 break;
876         }
877 }
878
879
880 bool MathHullInset::getStatus(LCursor & cur, FuncRequest const & cmd,
881                 FuncStatus & flag) const
882 {
883         switch (cmd.action) {
884         case LFUN_BREAKLINE:
885         case LFUN_MATH_NUMBER:
886         case LFUN_MATH_NONUMBER:
887         case LFUN_INSERT_LABEL:
888         case LFUN_MATH_EXTERN:
889         case LFUN_MATH_MUTATE:
890         case LFUN_MATH_DISPLAY:
891                 // we handle these
892                 return true;
893         default:
894                 return MathGridInset::getStatus(cur, cmd, flag);
895         }
896 }
897
898
899 string MathHullInset::fileInsetLabel() const
900 {
901         return "Formula";
902 }
903
904
905 /////////////////////////////////////////////////////////////////////
906
907 #include "formulamacro.h"
908 #include "math_arrayinset.h"
909 #include "math_deliminset.h"
910 #include "math_factory.h"
911 #include "math_parser.h"
912 #include "math_spaceinset.h"
913 #include "ref_inset.h"
914
915 #include "bufferview_funcs.h"
916 #include "lyxtext.h"
917 #include "undo.h"
918
919 #include "frontends/LyXView.h"
920 #include "frontends/Dialogs.h"
921
922 #include "support/std_sstream.h"
923 #include "support/lstrings.h"
924 #include "support/lyxlib.h"
925
926
927 // simply scrap this function if you want
928 void MathHullInset::mutateToText()
929 {
930 #if 0
931         // translate to latex
932         ostringstream os;
933         latex(NULL, os, false, false);
934         string str = os.str();
935
936         // insert this text
937         LyXText * lt = view_->getLyXText();
938         string::const_iterator cit = str.begin();
939         string::const_iterator end = str.end();
940         for (; cit != end; ++cit)
941                 view_->owner()->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
942
943         // remove ourselves
944         //view_->owner()->dispatch(LFUN_ESCAPE);
945 #endif
946 }
947
948
949 void MathHullInset::handleFont(LCursor & cur, string const & arg,
950         string const & font)
951 {
952         // this whole function is a hack and won't work for incremental font
953         // changes...
954         recordUndo(cur);
955         if (cur.inset().asMathInset()->name() == font)
956                 cur.handleFont(font);
957         else {
958                 cur.handleNest(createMathInset(font));
959                 cur.insert(arg);
960         }
961 }
962
963
964 void MathHullInset::handleFont2(LCursor & cur, string const & arg)
965 {
966         recordUndo(cur);
967         LyXFont font;
968         bool b;
969         bv_funcs::string2font(arg, font, b);
970         if (font.color() != LColor::inherit) {
971                 MathAtom at = createMathInset("color");
972                 asArray(lcolor.getGUIName(font.color()), at.nucleus()->cell(0));
973                 cur.handleNest(at, 1);
974         }
975 }
976
977
978 void MathHullInset::edit(LCursor & cur, bool left)
979 {
980         lyxerr << "MathHullInset: edit left/right" << endl;
981         cur.push(*this);
982 }
983
984
985 string const MathHullInset::editMessage() const
986 {
987         return _("Math editor mode");
988 }
989
990
991 void MathHullInset::getCursorDim(int & asc, int & desc) const
992 {
993         asc = 10;
994         desc = 2;
995         //math_font_max_dim(font_, asc, des);
996 }
997
998
999 void MathHullInset::revealCodes(LCursor & cur) const
1000 {
1001         if (!cur.inMathed())
1002                 return;
1003         ostringstream os;
1004         cur.info(os);
1005         cur.message(os.str());
1006 /*
1007         // write something to the minibuffer
1008         // translate to latex
1009         cur.markInsert(bv);
1010         ostringstream os;
1011         write(NULL, os);
1012         string str = os.str();
1013         cur.markErase(bv);
1014         string::size_type pos = 0;
1015         string res;
1016         for (string::iterator it = str.begin(); it != str.end(); ++it) {
1017                 if (*it == '\n')
1018                         res += ' ';
1019                 else if (*it == '\0') {
1020                         res += "  -X-  ";
1021                         pos = it - str.begin();
1022                 }
1023                 else
1024                         res += *it;
1025         }
1026         if (pos > 30)
1027                 res = res.substr(pos - 30);
1028         if (res.size() > 60)
1029                 res = res.substr(0, 60);
1030         cur.message(res);
1031 */
1032 }
1033
1034
1035 InsetBase::Code MathHullInset::lyxCode() const
1036 {
1037         return MATH_CODE;
1038 }
1039
1040
1041 /////////////////////////////////////////////////////////////////////
1042
1043
1044 #if 1
1045 bool MathHullInset::searchForward(BufferView *, string const &, bool, bool)
1046 {
1047         return false;
1048 }
1049
1050 #else
1051 bool MathHullInset::searchForward(BufferView * bv, string const & str,
1052                                      bool, bool)
1053 {
1054         return false;
1055 #ifdef WITH_WARNINGS
1056 #warning pretty ugly
1057 #endif
1058         static MathHullInset * lastformula = 0;
1059         static CursorBase current = DocIterator(ibegin(nucleus()));
1060         static MathArray ar;
1061         static string laststr;
1062
1063         if (lastformula != this || laststr != str) {
1064                 //lyxerr << "reset lastformula to " << this << endl;
1065                 lastformula = this;
1066                 laststr = str;
1067                 current = ibegin(nucleus());
1068                 ar.clear();
1069                 mathed_parse_cell(ar, str);
1070         } else {
1071                 increment(current);
1072         }
1073         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1074
1075         for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1076                 CursorSlice & top = it.back();
1077                 MathArray const & a = top.asMathInset()->cell(top.idx_);
1078                 if (a.matchpart(ar, top.pos_)) {
1079                         bv->cursor().setSelection(it, ar.size());
1080                         current = it;
1081                         top.pos_ += ar.size();
1082                         bv->update();
1083                         return true;
1084                 }
1085         }
1086
1087         //lyxerr << "not found!" << endl;
1088         lastformula = 0;
1089         return false;
1090 }
1091 #endif
1092
1093
1094 bool MathHullInset::searchBackward(BufferView * bv, string const & what,
1095                                       bool a, bool b)
1096 {
1097         lyxerr[Debug::MATHED]
1098                 << "searching backward not implemented in mathed" << endl;
1099         return searchForward(bv, what, a, b);
1100 }
1101
1102
1103 void MathHullInset::write(Buffer const &, std::ostream & os) const
1104 {
1105         WriteStream wi(os, false, false);
1106         os << fileInsetLabel() << ' ';
1107         write(wi);
1108 }
1109
1110
1111 void MathHullInset::read(Buffer const &, LyXLex & lex)
1112 {
1113         MathAtom at;
1114         mathed_parse_normal(at, lex);
1115         operator=(*at->asHullInset());
1116 }
1117
1118
1119 int MathHullInset::latex(Buffer const &, ostream & os,
1120                         OutputParams const & runparams) const
1121 {
1122         WriteStream wi(os, runparams.moving_arg, true);
1123         write(wi);
1124         return wi.line();
1125 }
1126
1127
1128 int MathHullInset::plaintext(Buffer const &, ostream & os,
1129                         OutputParams const &) const
1130 {
1131         if (0 && display()) {
1132                 Dimension dim;
1133                 TextMetricsInfo mi;
1134                 metricsT(mi, dim);
1135                 TextPainter tpain(dim.width(), dim.height());
1136                 drawT(tpain, 0, dim.ascent());
1137                 tpain.show(os, 3);
1138                 // reset metrics cache to "real" values
1139                 //metrics();
1140                 return tpain.textheight();
1141         } else {
1142                 WriteStream wi(os, false, true);
1143                 wi << ' ' << cell(0) << ' ';
1144                 return wi.line();
1145         }
1146 }
1147
1148
1149 int MathHullInset::linuxdoc(Buffer const & buf, ostream & os,
1150                            OutputParams const & runparams) const
1151 {
1152         return docbook(buf, os, runparams);
1153 }
1154
1155
1156 int MathHullInset::docbook(Buffer const & buf, ostream & os,
1157                           OutputParams const & runparams) const
1158 {
1159         MathMLStream ms(os);
1160         ms << MTag("equation");
1161         ms <<   MTag("alt");
1162         ms <<    "<[CDATA[";
1163         int res = plaintext(buf, ms.os(), runparams);
1164         ms <<    "]]>";
1165         ms <<   ETag("alt");
1166         ms <<   MTag("math");
1167         MathGridInset::mathmlize(ms);
1168         ms <<   ETag("math");
1169         ms << ETag("equation");
1170         return ms.line() + res;
1171 }