]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathHull.C
This commit fixes a crash when accessing a math inset. This was due to an invalid...
[lyx.git] / src / mathed / InsetMathHull.C
1 /**
2  * \file InsetMathHull.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 "InsetMathArray.h"
14 #include "InsetMathChar.h"
15 #include "InsetMathColor.h"
16 #include "MathData.h"
17 #include "InsetMathDelim.h"
18 #include "MathExtern.h"
19 #include "MathFactory.h"
20 #include "InsetMathHull.h"
21 #include "MathMLStream.h"
22 #include "MathParser.h"
23 #include "InsetMathSpace.h"
24 #include "MathStream.h"
25 #include "MathSupport.h"
26 #include "InsetMathRef.h"
27
28 #include "bufferview_funcs.h"
29 #include "lyxtext.h"
30
31 #include "buffer.h"
32 #include "bufferparams.h"
33 #include "BufferView.h"
34 #include "CutAndPaste.h"
35 #include "FuncStatus.h"
36 #include "LColor.h"
37 #include "LaTeXFeatures.h"
38 #include "cursor.h"
39 #include "debug.h"
40 #include "dispatchresult.h"
41 #include "funcrequest.h"
42 #include "gettext.h"
43 #include "lyx_main.h"
44 #include "lyxrc.h"
45 #include "outputparams.h"
46 #include "sgml.h"
47 #include "TextPainter.h"
48 #include "undo.h"
49
50 #include "insets/render_preview.h"
51 #include "insets/insetlabel.h"
52
53 #include "graphics/PreviewImage.h"
54 #include "graphics/PreviewLoader.h"
55
56 #include "support/lyxlib.h"
57 #include "support/lstrings.h"
58
59 #include <boost/bind.hpp>
60
61 #include <sstream>
62
63 using lyx::docstring;
64 using lyx::cap::grabAndEraseSelection;
65 using lyx::support::bformat;
66 using lyx::support::subst;
67
68 using std::endl;
69 using std::max;
70 using std::string;
71 using std::ostream;
72 using std::auto_ptr;
73 using std::istringstream;
74 using std::ostream;
75 using std::ostringstream;
76 using std::pair;
77 using std::swap;
78 using std::vector;
79
80
81 namespace {
82
83         int getCols(HullType type)
84         {
85                 switch (type) {
86                         case hullEqnArray:
87                                 return 3;
88                         case hullAlign:
89                         case hullFlAlign:
90                         case hullAlignAt:
91                         case hullXAlignAt:
92                         case hullXXAlignAt:
93                                 return 2;
94                         default:
95                                 return 1;
96                 }
97         }
98
99
100         // returns position of first relation operator in the array
101         // used for "intelligent splitting"
102         size_t firstRelOp(MathArray const & ar)
103         {
104                 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
105                         if ((*it)->isRelOp())
106                                 return it - ar.begin();
107                 return ar.size();
108         }
109
110
111         char const * star(bool numbered)
112         {
113                 return numbered ? "" : "*";
114         }
115
116
117 } // end anon namespace
118
119
120 HullType hullType(std::string const & s)
121 {
122         if (s == "none")      return hullNone;
123         if (s == "simple")    return hullSimple;
124         if (s == "equation")  return hullEquation;
125         if (s == "eqnarray")  return hullEqnArray;
126         if (s == "align")     return hullAlign;
127         if (s == "alignat")   return hullAlignAt;
128         if (s == "xalignat")  return hullXAlignAt;
129         if (s == "xxalignat") return hullXXAlignAt;
130         if (s == "multline")  return hullMultline;
131         if (s == "gather")    return hullGather;
132         if (s == "flalign")   return hullFlAlign;
133         lyxerr << "unknown hull type '" << s << "'" << endl;
134         return HullType(-1);
135 }
136
137
138 std::string hullName(HullType type)
139 {
140         switch (type) {
141                 case hullNone:       return "none";
142                 case hullSimple:     return "simple";
143                 case hullEquation:   return "equation";
144                 case hullEqnArray:   return "eqnarray";
145                 case hullAlign:      return "align";
146                 case hullAlignAt:    return "alignat";
147                 case hullXAlignAt:   return "xalignat";
148                 case hullXXAlignAt:  return "xxalignat";
149                 case hullMultline:   return "multline";
150                 case hullGather:     return "gather";
151                 case hullFlAlign:    return "flalign";
152                 default:
153                         lyxerr << "unknown hull type '" << type << "'" << endl;
154                         return "none";
155         }
156 }
157
158
159 InsetMathHull::InsetMathHull()
160         : InsetMathGrid(1, 1), type_(hullNone), nonum_(1), label_(1),
161           preview_(new RenderPreview(this))
162 {
163         //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
164         //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
165         //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
166         //lyxerr << "sizeof LyXFont: " << sizeof(LyXFont) << endl;
167         initMath();
168         setDefaults();
169 }
170
171
172 InsetMathHull::InsetMathHull(HullType type)
173         : InsetMathGrid(getCols(type), 1), type_(type), nonum_(1), label_(1),
174           preview_(new RenderPreview(this))
175 {
176         initMath();
177         setDefaults();
178 }
179
180
181 InsetMathHull::InsetMathHull(InsetMathHull const & other)
182         : InsetMathGrid(other),
183           type_(other.type_), nonum_(other.nonum_), label_(other.label_),
184           preview_(new RenderPreview(this))
185 {}
186
187
188 InsetMathHull::~InsetMathHull()
189 {}
190
191
192 auto_ptr<InsetBase> InsetMathHull::doClone() const
193 {
194         return auto_ptr<InsetBase>(new InsetMathHull(*this));
195 }
196
197
198 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
199 {
200         if (this == &other)
201                 return *this;
202         *static_cast<InsetMathGrid*>(this) = InsetMathGrid(other);
203         type_  = other.type_;
204         nonum_ = other.nonum_;
205         label_ = other.label_;
206         preview_.reset(new RenderPreview(*other.preview_, this));
207
208         return *this;
209 }
210
211
212 InsetBase * InsetMathHull::editXY(LCursor & cur, int x, int y)
213 {
214         if (use_preview_) {
215                 edit(cur, true);
216                 return this;
217         }
218         return InsetMathNest::editXY(cur, x, y);
219 }
220
221
222 InsetMath::mode_type InsetMathHull::currentMode() const
223 {
224         if (type_ == hullNone)
225                 return UNDECIDED_MODE;
226         // definitely math mode ...
227         return MATH_MODE;
228 }
229
230
231 bool InsetMathHull::idxFirst(LCursor & cur) const
232 {
233         cur.idx() = 0;
234         cur.pos() = 0;
235         return true;
236 }
237
238
239 bool InsetMathHull::idxLast(LCursor & cur) const
240 {
241         cur.idx() = nargs() - 1;
242         cur.pos() = cur.lastpos();
243         return true;
244 }
245
246
247 char InsetMathHull::defaultColAlign(col_type col)
248 {
249         if (type_ == hullEqnArray)
250                 return "rcl"[col];
251         if (type_ >= hullAlign)
252                 return "rl"[col & 1];
253         return 'c';
254 }
255
256
257 int InsetMathHull::defaultColSpace(col_type col)
258 {
259         if (type_ == hullAlign || type_ == hullAlignAt)
260                 return 0;
261         if (type_ == hullXAlignAt)
262                 return (col & 1) ? 20 : 0;
263         if (type_ == hullXXAlignAt || type_ == hullFlAlign)
264                 return (col & 1) ? 40 : 0;
265         return 0;
266 }
267
268
269 char const * InsetMathHull::standardFont() const
270 {
271         return type_ == hullNone ? "lyxnochange" : "mathnormal";
272 }
273
274
275 bool InsetMathHull::previewState(BufferView * bv) const
276 {
277         if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
278                 lyx::graphics::PreviewImage const * pimage =
279                         preview_->getPreviewImage(*bv->buffer());
280                 return pimage && pimage->image();
281         }
282         return false;
283 }
284
285
286 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
287 {
288         if (previewState(mi.base.bv)) {
289                 preview_->metrics(mi, dim);
290                 // insert a one pixel gap in front of the formula
291                 dim.wid += 1;
292                 if (display())
293                         dim.des += displayMargin();
294                 dim_ = dim;
295                 return;
296         }
297
298         FontSetChanger dummy1(mi.base, standardFont());
299         StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
300
301         // let the cells adjust themselves
302         InsetMathGrid::metrics(mi, dim);
303
304         if (display()) {
305                 dim.asc += displayMargin();
306                 dim.des += displayMargin();
307         }
308
309         if (numberedType()) {
310                 FontSetChanger dummy(mi.base, "mathbf");
311                 int l = 0;
312                 for (row_type row = 0; row < nrows(); ++row)
313                         l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
314
315                 if (l)
316                         dim.wid += 30 + l;
317         }
318
319         // make it at least as high as the current font
320         int asc = 0;
321         int des = 0;
322         math_font_max_dim(mi.base.font, asc, des);
323         dim.asc = max(dim.asc, asc);
324         dim.des = max(dim.des, des);
325
326         dim_ = dim;
327 }
328
329
330 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
331 {
332         use_preview_ = previewState(pi.base.bv);
333
334         if (use_preview_) {
335                 // one pixel gap in front
336                 preview_->draw(pi, x + 1, y);
337                 setPosCache(pi, x, y);
338                 return;
339         }
340
341         FontSetChanger dummy1(pi.base, standardFont());
342         StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
343         InsetMathGrid::draw(pi, x + 1, y);
344
345         if (numberedType()) {
346                 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
347                 for (row_type row = 0; row < nrows(); ++row) {
348                         int const yy = y + rowinfo_[row].offset_;
349                         FontSetChanger dummy(pi.base, "mathrm");
350                         docstring const nl = nicelabel(row);
351                         pi.draw(xx, yy, nl);
352                 }
353         }
354         setPosCache(pi, x, y);
355 }
356
357
358 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
359 {
360         if (display()) {
361                 InsetMathGrid::metricsT(mi, dim);
362         } else {
363                 ostringstream os;
364                 WriteStream wi(os, false, true);
365                 write(wi);
366                 dim.wid = os.str().size();
367                 dim.asc = 1;
368                 dim.des = 0;
369         }
370 }
371
372
373 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
374 {
375         if (display()) {
376                 InsetMathGrid::drawT(pain, x, y);
377         } else {
378                 ostringstream os;
379                 WriteStream wi(os, false, true);
380                 write(wi);
381                 pain.draw(x, y, os.str().c_str());
382         }
383 }
384
385
386 namespace {
387
388 string const latex_string(InsetMathHull const & inset)
389 {
390         ostringstream ls;
391         WriteStream wi(ls, false, false);
392         inset.write(wi);
393         return ls.str();
394 }
395
396 } // namespace anon
397
398
399 void InsetMathHull::addPreview(lyx::graphics::PreviewLoader & ploader) const
400 {
401         if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
402                 string const snippet = latex_string(*this);
403                 preview_->addPreview(snippet, ploader);
404         }
405 }
406
407
408 bool InsetMathHull::notifyCursorLeaves(LCursor & cur)
409 {
410         if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
411                 Buffer const & buffer = cur.buffer();
412                 string const snippet = latex_string(*this);
413                 preview_->addPreview(snippet, buffer);
414                 preview_->startLoading(buffer);
415         }
416         return false;
417 }
418
419
420 string InsetMathHull::label(row_type row) const
421 {
422         BOOST_ASSERT(row < nrows());
423         return label_[row];
424 }
425
426
427 void InsetMathHull::label(row_type row, string const & label)
428 {
429         //lyxerr << "setting label '" << label << "' for row " << row << endl;
430         label_[row] = label;
431 }
432
433
434 void InsetMathHull::numbered(row_type row, bool num)
435 {
436         nonum_[row] = !num;
437 }
438
439
440 bool InsetMathHull::numbered(row_type row) const
441 {
442         return !nonum_[row];
443 }
444
445
446 bool InsetMathHull::ams() const
447 {
448         return
449                 type_ == hullAlign ||
450                 type_ == hullFlAlign ||
451                 type_ == hullMultline ||
452                 type_ == hullGather ||
453                 type_ == hullAlignAt ||
454                 type_ == hullXAlignAt ||
455                 type_ == hullXXAlignAt;
456 }
457
458
459 bool InsetMathHull::display() const
460 {
461         return type_ != hullSimple && type_ != hullNone;
462 }
463
464
465 void InsetMathHull::getLabelList(Buffer const &, vector<docstring> & labels) const
466 {
467         for (row_type row = 0; row < nrows(); ++row)
468                 if (!label_[row].empty() && nonum_[row] != 1)
469                         // FIXME UNICODE
470                         labels.push_back(lyx::from_utf8(label_[row]));
471 }
472
473
474 bool InsetMathHull::numberedType() const
475 {
476         if (type_ == hullNone)
477                 return false;
478         if (type_ == hullSimple)
479                 return false;
480         if (type_ == hullXXAlignAt)
481                 return false;
482         for (row_type row = 0; row < nrows(); ++row)
483                 if (!nonum_[row])
484                         return true;
485         return false;
486 }
487
488
489 void InsetMathHull::validate(LaTeXFeatures & features) const
490 {
491         if (ams())
492                 features.require("amsmath");
493
494
495         // Validation is necessary only if not using AMS math.
496         // To be safe, we will always run mathedvalidate.
497         //if (features.amsstyle)
498         //  return;
499
500         features.require("boldsymbol");
501         //features.binom      = true;
502
503         InsetMathGrid::validate(features);
504 }
505
506
507 void InsetMathHull::header_write(WriteStream & os) const
508 {
509         bool n = numberedType();
510
511         switch(type_) {
512         case hullNone:
513                 break;
514
515         case hullSimple:
516                 os << '$';
517                 if (cell(0).empty())
518                         os << ' ';
519                 break;
520
521         case hullEquation:
522                 if (n)
523                         os << "\\begin{equation" << star(n) << "}\n";
524                 else
525                         os << "\\[\n";
526                 break;
527
528         case hullEqnArray:
529         case hullAlign:
530         case hullFlAlign:
531         case hullGather:
532         case hullMultline:
533                 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
534                 break;
535
536         case hullAlignAt:
537         case hullXAlignAt:
538                 os << "\\begin{" << hullName(type_) << star(n) << '}'
539                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
540                 break;
541
542         case hullXXAlignAt:
543                 os << "\\begin{" << hullName(type_) << '}'
544                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
545                 break;
546
547         default:
548                 os << "\\begin{unknown" << star(n) << '}';
549                 break;
550         }
551 }
552
553
554 void InsetMathHull::footer_write(WriteStream & os) const
555 {
556         bool n = numberedType();
557
558         switch(type_) {
559         case hullNone:
560                 os << "\n";
561                 break;
562
563         case hullSimple:
564                 os << '$';
565                 break;
566
567         case hullEquation:
568                 if (n)
569                         os << "\\end{equation" << star(n) << "}\n";
570                 else
571                         os << "\\]\n";
572                 break;
573
574         case hullEqnArray:
575         case hullAlign:
576         case hullFlAlign:
577         case hullAlignAt:
578         case hullXAlignAt:
579         case hullGather:
580         case hullMultline:
581                 os << "\\end{" << hullName(type_) << star(n) << "}\n";
582                 break;
583
584         case hullXXAlignAt:
585                 os << "\\end{" << hullName(type_) << "}\n";
586                 break;
587
588         default:
589                 os << "\\end{unknown" << star(n) << '}';
590                 break;
591         }
592 }
593
594
595 bool InsetMathHull::rowChangeOK() const
596 {
597         return
598                 type_ == hullEqnArray || type_ == hullAlign ||
599                 type_ == hullFlAlign || type_ == hullAlignAt ||
600                 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
601                 type_ == hullGather || type_ == hullMultline;
602 }
603
604
605 bool InsetMathHull::colChangeOK() const
606 {
607         return
608                 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
609                 type_ == hullXAlignAt || type_ == hullXXAlignAt;
610 }
611
612
613 void InsetMathHull::addRow(row_type row)
614 {
615         if (!rowChangeOK())
616                 return;
617         nonum_.insert(nonum_.begin() + row + 1, !numberedType());
618         label_.insert(label_.begin() + row + 1, string());
619         InsetMathGrid::addRow(row);
620 }
621
622
623 void InsetMathHull::swapRow(row_type row)
624 {
625         if (nrows() <= 1)
626                 return;
627         if (row + 1 == nrows())
628                 --row;
629         swap(nonum_[row], nonum_[row + 1]);
630         swap(label_[row], label_[row + 1]);
631         InsetMathGrid::swapRow(row);
632 }
633
634
635 void InsetMathHull::delRow(row_type row)
636 {
637         if (nrows() <= 1 || !rowChangeOK())
638                 return;
639         InsetMathGrid::delRow(row);
640         // The last dummy row has no number info nor a label.
641         // Test nrows() + 1 because we have already erased the row.
642         if (row == nrows() + 1)
643                 row--;
644         nonum_.erase(nonum_.begin() + row);
645         label_.erase(label_.begin() + row);
646 }
647
648
649 void InsetMathHull::addCol(col_type col)
650 {
651         if (!colChangeOK())
652                 return;
653         InsetMathGrid::addCol(col);
654 }
655
656
657 void InsetMathHull::delCol(col_type col)
658 {
659         if (ncols() <= 1 || !colChangeOK())
660                 return;
661         InsetMathGrid::delCol(col);
662 }
663
664
665 docstring InsetMathHull::nicelabel(row_type row) const
666 {
667         if (nonum_[row])
668                 return docstring();
669         if (label_[row].empty())
670                 return lyx::from_ascii("(#)");
671         // FIXME UNICODE
672         return lyx::from_utf8('(' + label_[row] + ')');
673 }
674
675
676 void InsetMathHull::glueall()
677 {
678         MathArray ar;
679         for (idx_type i = 0; i < nargs(); ++i)
680                 ar.append(cell(i));
681         *this = InsetMathHull(hullSimple);
682         cell(0) = ar;
683         setDefaults();
684 }
685
686
687 void InsetMathHull::splitTo2Cols()
688 {
689         BOOST_ASSERT(ncols() == 1);
690         InsetMathGrid::addCol(1);
691         for (row_type row = 0; row < nrows(); ++row) {
692                 idx_type const i = 2 * row;
693                 pos_type pos = firstRelOp(cell(i));
694                 cell(i + 1) = MathArray(cell(i).begin() + pos, cell(i).end());
695                 cell(i).erase(pos, cell(i).size());
696         }
697 }
698
699
700 void InsetMathHull::splitTo3Cols()
701 {
702         BOOST_ASSERT(ncols() < 3);
703         if (ncols() < 2)
704                 splitTo2Cols();
705         InsetMathGrid::addCol(1);
706         for (row_type row = 0; row < nrows(); ++row) {
707                 idx_type const i = 3 * row + 1;
708                 if (cell(i).size()) {
709                         cell(i + 1) = MathArray(cell(i).begin() + 1, cell(i).end());
710                         cell(i).erase(1, cell(i).size());
711                 }
712         }
713 }
714
715
716 void InsetMathHull::changeCols(col_type cols)
717 {
718         if (ncols() == cols)
719                 return;
720         else if (ncols() < cols) {
721                 // split columns
722                 if (cols < 3)
723                         splitTo2Cols();
724                 else {
725                         splitTo3Cols();
726                         while (ncols() < cols)
727                                 InsetMathGrid::addCol(ncols() - 1);
728                 }
729                 return;
730         }
731
732         // combine columns
733         for (row_type row = 0; row < nrows(); ++row) {
734                 idx_type const i = row * ncols();
735                 for (col_type col = cols; col < ncols(); ++col) {
736                         cell(i + cols - 1).append(cell(i + col));
737                 }
738         }
739         // delete columns
740         while (ncols() > cols) {
741                 InsetMathGrid::delCol(ncols() - 1);
742         }
743 }
744
745
746 HullType InsetMathHull::getType() const
747 {
748         return type_;
749 }
750
751
752 void InsetMathHull::setType(HullType type)
753 {
754         type_ = type;
755         setDefaults();
756 }
757
758
759 void InsetMathHull::mutate(HullType newtype)
760 {
761         //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
762
763         // we try to move along the chain
764         // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
765         //                                     ^                                     |
766         //                                     +-------------------------------------+
767         // we use eqnarray as intermediate type for mutations that are not
768         // directly supported because it handles labels and numbering for
769         // "down mutation".
770
771         if (newtype == type_) {
772                 // done
773         }
774
775         else if (newtype < hullNone) {
776                 // unknown type
777                 dump();
778         }
779
780         else if (type_ == hullNone) {
781                 setType(hullSimple);
782                 numbered(0, false);
783                 mutate(newtype);
784         }
785
786         else if (type_ == hullSimple) {
787                 if (newtype == hullNone) {
788                         setType(hullNone);
789                         numbered(0, false);
790                 } else {
791                         setType(hullEquation);
792                         numbered(0, false);
793                         mutate(newtype);
794                 }
795         }
796
797         else if (type_ == hullEquation) {
798                 if (newtype < type_) {
799                         setType(hullSimple);
800                         numbered(0, false);
801                         mutate(newtype);
802                 } else if (newtype == hullEqnArray) {
803                         // split it "nicely" on the first relop
804                         splitTo3Cols();
805                         setType(hullEqnArray);
806                 } else if (newtype == hullMultline || newtype == hullGather) {
807                         setType(newtype);
808                 } else {
809                         // split it "nicely"
810                         splitTo2Cols();
811                         setType(hullAlign);
812                         mutate(newtype);
813                 }
814         }
815
816         else if (type_ == hullEqnArray) {
817                 if (newtype < type_) {
818                         // set correct (no)numbering
819                         bool allnonum = true;
820                         for (row_type row = 0; row < nrows(); ++row)
821                                 if (!nonum_[row])
822                                         allnonum = false;
823
824                         // set first non-empty label
825                         string label;
826                         for (row_type row = 0; row < nrows(); ++row) {
827                                 if (!label_[row].empty()) {
828                                         label = label_[row];
829                                         break;
830                                 }
831                         }
832
833                         glueall();
834                         nonum_[0] = allnonum;
835                         label_[0] = label;
836                         mutate(newtype);
837                 } else { // align & Co.
838                         changeCols(2);
839                         setType(hullAlign);
840                         mutate(newtype);
841                 }
842         }
843
844         else if (type_ ==  hullAlign || type_ == hullAlignAt ||
845                  type_ == hullXAlignAt || type_ == hullFlAlign) {
846                 if (newtype < hullAlign) {
847                         changeCols(3);
848                         setType(hullEqnArray);
849                         mutate(newtype);
850                 } else if (newtype == hullGather || newtype == hullMultline) {
851                         changeCols(1);
852                         setType(newtype);
853                 } else if (newtype ==   hullXXAlignAt) {
854                         for (row_type row = 0; row < nrows(); ++row)
855                                 numbered(row, false);
856                         setType(newtype);
857                 } else {
858                         setType(newtype);
859                 }
860         }
861
862         else if (type_ == hullXXAlignAt) {
863                 for (row_type row = 0; row < nrows(); ++row)
864                         numbered(row, false);
865                 if (newtype < hullAlign) {
866                         changeCols(3);
867                         setType(hullEqnArray);
868                         mutate(newtype);
869                 } else if (newtype == hullGather || newtype == hullMultline) {
870                         changeCols(1);
871                         setType(newtype);
872                 } else {
873                         setType(newtype);
874                 }
875         }
876
877         else if (type_ == hullMultline || type_ == hullGather) {
878                 if (newtype == hullGather || newtype == hullMultline)
879                         setType(newtype);
880                 else if (newtype == hullAlign || newtype == hullFlAlign  ||
881                          newtype == hullAlignAt || newtype == hullXAlignAt) {
882                         splitTo2Cols();
883                         setType(newtype);
884                 } else if (newtype ==   hullXXAlignAt) {
885                         splitTo2Cols();
886                         for (row_type row = 0; row < nrows(); ++row)
887                                 numbered(row, false);
888                         setType(newtype);
889                 } else {
890                         splitTo3Cols();
891                         setType(hullEqnArray);
892                         mutate(newtype);
893                 }
894         }
895
896         else {
897                 lyxerr << "mutation from '" << hullName(type_)
898                        << "' to '" << hullName(newtype)
899                        << "' not implemented" << endl;
900         }
901 }
902
903
904 string InsetMathHull::eolString(row_type row, bool emptyline, bool fragile) const
905 {
906         string res;
907         if (numberedType()) {
908                 if (!label_[row].empty() && !nonum_[row])
909                         res += "\\label{" + label_[row] + '}';
910                 if (nonum_[row] && (type_ != hullMultline))
911                         res += "\\nonumber ";
912         }
913         return res + InsetMathGrid::eolString(row, emptyline, fragile);
914 }
915
916
917 void InsetMathHull::write(WriteStream & os) const
918 {
919         header_write(os);
920         InsetMathGrid::write(os);
921         footer_write(os);
922 }
923
924
925 void InsetMathHull::normalize(NormalStream & os) const
926 {
927         os << "[formula " << hullName(type_) << ' ';
928         InsetMathGrid::normalize(os);
929         os << "] ";
930 }
931
932
933 void InsetMathHull::mathmlize(MathMLStream & os) const
934 {
935         InsetMathGrid::mathmlize(os);
936 }
937
938
939 void InsetMathHull::infoize(ostream & os) const
940 {
941         os << "Type: " << hullName(type_);
942 }
943
944
945 void InsetMathHull::check() const
946 {
947         BOOST_ASSERT(nonum_.size() == nrows());
948         BOOST_ASSERT(label_.size() == nrows());
949 }
950
951
952 void InsetMathHull::doExtern(LCursor & cur, FuncRequest & func)
953 {
954         string lang;
955         string extra;
956         istringstream iss(lyx::to_utf8(func.argument()));
957         iss >> lang >> extra;
958         if (extra.empty())
959                 extra = "noextra";
960
961 #ifdef WITH_WARNINGS
962 #warning temporarily disabled
963         //if (cur.selection()) {
964         //      MathArray ar;
965         //      selGet(cur.ar);
966         //      lyxerr << "use selection: " << ar << endl;
967         //      insert(pipeThroughExtern(lang, extra, ar));
968         //      return;
969         //}
970 #endif
971
972         MathArray eq;
973         eq.push_back(MathAtom(new InsetMathChar('=')));
974
975         // go to first item in line
976         cur.idx() -= cur.idx() % ncols();
977         cur.pos() = 0;
978
979         if (getType() == hullSimple) {
980                 size_type pos = cur.cell().find_last(eq);
981                 MathArray ar;
982                 if (cur.inMathed() && cur.selection()) {
983                         // FIXME UNICODE
984                         asArray(lyx::from_utf8(grabAndEraseSelection(cur)), ar);
985                 } else if (pos == cur.cell().size()) {
986                         ar = cur.cell();
987                         lyxerr << "use whole cell: " << ar << endl;
988                 } else {
989                         ar = MathArray(cur.cell().begin() + pos + 1, cur.cell().end());
990                         lyxerr << "use partial cell form pos: " << pos << endl;
991                 }
992                 cur.cell().append(eq);
993                 cur.cell().append(pipeThroughExtern(lang, extra, ar));
994                 cur.pos() = cur.lastpos();
995                 return;
996         }
997
998         if (getType() == hullEquation) {
999                 lyxerr << "use equation inset" << endl;
1000                 mutate(hullEqnArray);
1001                 MathArray & ar = cur.cell();
1002                 lyxerr << "use cell: " << ar << endl;
1003                 ++cur.idx();
1004                 cur.cell() = eq;
1005                 ++cur.idx();
1006                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1007                 // move to end of line
1008                 cur.pos() = cur.lastpos();
1009                 return;
1010         }
1011
1012         {
1013                 lyxerr << "use eqnarray" << endl;
1014                 cur.idx() += 2 - cur.idx() % ncols();
1015                 cur.pos() = 0;
1016                 MathArray ar = cur.cell();
1017                 lyxerr << "use cell: " << ar << endl;
1018 #ifdef WITH_WARNINGS
1019 #warning temporarily disabled
1020 #endif
1021                 addRow(cur.row());
1022                 ++cur.idx();
1023                 ++cur.idx();
1024                 cur.cell() = eq;
1025                 ++cur.idx();
1026                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1027                 cur.pos() = cur.lastpos();
1028         }
1029 }
1030
1031
1032 void InsetMathHull::doDispatch(LCursor & cur, FuncRequest & cmd)
1033 {
1034         //lyxerr << "action: " << cmd.action << endl;
1035         switch (cmd.action) {
1036
1037         case LFUN_FINISHED_LEFT:
1038         case LFUN_FINISHED_RIGHT:
1039         case LFUN_FINISHED_UP:
1040         case LFUN_FINISHED_DOWN:
1041                 //lyxerr << "action: " << cmd.action << endl;
1042                 InsetMathGrid::doDispatch(cur, cmd);
1043                 notifyCursorLeaves(cur);
1044                 cur.undispatched();
1045                 break;
1046
1047         case LFUN_BREAK_PARAGRAPH:
1048                 // just swallow this
1049                 break;
1050
1051         case LFUN_BREAK_LINE:
1052                 // some magic for the common case
1053                 if (type_ == hullSimple || type_ == hullEquation) {
1054                         recordUndoInset(cur);
1055                         bool const align =
1056                                 cur.bv().buffer()->params().use_amsmath == BufferParams::AMS_ON;
1057                         mutate(align ? hullAlign : hullEqnArray);
1058                         cur.idx() = 0;
1059                         cur.pos() = cur.lastpos();
1060                 }
1061                 InsetMathGrid::doDispatch(cur, cmd);
1062                 break;
1063
1064         case LFUN_MATH_NUMBER:
1065                 //lyxerr << "toggling all numbers" << endl;
1066                 if (display()) {
1067                         recordUndoInset(cur);
1068                         bool old = numberedType();
1069                         if (type_ == hullMultline)
1070                                 numbered(nrows() - 1, !old);
1071                         else
1072                                 for (row_type row = 0; row < nrows(); ++row)
1073                                         numbered(row, !old);
1074
1075                         cur.message(old ? _("No number") : _("Number"));
1076                 }
1077                 break;
1078
1079         case LFUN_MATH_NONUMBER:
1080                 if (display()) {
1081                         recordUndoInset(cur);
1082                         row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1083                         bool old = numbered(r);
1084                         cur.message(old ? _("No number") : _("Number"));
1085                         numbered(r, !old);
1086                 }
1087                 break;
1088
1089         case LFUN_LABEL_INSERT: {
1090                 recordUndoInset(cur);
1091                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1092                 string old_label = label(r);
1093                 string const default_label =
1094                         (lyxrc.label_init_length >= 0) ? "eq:" : "";
1095                 if (old_label.empty())
1096                         old_label = default_label;
1097                 string const contents = cmd.argument().empty() ?
1098                         old_label : lyx::to_utf8(cmd.argument());
1099
1100                 InsetCommandParams p("label", contents);
1101                 string const data = InsetCommandMailer::params2string("label", p);
1102
1103                 if (cmd.argument().empty())
1104                         cur.bv().showInsetDialog("label", data, 0);
1105                 else {
1106                         FuncRequest fr(LFUN_INSET_INSERT, data);
1107                         dispatch(cur, fr);
1108                 }
1109                 break;
1110         }
1111
1112         case LFUN_INSET_INSERT: {
1113                 //lyxerr << "arg: " << lyx::to_utf8(cmd.argument()) << endl;
1114                 string const name = cmd.getArg(0);
1115                 if (name == "label") {
1116                         InsetCommandParams p;
1117                         InsetCommandMailer::string2params(name, lyx::to_utf8(cmd.argument()), p);
1118                         string str = p.getContents();
1119                         recordUndoInset(cur);
1120                         row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1121                         str = lyx::support::trim(str);
1122                         if (!str.empty())
1123                                 numbered(r, true);
1124                         string old = label(r);
1125                         if (str != old) {
1126                                 cur.bv().buffer()->changeRefsIfUnique(old, str,
1127                                                         InsetBase::REF_CODE);
1128                                 label(r, str);
1129                         }
1130                         break;
1131                 }
1132                 InsetMathGrid::doDispatch(cur, cmd);
1133                 return;
1134         }
1135
1136         case LFUN_MATH_EXTERN:
1137                 recordUndoInset(cur);
1138                 doExtern(cur, cmd);
1139                 break;
1140
1141         case LFUN_MATH_MUTATE: {
1142                 recordUndoInset(cur);
1143                 row_type row = cur.row();
1144                 col_type col = cur.col();
1145                 mutate(hullType(lyx::to_utf8(cmd.argument())));
1146                 cur.idx() = row * ncols() + col;
1147                 if (cur.idx() > cur.lastidx()) {
1148                         cur.idx() = cur.lastidx();
1149                         cur.pos() = cur.lastpos();
1150                 }
1151                 if (cur.pos() > cur.lastpos())
1152                         cur.pos() = cur.lastpos();
1153                 //cur.dispatched(FINISHED);
1154                 break;
1155         }
1156
1157         case LFUN_MATH_DISPLAY: {
1158                 recordUndoInset(cur);
1159                 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1160                 cur.idx() = 0;
1161                 cur.pos() = cur.lastpos();
1162                 //cur.dispatched(FINISHED);
1163                 break;
1164         }
1165
1166         default:
1167                 InsetMathGrid::doDispatch(cur, cmd);
1168                 break;
1169         }
1170 }
1171
1172
1173 bool InsetMathHull::getStatus(LCursor & cur, FuncRequest const & cmd,
1174                 FuncStatus & status) const
1175 {
1176         switch (cmd.action) {
1177         case LFUN_FINISHED_LEFT:
1178         case LFUN_FINISHED_RIGHT:
1179         case LFUN_FINISHED_UP:
1180         case LFUN_FINISHED_DOWN:
1181                 status.enabled(true);
1182                 return true;
1183         case LFUN_BREAK_LINE:
1184         case LFUN_MATH_NUMBER:
1185         case LFUN_MATH_NONUMBER:
1186         case LFUN_MATH_EXTERN:
1187         case LFUN_MATH_MUTATE:
1188         case LFUN_MATH_DISPLAY:
1189                 // we handle these
1190                 status.enabled(true);
1191                 return true;
1192         case LFUN_LABEL_INSERT:
1193                 status.enabled(type_ != hullSimple);
1194                 return true;
1195         case LFUN_INSET_INSERT:
1196                 if (cmd.getArg(0) == "label") {
1197                         status.enabled(type_ != hullSimple);
1198                         return true;
1199                 }
1200                 return InsetMathGrid::getStatus(cur, cmd, status);
1201         case LFUN_TABULAR_FEATURE: {
1202                 istringstream is(lyx::to_utf8(cmd.argument()));
1203                 string s;
1204                 is >> s;
1205                 if (!rowChangeOK()
1206                     && (s == "append-row"
1207                         || s == "delete-row"
1208                         || s == "copy-row")) {
1209                         status.message(bformat(
1210                                 lyx::from_utf8(N_("Can't change number of rows in '%1$s'")),
1211                                 lyx::from_utf8(hullName(type_))));
1212                         status.enabled(false);
1213                         return true;
1214                 }
1215                 if (!colChangeOK()
1216                     && (s == "append-column"
1217                         || s == "delete-column"
1218                         || s == "copy-column")) {
1219                         status.message(bformat(
1220                                 lyx::from_utf8(N_("Can't change number of columns in '%1$s'")),
1221                                 lyx::from_utf8(hullName(type_))));
1222                         status.enabled(false);
1223                         return true;
1224                 }
1225                 if ((type_ == hullSimple
1226                   || type_ == hullEquation
1227                   || type_ == hullNone) &&
1228                     (s == "add-hline-above" || s == "add-hline-below")) {
1229                         status.message(bformat(
1230                                 lyx::from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1231                                 lyx::from_utf8(hullName(type_))));
1232                         status.enabled(false);
1233                         return true;
1234                 }
1235                 if (s == "add-vline-left" || s == "add-vline-right") {
1236                         status.message(bformat(
1237                                 lyx::from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1238                                 lyx::from_utf8(hullName(type_))));
1239                         status.enabled(false);
1240                         return true;
1241                 }
1242                 if (s == "valign-top" || s == "valign-middle"
1243                  || s == "valign-bottom" || s == "align-left"
1244                  || s == "align-center" || s == "align-right") {
1245                         status.enabled(false);
1246                         return true;
1247                 }
1248                 return InsetMathGrid::getStatus(cur, cmd, status);
1249         }
1250         default:
1251                 return InsetMathGrid::getStatus(cur, cmd, status);
1252         }
1253
1254         // This cannot really happen, but inserted to shut-up gcc
1255         return InsetMathGrid::getStatus(cur, cmd, status);
1256 }
1257
1258
1259 /////////////////////////////////////////////////////////////////////
1260
1261
1262
1263 // simply scrap this function if you want
1264 void InsetMathHull::mutateToText()
1265 {
1266 #if 0
1267         // translate to latex
1268         ostringstream os;
1269         latex(NULL, os, false, false);
1270         string str = os.str();
1271
1272         // insert this text
1273         LyXText * lt = view_->getLyXText();
1274         string::const_iterator cit = str.begin();
1275         string::const_iterator end = str.end();
1276         for (; cit != end; ++cit)
1277                 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1278
1279         // remove ourselves
1280         //lyx::dispatch(LFUN_ESCAPE);
1281 #endif
1282 }
1283
1284
1285 void InsetMathHull::handleFont(LCursor & cur, string const & arg,
1286         string const & font)
1287 {
1288         // this whole function is a hack and won't work for incremental font
1289         // changes...
1290         recordUndo(cur);
1291         if (cur.inset().asInsetMath()->name() == font)
1292                 cur.handleFont(font);
1293         else {
1294                 cur.handleNest(createInsetMath(font));
1295                 cur.insert(arg);
1296         }
1297 }
1298
1299
1300 void InsetMathHull::handleFont2(LCursor & cur, string const & arg)
1301 {
1302         recordUndo(cur);
1303         LyXFont font;
1304         bool b;
1305         bv_funcs::string2font(arg, font, b);
1306         if (font.color() != LColor::inherit) {
1307                 MathAtom at = MathAtom(new InsetMathColor(true, font.color()));
1308                 cur.handleNest(at, 0);
1309         }
1310 }
1311
1312
1313 void InsetMathHull::edit(LCursor & cur, bool left)
1314 {
1315         cur.push(*this);
1316         left ? idxFirst(cur) : idxLast(cur);
1317 }
1318
1319
1320 docstring const InsetMathHull::editMessage() const
1321 {
1322         return _("Math editor mode");
1323 }
1324
1325
1326 void InsetMathHull::revealCodes(LCursor & cur) const
1327 {
1328         if (!cur.inMathed())
1329                 return;
1330         ostringstream os;
1331         cur.info(os);
1332         cur.message(lyx::from_utf8(os.str()));
1333 /*
1334         // write something to the minibuffer
1335         // translate to latex
1336         cur.markInsert(bv);
1337         ostringstream os;
1338         write(NULL, os);
1339         string str = os.str();
1340         cur.markErase(bv);
1341         string::size_type pos = 0;
1342         string res;
1343         for (string::iterator it = str.begin(); it != str.end(); ++it) {
1344                 if (*it == '\n')
1345                         res += ' ';
1346                 else if (*it == '\0') {
1347                         res += "  -X-  ";
1348                         pos = it - str.begin();
1349                 }
1350                 else
1351                         res += *it;
1352         }
1353         if (pos > 30)
1354                 res = res.substr(pos - 30);
1355         if (res.size() > 60)
1356                 res = res.substr(0, 60);
1357         cur.message(res);
1358 */
1359 }
1360
1361
1362 InsetBase::Code InsetMathHull::lyxCode() const
1363 {
1364         return MATH_CODE;
1365 }
1366
1367
1368 /////////////////////////////////////////////////////////////////////
1369
1370
1371 #if 0
1372 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1373                                      bool, bool)
1374 {
1375 #ifdef WITH_WARNINGS
1376 #warning completely broken
1377 #endif
1378         static InsetMathHull * lastformula = 0;
1379         static CursorBase current = DocIterator(ibegin(nucleus()));
1380         static MathArray ar;
1381         static string laststr;
1382
1383         if (lastformula != this || laststr != str) {
1384                 //lyxerr << "reset lastformula to " << this << endl;
1385                 lastformula = this;
1386                 laststr = str;
1387                 current = ibegin(nucleus());
1388                 ar.clear();
1389                 mathed_parse_cell(ar, str);
1390         } else {
1391                 increment(current);
1392         }
1393         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1394
1395         for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1396                 CursorSlice & top = it.back();
1397                 MathArray const & a = top.asInsetMath()->cell(top.idx_);
1398                 if (a.matchpart(ar, top.pos_)) {
1399                         bv->cursor().setSelection(it, ar.size());
1400                         current = it;
1401                         top.pos_ += ar.size();
1402                         bv->update();
1403                         return true;
1404                 }
1405         }
1406
1407         //lyxerr << "not found!" << endl;
1408         lastformula = 0;
1409         return false;
1410 }
1411 #endif
1412
1413
1414 void InsetMathHull::write(Buffer const &, std::ostream & os) const
1415 {
1416         WriteStream wi(os, false, false);
1417         os << "Formula ";
1418         write(wi);
1419 }
1420
1421
1422 void InsetMathHull::read(Buffer const &, LyXLex & lex)
1423 {
1424         MathAtom at;
1425         mathed_parse_normal(at, lex);
1426         operator=(*at->asHullInset());
1427 }
1428
1429
1430 int InsetMathHull::plaintext(Buffer const &, lyx::odocstream & os,
1431                         OutputParams const &) const
1432 {
1433         if (0 && display()) {
1434                 Dimension dim;
1435                 TextMetricsInfo mi;
1436                 metricsT(mi, dim);
1437                 TextPainter tpain(dim.width(), dim.height());
1438                 drawT(tpain, 0, dim.ascent());
1439                 tpain.show(os, 3);
1440                 // reset metrics cache to "real" values
1441                 //metrics();
1442                 return tpain.textheight();
1443         } else {
1444                 std::ostringstream oss;
1445                 WriteStream wi(oss, false, true);
1446                 wi << cell(0);
1447                 // FIXME UNICODE
1448                 os << lyx::from_utf8(oss.str());
1449                 return wi.line();
1450         }
1451 }
1452
1453
1454 int InsetMathHull::docbook(Buffer const & buf, ostream & os,
1455                           OutputParams const & runparams) const
1456 {
1457         MathMLStream ms(os);
1458         int res = 0;
1459         string name;
1460         if (getType() == hullSimple)
1461                 name = "inlineequation";
1462         else
1463                 name = "informalequation";
1464
1465         string bname = name;
1466         if (!label(0).empty())
1467                 bname += " id=\"" + sgml::cleanID(buf, runparams, label(0)) + "\"";
1468         ms << MTag(bname.c_str());
1469
1470         ostringstream ls;
1471         if (runparams.flavor == OutputParams::XML) {
1472                 ms << MTag("alt role=\"tex\" ");
1473                 // Workaround for db2latex: db2latex always includes equations with
1474                 // \ensuremath{} or \begin{display}\end{display}
1475                 // so we strip LyX' math environment
1476                 WriteStream wi(ls, false, false);
1477                 InsetMathGrid::write(wi);
1478                 ms << subst(subst(ls.str(), "&", "&amp;"), "<", "&lt;");
1479                 ms << ETag("alt");
1480                 ms << MTag("math");
1481                 InsetMathGrid::mathmlize(ms);
1482                 ms << ETag("math");
1483         } else {
1484                 ms << MTag("alt role=\"tex\"");
1485                 res = latex(buf, ls, runparams);
1486                 ms << subst(subst(ls.str(), "&", "&amp;"), "<", "&lt;");
1487                 ms << ETag("alt");
1488         }
1489
1490         ms <<  "<graphic fileref=\"eqn/";
1491         if ( !label(0).empty())
1492                 ms << sgml::cleanID(buf, runparams, label(0));
1493         else
1494                 ms << sgml::uniqueID("anon");
1495
1496         if (runparams.flavor == OutputParams::XML)
1497                 ms << "\"/>";
1498         else
1499                 ms << "\">";
1500
1501         ms << ETag(name.c_str());
1502         return ms.line() + res;
1503 }
1504
1505
1506 int InsetMathHull::textString(Buffer const & buf, lyx::odocstream & os,
1507                        OutputParams const & op) const
1508 {
1509         return plaintext(buf, os, op);
1510 }