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