]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathHull.cpp
Fix a few rename inconsistencies discovered by JMarc in insets and mathed, step 1
[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 "MathArray.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 "bufferview_funcs.h"
29 #include "lyxtext.h"
30
31 #include "buffer.h"
32 #include "bufferparams.h"
33 #include "BufferView.h"
34 #include "CutAndPaste.h"
35 #include "FuncStatus.h"
36 #include "LColor.h"
37 #include "LaTeXFeatures.h"
38 #include "cursor.h"
39 #include "debug.h"
40 #include "dispatchresult.h"
41 #include "funcrequest.h"
42 #include "gettext.h"
43 #include "lyxrc.h"
44 #include "outputparams.h"
45 #include "sgml.h"
46 #include "TextPainter.h"
47 #include "undo.h"
48
49 #include "insets/RenderPreview.h"
50 #include "insets/InsetLabel.h"
51
52 #include "graphics/PreviewImage.h"
53 #include "graphics/PreviewLoader.h"
54
55 #include "support/lyxlib.h"
56 #include "support/lstrings.h"
57
58 #include <boost/bind.hpp>
59
60 #include <sstream>
61
62
63 namespace lyx {
64
65 using cap::grabAndEraseSelection;
66 using support::bformat;
67 using support::subst;
68
69 using std::endl;
70 using std::max;
71 using std::ostream;
72 using std::auto_ptr;
73 using std::istringstream;
74 using std::ostringstream;
75 using std::pair;
76 using std::swap;
77 using std::vector;
78
79
80 namespace {
81
82         int getCols(HullType type)
83         {
84                 switch (type) {
85                         case hullEqnArray:
86                                 return 3;
87                         case hullAlign:
88                         case hullFlAlign:
89                         case hullAlignAt:
90                         case hullXAlignAt:
91                         case hullXXAlignAt:
92                                 return 2;
93                         default:
94                                 return 1;
95                 }
96         }
97
98
99         // returns position of first relation operator in the array
100         // used for "intelligent splitting"
101         size_t firstRelOp(MathArray const & ar)
102         {
103                 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
104                         if ((*it)->isRelOp())
105                                 return it - ar.begin();
106                 return ar.size();
107         }
108
109
110         char const * star(bool numbered)
111         {
112                 return numbered ? "" : "*";
113         }
114
115
116 } // end anon namespace
117
118
119 HullType hullType(docstring const & s)
120 {
121         if (s == "none")      return hullNone;
122         if (s == "simple")    return hullSimple;
123         if (s == "equation")  return hullEquation;
124         if (s == "eqnarray")  return hullEqnArray;
125         if (s == "align")     return hullAlign;
126         if (s == "alignat")   return hullAlignAt;
127         if (s == "xalignat")  return hullXAlignAt;
128         if (s == "xxalignat") return hullXXAlignAt;
129         if (s == "multline")  return hullMultline;
130         if (s == "gather")    return hullGather;
131         if (s == "flalign")   return hullFlAlign;
132         lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
133         return HullType(-1);
134 }
135
136
137 docstring hullName(HullType type)
138 {
139         switch (type) {
140                 case hullNone:       return from_ascii("none");
141                 case hullSimple:     return from_ascii("simple");
142                 case hullEquation:   return from_ascii("equation");
143                 case hullEqnArray:   return from_ascii("eqnarray");
144                 case hullAlign:      return from_ascii("align");
145                 case hullAlignAt:    return from_ascii("alignat");
146                 case hullXAlignAt:   return from_ascii("xalignat");
147                 case hullXXAlignAt:  return from_ascii("xxalignat");
148                 case hullMultline:   return from_ascii("multline");
149                 case hullGather:     return from_ascii("gather");
150                 case hullFlAlign:    return from_ascii("flalign");
151                 default:
152                         lyxerr << "unknown hull type '" << type << "'" << endl;
153                         return from_ascii("none");
154         }
155 }
156
157
158 InsetMathHull::InsetMathHull()
159         : InsetMathGrid(1, 1), type_(hullNone), nonum_(1), label_(1),
160           preview_(new RenderPreview(this))
161 {
162         //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
163         //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
164         //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
165         //lyxerr << "sizeof LyXFont: " << sizeof(LyXFont) << endl;
166         initMath();
167         setDefaults();
168 }
169
170
171 InsetMathHull::InsetMathHull(HullType type)
172         : InsetMathGrid(getCols(type), 1), type_(type), nonum_(1), label_(1),
173           preview_(new RenderPreview(this))
174 {
175         initMath();
176         setDefaults();
177 }
178
179
180 InsetMathHull::InsetMathHull(InsetMathHull const & other)
181         : InsetMathGrid(other),
182           type_(other.type_), nonum_(other.nonum_), label_(other.label_),
183           preview_(new RenderPreview(this))
184 {}
185
186
187 InsetMathHull::~InsetMathHull()
188 {}
189
190
191 auto_ptr<InsetBase> InsetMathHull::doClone() const
192 {
193         return auto_ptr<InsetBase>(new InsetMathHull(*this));
194 }
195
196
197 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
198 {
199         if (this == &other)
200                 return *this;
201         *static_cast<InsetMathGrid*>(this) = InsetMathGrid(other);
202         type_  = other.type_;
203         nonum_ = other.nonum_;
204         label_ = other.label_;
205         preview_.reset(new RenderPreview(*other.preview_, this));
206
207         return *this;
208 }
209
210
211 InsetBase * InsetMathHull::editXY(LCursor & cur, int x, int y)
212 {
213         if (use_preview_) {
214                 edit(cur, true);
215                 return this;
216         }
217         return InsetMathNest::editXY(cur, x, y);
218 }
219
220
221 InsetMath::mode_type InsetMathHull::currentMode() const
222 {
223         if (type_ == hullNone)
224                 return UNDECIDED_MODE;
225         // definitely math mode ...
226         return MATH_MODE;
227 }
228
229
230 bool InsetMathHull::idxFirst(LCursor & cur) const
231 {
232         cur.idx() = 0;
233         cur.pos() = 0;
234         return true;
235 }
236
237
238 bool InsetMathHull::idxLast(LCursor & cur) const
239 {
240         cur.idx() = nargs() - 1;
241         cur.pos() = cur.lastpos();
242         return true;
243 }
244
245
246 char InsetMathHull::defaultColAlign(col_type col)
247 {
248         if (type_ == hullEqnArray)
249                 return "rcl"[col];
250         if (type_ >= hullAlign)
251                 return "rl"[col & 1];
252         return 'c';
253 }
254
255
256 int InsetMathHull::defaultColSpace(col_type col)
257 {
258         if (type_ == hullAlign || type_ == hullAlignAt)
259                 return 0;
260         if (type_ == hullXAlignAt)
261                 return (col & 1) ? 20 : 0;
262         if (type_ == hullXXAlignAt || type_ == hullFlAlign)
263                 return (col & 1) ? 40 : 0;
264         return 0;
265 }
266
267
268 docstring InsetMathHull::standardFont() const
269 {
270         return from_ascii(type_ == hullNone ? "lyxnochange" : "mathnormal");
271 }
272
273
274 bool InsetMathHull::previewState(BufferView * bv) const
275 {
276         if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
277                 graphics::PreviewImage const * pimage =
278                         preview_->getPreviewImage(*bv->buffer());
279                 return pimage && pimage->image();
280         }
281         return false;
282 }
283
284
285 bool InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
286 {
287         if (previewState(mi.base.bv)) {
288                 preview_->metrics(mi, dim);
289                 // insert a one pixel gap in front of the formula
290                 dim.wid += 1;
291                 if (display())
292                         dim.des += displayMargin();
293                 if (dim_ == dim)
294                         return false;
295                 dim_ = dim;
296                 return true;
297         }
298
299         FontSetChanger dummy1(mi.base, standardFont());
300         StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
301
302         // let the cells adjust themselves
303         InsetMathGrid::metrics(mi, dim);
304
305         if (display()) {
306                 dim.asc += displayMargin();
307                 dim.des += displayMargin();
308         }
309
310         if (numberedType()) {
311                 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
312                 int l = 0;
313                 for (row_type row = 0; row < nrows(); ++row)
314                         l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
315
316                 if (l)
317                         dim.wid += 30 + l;
318         }
319
320         // make it at least as high as the current font
321         int asc = 0;
322         int des = 0;
323         math_font_max_dim(mi.base.font, asc, des);
324         dim.asc = max(dim.asc, asc);
325         dim.des = max(dim.des, des);
326
327         if (dim_ == dim)
328                 return false;
329         dim_ = dim;
330         return true;
331 }
332
333
334 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
335 {
336         use_preview_ = previewState(pi.base.bv);
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(LCursor & 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 bool InsetMathHull::display() const
467 {
468         return type_ != hullSimple && type_ != hullNone;
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         MathArray 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) = MathArray(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(1);
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) = MathArray(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() - 1);
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(LCursor & 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 #ifdef WITH_WARNINGS
968 #warning temporarily disabled
969         //if (cur.selection()) {
970         //      MathArray ar;
971         //      selGet(cur.ar);
972         //      lyxerr << "use selection: " << ar << endl;
973         //      insert(pipeThroughExtern(lang, extra, ar));
974         //      return;
975         //}
976 #endif
977
978         MathArray eq;
979         eq.push_back(MathAtom(new InsetMathChar('=')));
980
981         // go to first item in line
982         cur.idx() -= cur.idx() % ncols();
983         cur.pos() = 0;
984
985         if (getType() == hullSimple) {
986                 size_type pos = cur.cell().find_last(eq);
987                 MathArray ar;
988                 if (cur.inMathed() && cur.selection()) {
989                         asArray(grabAndEraseSelection(cur), ar);
990                 } else if (pos == cur.cell().size()) {
991                         ar = cur.cell();
992                         lyxerr << "use whole cell: " << ar << endl;
993                 } else {
994                         ar = MathArray(cur.cell().begin() + pos + 1, cur.cell().end());
995                         lyxerr << "use partial cell form pos: " << pos << endl;
996                 }
997                 cur.cell().append(eq);
998                 cur.cell().append(pipeThroughExtern(lang, extra, ar));
999                 cur.pos() = cur.lastpos();
1000                 return;
1001         }
1002
1003         if (getType() == hullEquation) {
1004                 lyxerr << "use equation inset" << endl;
1005                 mutate(hullEqnArray);
1006                 MathArray & ar = cur.cell();
1007                 lyxerr << "use cell: " << ar << endl;
1008                 ++cur.idx();
1009                 cur.cell() = eq;
1010                 ++cur.idx();
1011                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1012                 // move to end of line
1013                 cur.pos() = cur.lastpos();
1014                 return;
1015         }
1016
1017         {
1018                 lyxerr << "use eqnarray" << endl;
1019                 cur.idx() += 2 - cur.idx() % ncols();
1020                 cur.pos() = 0;
1021                 MathArray ar = cur.cell();
1022                 lyxerr << "use cell: " << ar << endl;
1023 #ifdef WITH_WARNINGS
1024 #warning temporarily disabled
1025 #endif
1026                 addRow(cur.row());
1027                 ++cur.idx();
1028                 ++cur.idx();
1029                 cur.cell() = eq;
1030                 ++cur.idx();
1031                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1032                 cur.pos() = cur.lastpos();
1033         }
1034 }
1035
1036
1037 void InsetMathHull::doDispatch(LCursor & cur, FuncRequest & cmd)
1038 {
1039         //lyxerr << "action: " << cmd.action << endl;
1040         switch (cmd.action) {
1041
1042         case LFUN_FINISHED_LEFT:
1043         case LFUN_FINISHED_RIGHT:
1044         case LFUN_FINISHED_UP:
1045         case LFUN_FINISHED_DOWN:
1046                 //lyxerr << "action: " << cmd.action << endl;
1047                 InsetMathGrid::doDispatch(cur, cmd);
1048                 notifyCursorLeaves(cur);
1049                 cur.undispatched();
1050                 break;
1051
1052         case LFUN_BREAK_PARAGRAPH:
1053                 // just swallow this
1054                 break;
1055
1056         case LFUN_BREAK_LINE:
1057                 // some magic for the common case
1058                 if (type_ == hullSimple || type_ == hullEquation) {
1059                         recordUndoInset(cur);
1060                         bool const align =
1061                                 cur.bv().buffer()->params().use_amsmath == BufferParams::package_on;
1062                         mutate(align ? hullAlign : hullEqnArray);
1063                         cur.idx() = 0;
1064                         cur.pos() = cur.lastpos();
1065                 }
1066                 InsetMathGrid::doDispatch(cur, cmd);
1067                 break;
1068
1069         case LFUN_MATH_NUMBER:
1070                 //lyxerr << "toggling all numbers" << endl;
1071                 if (display()) {
1072                         recordUndoInset(cur);
1073                         bool old = numberedType();
1074                         if (type_ == hullMultline)
1075                                 numbered(nrows() - 1, !old);
1076                         else
1077                                 for (row_type row = 0; row < nrows(); ++row)
1078                                         numbered(row, !old);
1079
1080                         cur.message(old ? _("No number") : _("Number"));
1081                 }
1082                 break;
1083
1084         case LFUN_MATH_NONUMBER:
1085                 if (display()) {
1086                         recordUndoInset(cur);
1087                         row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1088                         bool old = numbered(r);
1089                         cur.message(old ? _("No number") : _("Number"));
1090                         numbered(r, !old);
1091                 }
1092                 break;
1093
1094         case LFUN_LABEL_INSERT: {
1095                 recordUndoInset(cur);
1096                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1097                 docstring old_label = label(r);
1098                 docstring const default_label = from_ascii(
1099                         (lyxrc.label_init_length >= 0) ? "eq:" : "");
1100                 if (old_label.empty())
1101                         old_label = default_label;
1102
1103                 InsetCommandParams p("label");
1104                 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1105                 std::string const data = InsetCommandMailer::params2string("label", p);
1106
1107                 if (cmd.argument().empty())
1108                         cur.bv().showInsetDialog("label", data, 0);
1109                 else {
1110                         FuncRequest fr(LFUN_INSET_INSERT, data);
1111                         dispatch(cur, fr);
1112                 }
1113                 break;
1114         }
1115
1116         case LFUN_INSET_INSERT: {
1117                 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1118                 std::string const name = cmd.getArg(0);
1119                 if (name == "label") {
1120                         InsetCommandParams p("label");
1121                         InsetCommandMailer::string2params(name, to_utf8(cmd.argument()), p);
1122                         docstring str = p["name"];
1123                         recordUndoInset(cur);
1124                         row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1125                         str = support::trim(str);
1126                         if (!str.empty())
1127                                 numbered(r, true);
1128                         docstring old = label(r);
1129                         if (str != old) {
1130                                 cur.bv().buffer()->changeRefsIfUnique(old, str,
1131                                                         InsetBase::REF_CODE);
1132                                 label(r, str);
1133                         }
1134                         break;
1135                 }
1136                 InsetMathGrid::doDispatch(cur, cmd);
1137                 return;
1138         }
1139
1140         case LFUN_MATH_EXTERN:
1141                 recordUndoInset(cur);
1142                 doExtern(cur, cmd);
1143                 break;
1144
1145         case LFUN_MATH_MUTATE: {
1146                 recordUndoInset(cur);
1147                 row_type row = cur.row();
1148                 col_type col = cur.col();
1149                 mutate(hullType(cmd.argument()));
1150                 cur.idx() = row * ncols() + col;
1151                 if (cur.idx() > cur.lastidx()) {
1152                         cur.idx() = cur.lastidx();
1153                         cur.pos() = cur.lastpos();
1154                 }
1155                 if (cur.pos() > cur.lastpos())
1156                         cur.pos() = cur.lastpos();
1157                 //cur.dispatched(FINISHED);
1158                 break;
1159         }
1160
1161         case LFUN_MATH_DISPLAY: {
1162                 recordUndoInset(cur);
1163                 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1164                 cur.idx() = 0;
1165                 cur.pos() = cur.lastpos();
1166                 //cur.dispatched(FINISHED);
1167                 break;
1168         }
1169
1170         default:
1171                 InsetMathGrid::doDispatch(cur, cmd);
1172                 break;
1173         }
1174 }
1175
1176
1177 bool InsetMathHull::getStatus(LCursor & cur, FuncRequest const & cmd,
1178                 FuncStatus & status) const
1179 {
1180         switch (cmd.action) {
1181         case LFUN_FINISHED_LEFT:
1182         case LFUN_FINISHED_RIGHT:
1183         case LFUN_FINISHED_UP:
1184         case LFUN_FINISHED_DOWN:
1185                 status.enabled(true);
1186                 return true;
1187         case LFUN_BREAK_LINE:
1188         case LFUN_MATH_NUMBER:
1189         case LFUN_MATH_NONUMBER:
1190         case LFUN_MATH_EXTERN:
1191         case LFUN_MATH_MUTATE:
1192         case LFUN_MATH_DISPLAY:
1193                 // we handle these
1194                 status.enabled(true);
1195                 return true;
1196         case LFUN_LABEL_INSERT:
1197                 status.enabled(type_ != hullSimple);
1198                 return true;
1199         case LFUN_INSET_INSERT:
1200                 if (cmd.getArg(0) == "label") {
1201                         status.enabled(type_ != hullSimple);
1202                         return true;
1203                 }
1204                 return InsetMathGrid::getStatus(cur, cmd, status);
1205         case LFUN_TABULAR_FEATURE: {
1206                 istringstream is(to_utf8(cmd.argument()));
1207                 std::string s;
1208                 is >> s;
1209                 if (!rowChangeOK()
1210                     && (s == "append-row"
1211                         || s == "delete-row"
1212                         || s == "copy-row")) {
1213                         status.message(bformat(
1214                                 from_utf8(N_("Can't change number of rows in '%1$s'")),
1215                                 hullName(type_)));
1216                         status.enabled(false);
1217                         return true;
1218                 }
1219                 if (!colChangeOK()
1220                     && (s == "append-column"
1221                         || s == "delete-column"
1222                         || s == "copy-column")) {
1223                         status.message(bformat(
1224                                 from_utf8(N_("Can't change number of columns in '%1$s'")),
1225                                 hullName(type_)));
1226                         status.enabled(false);
1227                         return true;
1228                 }
1229                 if ((type_ == hullSimple
1230                   || type_ == hullEquation
1231                   || type_ == hullNone) &&
1232                     (s == "add-hline-above" || s == "add-hline-below")) {
1233                         status.message(bformat(
1234                                 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1235                                 hullName(type_)));
1236                         status.enabled(false);
1237                         return true;
1238                 }
1239                 if (s == "add-vline-left" || s == "add-vline-right") {
1240                         status.message(bformat(
1241                                 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1242                                 hullName(type_)));
1243                         status.enabled(false);
1244                         return true;
1245                 }
1246                 if (s == "valign-top" || s == "valign-middle"
1247                  || s == "valign-bottom" || s == "align-left"
1248                  || s == "align-center" || s == "align-right") {
1249                         status.enabled(false);
1250                         return true;
1251                 }
1252                 return InsetMathGrid::getStatus(cur, cmd, status);
1253         }
1254         default:
1255                 return InsetMathGrid::getStatus(cur, cmd, status);
1256         }
1257
1258         // This cannot really happen, but inserted to shut-up gcc
1259         return InsetMathGrid::getStatus(cur, cmd, status);
1260 }
1261
1262
1263 /////////////////////////////////////////////////////////////////////
1264
1265
1266
1267 // simply scrap this function if you want
1268 void InsetMathHull::mutateToText()
1269 {
1270 #if 0
1271         // translate to latex
1272         ostringstream os;
1273         latex(NULL, os, false, false);
1274         string str = os.str();
1275
1276         // insert this text
1277         LyXText * lt = view_->cursor().innerText();
1278         string::const_iterator cit = str.begin();
1279         string::const_iterator end = str.end();
1280         for (; cit != end; ++cit)
1281                 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1282
1283         // remove ourselves
1284         //dispatch(LFUN_ESCAPE);
1285 #endif
1286 }
1287
1288
1289 void InsetMathHull::handleFont(LCursor & cur, docstring const & arg,
1290         docstring const & font)
1291 {
1292         // this whole function is a hack and won't work for incremental font
1293         // changes...
1294         recordUndo(cur);
1295         if (cur.inset().asInsetMath()->name() == font)
1296                 cur.handleFont(to_utf8(font));
1297         else {
1298                 cur.handleNest(createInsetMath(font));
1299                 cur.insert(arg);
1300         }
1301 }
1302
1303
1304 void InsetMathHull::handleFont2(LCursor & cur, docstring const & arg)
1305 {
1306         recordUndo(cur);
1307         LyXFont font;
1308         bool b;
1309         bv_funcs::string2font(to_utf8(arg), font, b);
1310         if (font.color() != LColor::inherit) {
1311                 MathAtom at = MathAtom(new InsetMathColor(true, font.color()));
1312                 cur.handleNest(at, 0);
1313         }
1314 }
1315
1316
1317 void InsetMathHull::edit(LCursor & cur, bool left)
1318 {
1319         cur.push(*this);
1320         left ? idxFirst(cur) : idxLast(cur);
1321         // The inset formula dimension is not necessarily the same as the
1322         // one of the instant preview image, so we have to indicate to the
1323         // BufferView that a metrics update is needed. 
1324         cur.updateFlags(Update::Force);
1325 }
1326
1327
1328 docstring const InsetMathHull::editMessage() const
1329 {
1330         return _("Math editor mode");
1331 }
1332
1333
1334 void InsetMathHull::revealCodes(LCursor & cur) const
1335 {
1336         if (!cur.inMathed())
1337                 return;
1338         odocstringstream os;
1339         cur.info(os);
1340         cur.message(os.str());
1341 /*
1342         // write something to the minibuffer
1343         // translate to latex
1344         cur.markInsert(bv);
1345         ostringstream os;
1346         write(NULL, os);
1347         string str = os.str();
1348         cur.markErase(bv);
1349         string::size_type pos = 0;
1350         string res;
1351         for (string::iterator it = str.begin(); it != str.end(); ++it) {
1352                 if (*it == '\n')
1353                         res += ' ';
1354                 else if (*it == '\0') {
1355                         res += "  -X-  ";
1356                         pos = it - str.begin();
1357                 }
1358                 else
1359                         res += *it;
1360         }
1361         if (pos > 30)
1362                 res = res.substr(pos - 30);
1363         if (res.size() > 60)
1364                 res = res.substr(0, 60);
1365         cur.message(res);
1366 */
1367 }
1368
1369
1370 InsetBase::Code InsetMathHull::lyxCode() const
1371 {
1372         return MATH_CODE;
1373 }
1374
1375
1376 /////////////////////////////////////////////////////////////////////
1377
1378
1379 #if 0
1380 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1381                                      bool, bool)
1382 {
1383 #ifdef WITH_WARNINGS
1384 #warning completely broken
1385 #endif
1386         static InsetMathHull * lastformula = 0;
1387         static CursorBase current = DocIterator(ibegin(nucleus()));
1388         static MathArray ar;
1389         static string laststr;
1390
1391         if (lastformula != this || laststr != str) {
1392                 //lyxerr << "reset lastformula to " << this << endl;
1393                 lastformula = this;
1394                 laststr = str;
1395                 current = ibegin(nucleus());
1396                 ar.clear();
1397                 mathed_parse_cell(ar, str);
1398         } else {
1399                 increment(current);
1400         }
1401         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1402
1403         for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1404                 CursorSlice & top = it.back();
1405                 MathArray const & a = top.asInsetMath()->cell(top.idx_);
1406                 if (a.matchpart(ar, top.pos_)) {
1407                         bv->cursor().setSelection(it, ar.size());
1408                         current = it;
1409                         top.pos_ += ar.size();
1410                         bv->update();
1411                         return true;
1412                 }
1413         }
1414
1415         //lyxerr << "not found!" << endl;
1416         lastformula = 0;
1417         return false;
1418 }
1419 #endif
1420
1421
1422 void InsetMathHull::write(Buffer const &, std::ostream & os) const
1423 {
1424         odocstringstream oss;
1425         WriteStream wi(oss, false, false);
1426         oss << "Formula ";
1427         write(wi);
1428         os << to_utf8(oss.str());
1429 }
1430
1431
1432 void InsetMathHull::read(Buffer const &, LyXLex & lex)
1433 {
1434         MathAtom at;
1435         mathed_parse_normal(at, lex);
1436         operator=(*at->asHullInset());
1437 }
1438
1439
1440 int InsetMathHull::plaintext(Buffer const &, odocstream & os,
1441                              OutputParams const &) const
1442 {
1443         if (0 && display()) {
1444                 Dimension dim;
1445                 TextMetricsInfo mi;
1446                 metricsT(mi, dim);
1447                 TextPainter tpain(dim.width(), dim.height());
1448                 drawT(tpain, 0, dim.ascent());
1449                 tpain.show(os, 3);
1450                 // reset metrics cache to "real" values
1451                 //metrics();
1452                 return tpain.textheight();
1453         } else {
1454                 odocstringstream oss;
1455                 WriteStream wi(oss, false, true);
1456                 wi << cell(0);
1457
1458                 docstring const str = oss.str();
1459                 os << str;
1460                 return str.size();
1461         }
1462 }
1463
1464
1465 int InsetMathHull::docbook(Buffer const & buf, odocstream & os,
1466                            OutputParams const & runparams) const
1467 {
1468         MathStream ms(os);
1469         int res = 0;
1470         docstring name;
1471         if (getType() == hullSimple)
1472                 name = from_ascii("inlineequation");
1473         else
1474                 name = from_ascii("informalequation");
1475
1476         docstring bname = name;
1477         if (!label(0).empty())
1478                 bname += " id='" + sgml::cleanID(buf, runparams, label(0)) + "'";
1479         ms << MTag(bname);
1480
1481         odocstringstream ls;
1482         if (runparams.flavor == OutputParams::XML) {
1483                 ms << MTag(from_ascii("alt role='tex' "));
1484                 // Workaround for db2latex: db2latex always includes equations with
1485                 // \ensuremath{} or \begin{display}\end{display}
1486                 // so we strip LyX' math environment
1487                 WriteStream wi(ls, false, false);
1488                 InsetMathGrid::write(wi);
1489                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
1490                 ms << ETag(from_ascii("alt"));
1491                 ms << MTag(from_ascii("math"));
1492                 ms << ETag(from_ascii("alt"));
1493                 ms << MTag(from_ascii("math"));
1494                 InsetMathGrid::mathmlize(ms);
1495                 ms << ETag(from_ascii("math"));
1496         } else {
1497                 ms << MTag(from_ascii("alt role='tex'"));
1498                 res = latex(buf, ls, runparams);
1499                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
1500                 ms << ETag(from_ascii("alt"));
1501         }
1502
1503         ms << from_ascii("<graphic fileref=\"eqn/");
1504         if (!label(0).empty())
1505                 ms << sgml::cleanID(buf, runparams, label(0));
1506         else
1507                 ms << sgml::uniqueID(from_ascii("anon"));
1508
1509         if (runparams.flavor == OutputParams::XML)
1510                 ms << from_ascii("\"/>");
1511         else
1512                 ms << from_ascii("\">");
1513
1514         ms << ETag(name);
1515         return ms.line() + res;
1516 }
1517
1518
1519 void InsetMathHull::textString(Buffer const & buf, odocstream & os) const
1520 {
1521         plaintext(buf, os, OutputParams(0));
1522 }
1523
1524
1525 } // namespace lyx