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