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