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