]> git.lyx.org Git - features.git/blob - src/mathed/InsetMathHull.cpp
LateX export must not depend on screen label.
[features.git] / src / mathed / InsetMathHull.cpp
1 /**
2  * \file InsetMathHull.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetMathArray.h"
14 #include "InsetMathChar.h"
15 #include "InsetMathColor.h"
16 #include "MathData.h"
17 #include "InsetMathDelim.h"
18 #include "MathExtern.h"
19 #include "MathFactory.h"
20 #include "InsetMathHull.h"
21 #include "MathStream.h"
22 #include "MathParser.h"
23 #include "InsetMathSpace.h"
24 #include "MathStream.h"
25 #include "MathSupport.h"
26 #include "InsetMathRef.h"
27
28 #include "Buffer.h"
29 #include "BufferParams.h"
30 #include "BufferView.h"
31 #include "CutAndPaste.h"
32 #include "FuncStatus.h"
33 #include "LaTeXFeatures.h"
34 #include "Cursor.h"
35 #include "DispatchResult.h"
36 #include "FuncRequest.h"
37 #include "LyXRC.h"
38 #include "OutputParams.h"
39 #include "ParIterator.h"
40 #include "sgml.h"
41 #include "Text.h"
42 #include "TextPainter.h"
43 #include "TocBackend.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/debug.h"
54 #include "support/gettext.h"
55 #include "support/lstrings.h"
56
57 #include <sstream>
58
59 using namespace std;
60 using namespace lyx::support;
61
62 namespace lyx {
63
64 using cap::grabAndEraseSelection;
65
66 namespace {
67
68         int getCols(HullType type)
69         {
70                 switch (type) {
71                         case hullEqnArray:
72                                 return 3;
73                         case hullAlign:
74                         case hullFlAlign:
75                         case hullAlignAt:
76                         case hullXAlignAt:
77                         case hullXXAlignAt:
78                                 return 2;
79                         default:
80                                 return 1;
81                 }
82         }
83
84
85         // returns position of first relation operator in the array
86         // used for "intelligent splitting"
87         size_t firstRelOp(MathData const & ar)
88         {
89                 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
90                         if ((*it)->isRelOp())
91                                 return it - ar.begin();
92                 return ar.size();
93         }
94
95
96         char const * star(bool numbered)
97         {
98                 return numbered ? "" : "*";
99         }
100
101
102 } // end anon namespace
103
104
105 HullType hullType(docstring const & s)
106 {
107         if (s == "none")      return hullNone;
108         if (s == "simple")    return hullSimple;
109         if (s == "equation")  return hullEquation;
110         if (s == "eqnarray")  return hullEqnArray;
111         if (s == "align")     return hullAlign;
112         if (s == "alignat")   return hullAlignAt;
113         if (s == "xalignat")  return hullXAlignAt;
114         if (s == "xxalignat") return hullXXAlignAt;
115         if (s == "multline")  return hullMultline;
116         if (s == "gather")    return hullGather;
117         if (s == "flalign")   return hullFlAlign;
118         lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
119         return HullType(-1);
120 }
121
122
123 docstring hullName(HullType type)
124 {
125         switch (type) {
126                 case hullNone:       return from_ascii("none");
127                 case hullSimple:     return from_ascii("simple");
128                 case hullEquation:   return from_ascii("equation");
129                 case hullEqnArray:   return from_ascii("eqnarray");
130                 case hullAlign:      return from_ascii("align");
131                 case hullAlignAt:    return from_ascii("alignat");
132                 case hullXAlignAt:   return from_ascii("xalignat");
133                 case hullXXAlignAt:  return from_ascii("xxalignat");
134                 case hullMultline:   return from_ascii("multline");
135                 case hullGather:     return from_ascii("gather");
136                 case hullFlAlign:    return from_ascii("flalign");
137                 default:
138                         lyxerr << "unknown hull type '" << type << "'" << endl;
139                         return from_ascii("none");
140         }
141 }
142
143 static InsetLabel * dummy_pointer = 0;
144
145 InsetMathHull::InsetMathHull()
146         : InsetMathGrid(1, 1), type_(hullNone), nonum_(1, false), label_(1, dummy_pointer),
147           preview_(new RenderPreview(this))
148 {
149         //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
150         //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
151         //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
152         //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
153         initMath();
154         setDefaults();
155 }
156
157
158 InsetMathHull::InsetMathHull(HullType type)
159         : InsetMathGrid(getCols(type), 1), type_(type), nonum_(1, false), label_(1, dummy_pointer),
160           preview_(new RenderPreview(this))
161 {
162         initMath();
163         setDefaults();
164 }
165
166
167 InsetMathHull::InsetMathHull(InsetMathHull const & other)
168 {
169         operator=(other);
170 }
171
172
173 InsetMathHull::~InsetMathHull()
174 {
175         for (size_t i = 0; i < label_.size(); ++i) {
176                 if (label_[i])
177                         delete label_[i];
178         }
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                 if (label_[i])
197                         delete label_[i];
198         }
199         label_ = other.label_;
200         for (size_t i = 0; i != label_.size(); ++i) {
201                 if (label_[i])
202                         label_[i] = new InsetLabel(*label_[i]);
203         }
204         preview_.reset(new RenderPreview(*other.preview_, this));
205
206         return *this;
207 }
208
209
210 void InsetMathHull::setBuffer(Buffer & buffer)
211 {
212         buffer_ = &buffer;
213         for (size_t i = 0; i != label_.size(); ++i) {
214                 if (label_[i])
215                         label_[i]->setBuffer(buffer);
216         }
217 }
218
219
220 void InsetMathHull::updateLabels(ParIterator const & it)
221 {
222         if (!buffer_) {
223                 //FIXME: buffer_ should be set at creation for this inset! Problem is
224                 // This inset is created at too many places (see Parser::parse1() in
225                 // MathParser.cpp).
226                 return;
227         }
228         for (size_t i = 0; i != label_.size(); ++i) {
229                 if (label_[i])
230                         label_[i]->updateLabels(it);
231         }
232 }
233
234
235 void InsetMathHull::addToToc(ParConstIterator const & pit) const
236 {
237         if (!buffer_) {
238                 //FIXME: buffer_ should be set at creation for this inset! Problem is
239                 // This inset is created at too many places (see Parser::parse1() in
240                 // MathParser.cpp).
241                 return;
242         }
243
244         // FIXME: it would be way better to directly use InsetLabel instead of this
245         // label list. But it should be possible to copy&paste the code in
246         // InsetLabel::addToToc() anyway.
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);
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);
439                 write(wi);
440                 pain.draw(x, y, os.str().c_str());
441         }
442 }
443
444
445 namespace {
446
447 docstring const latex_string(InsetMathHull const & inset)
448 {
449         odocstringstream ls;
450         WriteStream wi(ls, false, false);
451         inset.write(wi);
452         return ls.str();
453 }
454
455 } // namespace anon
456
457
458 void InsetMathHull::addPreview(graphics::PreviewLoader & ploader) const
459 {
460         if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
461                 docstring const snippet = latex_string(*this);
462                 preview_->addPreview(snippet, ploader);
463         }
464 }
465
466
467 bool InsetMathHull::notifyCursorLeaves(Cursor const & /*old*/, Cursor & cur)
468 {
469         if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
470                 Buffer const & buffer = cur.buffer();
471                 docstring const snippet = latex_string(*this);
472                 preview_->addPreview(snippet, buffer);
473                 preview_->startLoading(buffer);
474                 cur.updateFlags(Update::Force);
475         }
476         return false;
477 }
478
479
480 docstring InsetMathHull::label(row_type row) const
481 {
482         BOOST_ASSERT(row < nrows());
483         if (InsetLabel * il = label_[row])
484                 return il->screenLabel();
485         return docstring();
486 }
487
488
489 void InsetMathHull::label(row_type row, docstring const & label)
490 {
491         //lyxerr << "setting label '" << label << "' for row " << row << endl;
492         if (label_[row]) {
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 void InsetMathHull::getLabelList(vector<docstring> & labels) const
540 {
541         for (row_type row = 0; row < nrows(); ++row)
542                 if (label_[row] && !nonum_[row])
543                         labels.push_back(label_[row]->screenLabel());
544 }
545
546
547 bool InsetMathHull::numberedType() const
548 {
549         if (type_ == hullNone)
550                 return false;
551         if (type_ == hullSimple)
552                 return false;
553         if (type_ == hullXXAlignAt)
554                 return false;
555         for (row_type row = 0; row < nrows(); ++row)
556                 if (!nonum_[row])
557                         return true;
558         return false;
559 }
560
561
562 void InsetMathHull::validate(LaTeXFeatures & features) const
563 {
564         if (ams())
565                 features.require("amsmath");
566
567
568         // Validation is necessary only if not using AMS math.
569         // To be safe, we will always run mathedvalidate.
570         //if (features.amsstyle)
571         //  return;
572
573         features.require("boldsymbol");
574         //features.binom      = true;
575
576         InsetMathGrid::validate(features);
577 }
578
579
580 void InsetMathHull::header_write(WriteStream & os) const
581 {
582         bool n = numberedType();
583
584         switch(type_) {
585         case hullNone:
586                 break;
587
588         case hullSimple:
589                 os << '$';
590                 if (cell(0).empty())
591                         os << ' ';
592                 break;
593
594         case hullEquation:
595                 if (n)
596                         os << "\\begin{equation" << star(n) << "}\n";
597                 else
598                         os << "\\[\n";
599                 break;
600
601         case hullEqnArray:
602         case hullAlign:
603         case hullFlAlign:
604         case hullGather:
605         case hullMultline:
606                 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
607                 break;
608
609         case hullAlignAt:
610         case hullXAlignAt:
611                 os << "\\begin{" << hullName(type_) << star(n) << '}'
612                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
613                 break;
614
615         case hullXXAlignAt:
616                 os << "\\begin{" << hullName(type_) << '}'
617                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
618                 break;
619
620         default:
621                 os << "\\begin{unknown" << star(n) << '}';
622                 break;
623         }
624 }
625
626
627 void InsetMathHull::footer_write(WriteStream & os) const
628 {
629         bool n = numberedType();
630
631         switch(type_) {
632         case hullNone:
633                 os << "\n";
634                 break;
635
636         case hullSimple:
637                 os << '$';
638                 break;
639
640         case hullEquation:
641                 if (n)
642                         os << "\\end{equation" << star(n) << "}\n";
643                 else
644                         os << "\\]\n";
645                 break;
646
647         case hullEqnArray:
648         case hullAlign:
649         case hullFlAlign:
650         case hullAlignAt:
651         case hullXAlignAt:
652         case hullGather:
653         case hullMultline:
654                 os << "\\end{" << hullName(type_) << star(n) << "}\n";
655                 break;
656
657         case hullXXAlignAt:
658                 os << "\\end{" << hullName(type_) << "}\n";
659                 break;
660
661         default:
662                 os << "\\end{unknown" << star(n) << '}';
663                 break;
664         }
665 }
666
667
668 bool InsetMathHull::rowChangeOK() const
669 {
670         return
671                 type_ == hullEqnArray || type_ == hullAlign ||
672                 type_ == hullFlAlign || type_ == hullAlignAt ||
673                 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
674                 type_ == hullGather || type_ == hullMultline;
675 }
676
677
678 bool InsetMathHull::colChangeOK() const
679 {
680         return
681                 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
682                 type_ == hullXAlignAt || type_ == hullXXAlignAt;
683 }
684
685
686 void InsetMathHull::addRow(row_type row)
687 {
688         if (!rowChangeOK())
689                 return;
690         nonum_.insert(nonum_.begin() + row + 1, !numberedType());
691         label_.insert(label_.begin() + row + 1, dummy_pointer);
692         InsetMathGrid::addRow(row);
693 }
694
695
696 void InsetMathHull::swapRow(row_type row)
697 {
698         if (nrows() <= 1)
699                 return;
700         if (row + 1 == nrows())
701                 --row;
702         swap(nonum_[row], nonum_[row + 1]);
703         swap(label_[row], label_[row + 1]);
704         InsetMathGrid::swapRow(row);
705 }
706
707
708 void InsetMathHull::delRow(row_type row)
709 {
710         if (nrows() <= 1 || !rowChangeOK())
711                 return;
712         InsetMathGrid::delRow(row);
713         // The last dummy row has no number info nor a label.
714         // Test nrows() + 1 because we have already erased the row.
715         if (row == nrows() + 1)
716                 row--;
717         nonum_.erase(nonum_.begin() + row);
718         if (label_[row])
719                 delete label_[row];
720         label_.erase(label_.begin() + row);
721 }
722
723
724 void InsetMathHull::addCol(col_type col)
725 {
726         if (!colChangeOK())
727                 return;
728         InsetMathGrid::addCol(col);
729 }
730
731
732 void InsetMathHull::delCol(col_type col)
733 {
734         if (ncols() <= 1 || !colChangeOK())
735                 return;
736         InsetMathGrid::delCol(col);
737 }
738
739
740 docstring InsetMathHull::nicelabel(row_type row) const
741 {
742         if (nonum_[row])
743                 return docstring();
744         if (!label_[row])
745                 return from_ascii("(#)");
746         return '(' + label_[row]->screenLabel() + ')';
747 }
748
749
750 void InsetMathHull::glueall()
751 {
752         MathData ar;
753         for (idx_type i = 0; i < nargs(); ++i)
754                 ar.append(cell(i));
755         *this = InsetMathHull(hullSimple);
756         cell(0) = ar;
757         setDefaults();
758 }
759
760
761 void InsetMathHull::splitTo2Cols()
762 {
763         BOOST_ASSERT(ncols() == 1);
764         InsetMathGrid::addCol(1);
765         for (row_type row = 0; row < nrows(); ++row) {
766                 idx_type const i = 2 * row;
767                 pos_type pos = firstRelOp(cell(i));
768                 cell(i + 1) = MathData(cell(i).begin() + pos, cell(i).end());
769                 cell(i).erase(pos, cell(i).size());
770         }
771 }
772
773
774 void InsetMathHull::splitTo3Cols()
775 {
776         BOOST_ASSERT(ncols() < 3);
777         if (ncols() < 2)
778                 splitTo2Cols();
779         InsetMathGrid::addCol(2);
780         for (row_type row = 0; row < nrows(); ++row) {
781                 idx_type const i = 3 * row + 1;
782                 if (cell(i).size()) {
783                         cell(i + 1) = MathData(cell(i).begin() + 1, cell(i).end());
784                         cell(i).erase(1, cell(i).size());
785                 }
786         }
787 }
788
789
790 void InsetMathHull::changeCols(col_type cols)
791 {
792         if (ncols() == cols)
793                 return;
794         else if (ncols() < cols) {
795                 // split columns
796                 if (cols < 3)
797                         splitTo2Cols();
798                 else {
799                         splitTo3Cols();
800                         while (ncols() < cols)
801                                 InsetMathGrid::addCol(ncols());
802                 }
803                 return;
804         }
805
806         // combine columns
807         for (row_type row = 0; row < nrows(); ++row) {
808                 idx_type const i = row * ncols();
809                 for (col_type col = cols; col < ncols(); ++col) {
810                         cell(i + cols - 1).append(cell(i + col));
811                 }
812         }
813         // delete columns
814         while (ncols() > cols) {
815                 InsetMathGrid::delCol(ncols() - 1);
816         }
817 }
818
819
820 HullType InsetMathHull::getType() const
821 {
822         return type_;
823 }
824
825
826 void InsetMathHull::setType(HullType type)
827 {
828         type_ = type;
829         setDefaults();
830 }
831
832
833 void InsetMathHull::mutate(HullType newtype)
834 {
835         //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
836
837         // we try to move along the chain
838         // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
839         //                                     ^                                     |
840         //                                     +-------------------------------------+
841         // we use eqnarray as intermediate type for mutations that are not
842         // directly supported because it handles labels and numbering for
843         // "down mutation".
844
845         if (newtype == type_) {
846                 // done
847         }
848
849         else if (newtype < hullNone) {
850                 // unknown type
851                 dump();
852         }
853
854         else if (type_ == hullNone) {
855                 setType(hullSimple);
856                 numbered(0, false);
857                 mutate(newtype);
858         }
859
860         else if (type_ == hullSimple) {
861                 if (newtype == hullNone) {
862                         setType(hullNone);
863                         numbered(0, false);
864                 } else {
865                         setType(hullEquation);
866                         numbered(0, false);
867                         mutate(newtype);
868                 }
869         }
870
871         else if (type_ == hullEquation) {
872                 if (newtype < type_) {
873                         setType(hullSimple);
874                         numbered(0, false);
875                         mutate(newtype);
876                 } else if (newtype == hullEqnArray) {
877                         // split it "nicely" on the first relop
878                         splitTo3Cols();
879                         setType(hullEqnArray);
880                 } else if (newtype == hullMultline || newtype == hullGather) {
881                         setType(newtype);
882                 } else {
883                         // split it "nicely"
884                         splitTo2Cols();
885                         setType(hullAlign);
886                         mutate(newtype);
887                 }
888         }
889
890         else if (type_ == hullEqnArray) {
891                 if (newtype < type_) {
892                         // set correct (no)numbering
893                         nonum_[0] = true;
894                         for (row_type row = 0; row < nrows(); ++row) {
895                                 if (!nonum_[row]) {
896                                         nonum_[0] = false;
897                                         break;
898                                 }
899                         }
900
901                         // set first non-empty label
902                         for (row_type row = 0; row < nrows(); ++row) {
903                                 if (label_[row]) {
904                                         label_[0] = label_[row];
905                                         break;
906                                 }
907                         }
908
909                         glueall();
910                         mutate(newtype);
911                 } else { // align & Co.
912                         changeCols(2);
913                         setType(hullAlign);
914                         mutate(newtype);
915                 }
916         }
917
918         else if (type_ ==  hullAlign || type_ == hullAlignAt ||
919                  type_ == hullXAlignAt || type_ == hullFlAlign) {
920                 if (newtype < hullAlign) {
921                         changeCols(3);
922                         setType(hullEqnArray);
923                         mutate(newtype);
924                 } else if (newtype == hullGather || newtype == hullMultline) {
925                         changeCols(1);
926                         setType(newtype);
927                 } else if (newtype ==   hullXXAlignAt) {
928                         for (row_type row = 0; row < nrows(); ++row)
929                                 numbered(row, false);
930                         setType(newtype);
931                 } else {
932                         setType(newtype);
933                 }
934         }
935
936         else if (type_ == hullXXAlignAt) {
937                 for (row_type row = 0; row < nrows(); ++row)
938                         numbered(row, false);
939                 if (newtype < hullAlign) {
940                         changeCols(3);
941                         setType(hullEqnArray);
942                         mutate(newtype);
943                 } else if (newtype == hullGather || newtype == hullMultline) {
944                         changeCols(1);
945                         setType(newtype);
946                 } else {
947                         setType(newtype);
948                 }
949         }
950
951         else if (type_ == hullMultline || type_ == hullGather) {
952                 if (newtype == hullGather || newtype == hullMultline)
953                         setType(newtype);
954                 else if (newtype == hullAlign || newtype == hullFlAlign  ||
955                          newtype == hullAlignAt || newtype == hullXAlignAt) {
956                         splitTo2Cols();
957                         setType(newtype);
958                 } else if (newtype ==   hullXXAlignAt) {
959                         splitTo2Cols();
960                         for (row_type row = 0; row < nrows(); ++row)
961                                 numbered(row, false);
962                         setType(newtype);
963                 } else {
964                         splitTo3Cols();
965                         setType(hullEqnArray);
966                         mutate(newtype);
967                 }
968         }
969
970         else {
971                 lyxerr << "mutation from '" << to_utf8(hullName(type_))
972                        << "' to '" << to_utf8(hullName(newtype))
973                        << "' not implemented" << endl;
974         }
975 }
976
977
978 docstring InsetMathHull::eolString(row_type row, bool emptyline, bool fragile) const
979 {
980         docstring res;
981         if (numberedType()) {
982                 if (label_[row] && !nonum_[row])
983                         res += "\\label{" + label_[row]->getParam("name") + '}';
984                 if (nonum_[row] && (type_ != hullMultline))
985                         res += "\\nonumber ";
986         }
987         return res + InsetMathGrid::eolString(row, emptyline, fragile);
988 }
989
990
991 void InsetMathHull::write(WriteStream & os) const
992 {
993         header_write(os);
994         InsetMathGrid::write(os);
995         footer_write(os);
996 }
997
998
999 void InsetMathHull::normalize(NormalStream & os) const
1000 {
1001         os << "[formula " << hullName(type_) << ' ';
1002         InsetMathGrid::normalize(os);
1003         os << "] ";
1004 }
1005
1006
1007 void InsetMathHull::mathmlize(MathStream & os) const
1008 {
1009         InsetMathGrid::mathmlize(os);
1010 }
1011
1012
1013 void InsetMathHull::infoize(odocstream & os) const
1014 {
1015         os << "Type: " << hullName(type_);
1016 }
1017
1018
1019 void InsetMathHull::check() const
1020 {
1021         BOOST_ASSERT(nonum_.size() == nrows());
1022         BOOST_ASSERT(label_.size() == nrows());
1023 }
1024
1025
1026 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1027 {
1028         docstring dlang;
1029         docstring extra;
1030         idocstringstream iss(func.argument());
1031         iss >> dlang >> extra;
1032         if (extra.empty())
1033                 extra = from_ascii("noextra");
1034         string const lang = to_ascii(dlang);
1035
1036         // FIXME: temporarily disabled
1037         //if (cur.selection()) {
1038         //      MathData ar;
1039         //      selGet(cur.ar);
1040         //      lyxerr << "use selection: " << ar << endl;
1041         //      insert(pipeThroughExtern(lang, extra, ar));
1042         //      return;
1043         //}
1044
1045         MathData eq;
1046         eq.push_back(MathAtom(new InsetMathChar('=')));
1047
1048         // go to first item in line
1049         cur.idx() -= cur.idx() % ncols();
1050         cur.pos() = 0;
1051
1052         if (getType() == hullSimple) {
1053                 size_type pos = cur.cell().find_last(eq);
1054                 MathData ar;
1055                 if (cur.inMathed() && cur.selection()) {
1056                         asArray(grabAndEraseSelection(cur), ar);
1057                 } else if (pos == cur.cell().size()) {
1058                         ar = cur.cell();
1059                         lyxerr << "use whole cell: " << ar << endl;
1060                 } else {
1061                         ar = MathData(cur.cell().begin() + pos + 1, cur.cell().end());
1062                         lyxerr << "use partial cell form pos: " << pos << endl;
1063                 }
1064                 cur.cell().append(eq);
1065                 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1066                 cur.pos() = cur.lastpos();
1067                 return;
1068         }
1069
1070         if (getType() == hullEquation) {
1071                 lyxerr << "use equation inset" << endl;
1072                 mutate(hullEqnArray);
1073                 MathData & ar = cur.cell();
1074                 lyxerr << "use cell: " << ar << endl;
1075                 ++cur.idx();
1076                 cur.cell() = eq;
1077                 ++cur.idx();
1078                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1079                 // move to end of line
1080                 cur.pos() = cur.lastpos();
1081                 return;
1082         }
1083
1084         {
1085                 lyxerr << "use eqnarray" << endl;
1086                 cur.idx() += 2 - cur.idx() % ncols();
1087                 cur.pos() = 0;
1088                 MathData ar = cur.cell();
1089                 lyxerr << "use cell: " << ar << endl;
1090                 // FIXME: temporarily disabled
1091                 addRow(cur.row());
1092                 ++cur.idx();
1093                 ++cur.idx();
1094                 cur.cell() = eq;
1095                 ++cur.idx();
1096                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1097                 cur.pos() = cur.lastpos();
1098         }
1099 }
1100
1101
1102 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1103 {
1104         //lyxerr << "action: " << cmd.action << endl;
1105         switch (cmd.action) {
1106
1107         case LFUN_FINISHED_BACKWARD:
1108         case LFUN_FINISHED_FORWARD:
1109         case LFUN_FINISHED_RIGHT:
1110         case LFUN_FINISHED_LEFT:
1111                 //lyxerr << "action: " << cmd.action << endl;
1112                 InsetMathGrid::doDispatch(cur, cmd);
1113                 cur.undispatched();
1114                 break;
1115
1116         case LFUN_BREAK_PARAGRAPH:
1117                 // just swallow this
1118                 break;
1119
1120         case LFUN_NEW_LINE:
1121                 // some magic for the common case
1122                 if (type_ == hullSimple || type_ == hullEquation) {
1123                         cur.recordUndoInset();
1124                         bool const align =
1125                                 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1126                         mutate(align ? hullAlign : hullEqnArray);
1127                         cur.idx() = nrows() * ncols() - 1;
1128                         cur.pos() = cur.lastpos();
1129                 }
1130                 InsetMathGrid::doDispatch(cur, cmd);
1131                 break;
1132
1133         case LFUN_MATH_NUMBER_TOGGLE: {
1134                 //lyxerr << "toggling all numbers" << endl;
1135                 cur.recordUndoInset();
1136                 bool old = numberedType();
1137                 if (type_ == hullMultline)
1138                         numbered(nrows() - 1, !old);
1139                 else
1140                         for (row_type row = 0; row < nrows(); ++row)
1141                                 numbered(row, !old);
1142                 
1143                 cur.message(old ? _("No number") : _("Number"));
1144                 break;
1145         }
1146
1147         case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1148                 cur.recordUndoInset();
1149                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1150                 bool old = numbered(r);
1151                 cur.message(old ? _("No number") : _("Number"));
1152                 numbered(r, !old);
1153                 break;
1154         }
1155
1156         case LFUN_LABEL_INSERT: {
1157                 cur.recordUndoInset();
1158                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1159                 docstring old_label = label(r);
1160                 docstring const default_label = from_ascii(
1161                         (lyxrc.label_init_length >= 0) ? "eq:" : "");
1162                 if (old_label.empty())
1163                         old_label = default_label;
1164
1165                 InsetCommandParams p(LABEL_CODE);
1166                 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1167                 string const data = InsetCommandMailer::params2string("label", p);
1168
1169                 if (cmd.argument().empty())
1170                         cur.bv().showDialog("label", data);
1171                 else {
1172                         FuncRequest fr(LFUN_INSET_INSERT, data);
1173                         dispatch(cur, fr);
1174                 }
1175                 break;
1176         }
1177
1178         case LFUN_INSET_INSERT: {
1179                 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1180                 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1181                 string const name = cmd.getArg(0);
1182                 if (name == "label") {
1183                         InsetCommandParams p(LABEL_CODE);
1184                         InsetCommandMailer::string2params(name, to_utf8(cmd.argument()), p);
1185                         docstring str = p["name"];
1186                         cur.recordUndoInset();
1187                         row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1188                         str = trim(str);
1189                         if (!str.empty())
1190                                 numbered(r, true);
1191                         docstring old = label(r);
1192                         if (str != old) {
1193                                 if (label_[r])
1194                                         // The label will take care of the reference update.
1195                                         label(r, str);
1196                                 else {
1197                                         label(r, str);
1198                                         // Newly created inset so initialize it.
1199                                         label_[r]->initView();
1200                                 }
1201                         }
1202                         break;
1203                 }
1204                 InsetMathGrid::doDispatch(cur, cmd);
1205                 return;
1206         }
1207
1208         case LFUN_MATH_EXTERN:
1209                 cur.recordUndoInset();
1210                 doExtern(cur, cmd);
1211                 break;
1212
1213         case LFUN_MATH_MUTATE: {
1214                 cur.recordUndoInset();
1215                 row_type row = cur.row();
1216                 col_type col = cur.col();
1217                 mutate(hullType(cmd.argument()));
1218                 cur.idx() = row * ncols() + col;
1219                 if (cur.idx() > cur.lastidx()) {
1220                         cur.idx() = cur.lastidx();
1221                         cur.pos() = cur.lastpos();
1222                 }
1223                 if (cur.pos() > cur.lastpos())
1224                         cur.pos() = cur.lastpos();
1225                 
1226                 // FIXME: find some more clever handling of the selection,
1227                 // i.e. preserve it.
1228                 cur.clearSelection();
1229                 //cur.dispatched(FINISHED);
1230                 break;
1231         }
1232
1233         case LFUN_MATH_DISPLAY: {
1234                 cur.recordUndoInset();
1235                 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1236                 cur.idx() = 0;
1237                 cur.pos() = cur.lastpos();
1238                 //cur.dispatched(FINISHED);
1239                 break;
1240         }
1241
1242         default:
1243                 InsetMathGrid::doDispatch(cur, cmd);
1244                 break;
1245         }
1246 }
1247
1248
1249 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1250                 FuncStatus & status) const
1251 {
1252         switch (cmd.action) {
1253         case LFUN_FINISHED_BACKWARD:
1254         case LFUN_FINISHED_FORWARD:
1255         case LFUN_FINISHED_RIGHT:
1256         case LFUN_FINISHED_LEFT:
1257         case LFUN_UP:
1258         case LFUN_DOWN:
1259         case LFUN_NEW_LINE:
1260         case LFUN_MATH_EXTERN:
1261         case LFUN_MATH_MUTATE:
1262         case LFUN_MATH_DISPLAY:
1263                 // we handle these
1264                 status.enabled(true);
1265                 return true;
1266         case LFUN_MATH_NUMBER_TOGGLE:
1267                 // FIXME: what is the right test, this or the one of
1268                 // LABEL_INSERT?
1269                 status.enabled(display());
1270                 status.setOnOff(numberedType());
1271                 return true;
1272         case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1273                 // FIXME: what is the right test, this or the one of
1274                 // LABEL_INSERT?
1275                 status.enabled(display());
1276                 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1277                 status.setOnOff(numbered(r));
1278                 return true;
1279         }
1280         case LFUN_LABEL_INSERT:
1281                 status.enabled(type_ != hullSimple);
1282                 return true;
1283         case LFUN_INSET_INSERT:
1284                 if (cmd.getArg(0) == "label") {
1285                         status.enabled(type_ != hullSimple);
1286                         return true;
1287                 }
1288                 return InsetMathGrid::getStatus(cur, cmd, status);
1289         case LFUN_TABULAR_FEATURE: {
1290                 istringstream is(to_utf8(cmd.argument()));
1291                 string s;
1292                 is >> s;
1293                 if (!rowChangeOK()
1294                     && (s == "append-row"
1295                         || s == "delete-row"
1296                         || s == "copy-row")) {
1297                         status.message(bformat(
1298                                 from_utf8(N_("Can't change number of rows in '%1$s'")),
1299                                 hullName(type_)));
1300                         status.enabled(false);
1301                         return true;
1302                 }
1303                 if (!colChangeOK()
1304                     && (s == "append-column"
1305                         || s == "delete-column"
1306                         || s == "copy-column")) {
1307                         status.message(bformat(
1308                                 from_utf8(N_("Can't change number of columns in '%1$s'")),
1309                                 hullName(type_)));
1310                         status.enabled(false);
1311                         return true;
1312                 }
1313                 if ((type_ == hullSimple
1314                   || type_ == hullEquation
1315                   || type_ == hullNone) &&
1316                     (s == "add-hline-above" || s == "add-hline-below")) {
1317                         status.message(bformat(
1318                                 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1319                                 hullName(type_)));
1320                         status.enabled(false);
1321                         return true;
1322                 }
1323                 if (s == "add-vline-left" || s == "add-vline-right") {
1324                         status.message(bformat(
1325                                 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1326                                 hullName(type_)));
1327                         status.enabled(false);
1328                         return true;
1329                 }
1330                 if (s == "valign-top" || s == "valign-middle"
1331                  || s == "valign-bottom" || s == "align-left"
1332                  || s == "align-center" || s == "align-right") {
1333                         status.enabled(false);
1334                         return true;
1335                 }
1336                 return InsetMathGrid::getStatus(cur, cmd, status);
1337         }
1338         default:
1339                 return InsetMathGrid::getStatus(cur, cmd, status);
1340         }
1341
1342         // This cannot really happen, but inserted to shut-up gcc
1343         return InsetMathGrid::getStatus(cur, cmd, status);
1344 }
1345
1346
1347 /////////////////////////////////////////////////////////////////////
1348
1349
1350
1351 // simply scrap this function if you want
1352 void InsetMathHull::mutateToText()
1353 {
1354 #if 0
1355         // translate to latex
1356         ostringstream os;
1357         latex(NULL, os, false, false);
1358         string str = os.str();
1359
1360         // insert this text
1361         Text * lt = view_->cursor().innerText();
1362         string::const_iterator cit = str.begin();
1363         string::const_iterator end = str.end();
1364         for (; cit != end; ++cit)
1365                 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1366
1367         // remove ourselves
1368         //dispatch(LFUN_ESCAPE);
1369 #endif
1370 }
1371
1372
1373 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1374         docstring const & font)
1375 {
1376         // this whole function is a hack and won't work for incremental font
1377         // changes...
1378         cur.recordUndo();
1379         if (cur.inset().asInsetMath()->name() == font)
1380                 cur.handleFont(to_utf8(font));
1381         else {
1382                 cur.handleNest(createInsetMath(font));
1383                 cur.insert(arg);
1384         }
1385 }
1386
1387
1388 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1389 {
1390         cur.recordUndo();
1391         Font font;
1392         bool b;
1393         font.fromString(to_utf8(arg), b);
1394         if (font.fontInfo().color() != Color_inherit) {
1395                 MathAtom at = MathAtom(new InsetMathColor(true, font.fontInfo().color()));
1396                 cur.handleNest(at, 0);
1397         }
1398 }
1399
1400
1401 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1402 {
1403         cur.push(*this);
1404         bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT || 
1405                 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1406         enter_front ? idxFirst(cur) : idxLast(cur);
1407         // The inset formula dimension is not necessarily the same as the
1408         // one of the instant preview image, so we have to indicate to the
1409         // BufferView that a metrics update is needed.
1410         cur.updateFlags(Update::Force);
1411 }
1412
1413
1414 docstring InsetMathHull::editMessage() const
1415 {
1416         return _("Math editor mode");
1417 }
1418
1419
1420 void InsetMathHull::revealCodes(Cursor & cur) const
1421 {
1422         if (!cur.inMathed())
1423                 return;
1424         odocstringstream os;
1425         cur.info(os);
1426         cur.message(os.str());
1427 /*
1428         // write something to the minibuffer
1429         // translate to latex
1430         cur.markInsert(bv);
1431         ostringstream os;
1432         write(NULL, os);
1433         string str = os.str();
1434         cur.markErase(bv);
1435         string::size_type pos = 0;
1436         string res;
1437         for (string::iterator it = str.begin(); it != str.end(); ++it) {
1438                 if (*it == '\n')
1439                         res += ' ';
1440                 else if (*it == '\0') {
1441                         res += "  -X-  ";
1442                         pos = it - str.begin();
1443                 }
1444                 else
1445                         res += *it;
1446         }
1447         if (pos > 30)
1448                 res = res.substr(pos - 30);
1449         if (res.size() > 60)
1450                 res = res.substr(0, 60);
1451         cur.message(res);
1452 */
1453 }
1454
1455
1456 InsetCode InsetMathHull::lyxCode() const
1457 {
1458         return MATH_CODE;
1459 }
1460
1461
1462 /////////////////////////////////////////////////////////////////////
1463
1464
1465 #if 0
1466 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1467                                      bool, bool)
1468 {
1469         // FIXME: completely broken
1470         static InsetMathHull * lastformula = 0;
1471         static CursorBase current = DocIterator(ibegin(nucleus()));
1472         static MathData ar;
1473         static string laststr;
1474
1475         if (lastformula != this || laststr != str) {
1476                 //lyxerr << "reset lastformula to " << this << endl;
1477                 lastformula = this;
1478                 laststr = str;
1479                 current = ibegin(nucleus());
1480                 ar.clear();
1481                 mathed_parse_cell(ar, str);
1482         } else {
1483                 increment(current);
1484         }
1485         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1486
1487         for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1488                 CursorSlice & top = it.back();
1489                 MathData const & a = top.asInsetMath()->cell(top.idx_);
1490                 if (a.matchpart(ar, top.pos_)) {
1491                         bv->cursor().setSelection(it, ar.size());
1492                         current = it;
1493                         top.pos_ += ar.size();
1494                         bv->update();
1495                         return true;
1496                 }
1497         }
1498
1499         //lyxerr << "not found!" << endl;
1500         lastformula = 0;
1501         return false;
1502 }
1503 #endif
1504
1505
1506 void InsetMathHull::write(ostream & os) const
1507 {
1508         odocstringstream oss;
1509         WriteStream wi(oss, false, false);
1510         oss << "Formula ";
1511         write(wi);
1512         os << to_utf8(oss.str());
1513 }
1514
1515
1516 void InsetMathHull::read(Lexer & lex)
1517 {
1518         MathAtom at;
1519         mathed_parse_normal(at, lex);
1520         operator=(*at->asHullInset());
1521 }
1522
1523
1524 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1525 {
1526         if (0 && display()) {
1527                 Dimension dim;
1528                 TextMetricsInfo mi;
1529                 metricsT(mi, dim);
1530                 TextPainter tpain(dim.width(), dim.height());
1531                 drawT(tpain, 0, dim.ascent());
1532                 tpain.show(os, 3);
1533                 // reset metrics cache to "real" values
1534                 //metrics();
1535                 return tpain.textheight();
1536         } else {
1537                 odocstringstream oss;
1538                 WriteStream wi(oss, false, true);
1539                 wi << cell(0);
1540
1541                 docstring const str = oss.str();
1542                 os << str;
1543                 return str.size();
1544         }
1545 }
1546
1547
1548 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1549 {
1550         MathStream ms(os);
1551         int res = 0;
1552         docstring name;
1553         if (getType() == hullSimple)
1554                 name = from_ascii("inlineequation");
1555         else
1556                 name = from_ascii("informalequation");
1557
1558         docstring bname = name;
1559         if (!label(0).empty())
1560                 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1561
1562         ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1563
1564         odocstringstream ls;
1565         if (runparams.flavor == OutputParams::XML) {
1566                 ms << MTag("alt role='tex' ");
1567                 // Workaround for db2latex: db2latex always includes equations with
1568                 // \ensuremath{} or \begin{display}\end{display}
1569                 // so we strip LyX' math environment
1570                 WriteStream wi(ls, false, false);
1571                 InsetMathGrid::write(wi);
1572                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
1573                 ms << ETag("alt");
1574                 ms << MTag("math");
1575                 ms << ETag("alt");
1576                 ms << MTag("math");
1577                 InsetMathGrid::mathmlize(ms);
1578                 ms << ETag("math");
1579         } else {
1580                 ms << MTag("alt role='tex'");
1581                 res = latex(ls, runparams);
1582                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
1583                 ms << ETag("alt");
1584         }
1585
1586         ms << from_ascii("<graphic fileref=\"eqn/");
1587         if (!label(0).empty())
1588                 ms << sgml::cleanID(buffer(), runparams, label(0));
1589         else
1590                 ms << sgml::uniqueID(from_ascii("anon"));
1591
1592         if (runparams.flavor == OutputParams::XML)
1593                 ms << from_ascii("\"/>");
1594         else
1595                 ms << from_ascii("\">");
1596
1597         ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1598
1599         return ms.line() + res;
1600 }
1601
1602
1603 void InsetMathHull::textString(odocstream & os) const
1604 {
1605         plaintext(os, OutputParams(0));
1606 }
1607
1608
1609 } // namespace lyx