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