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