]> git.lyx.org Git - features.git/blob - src/mathed/InsetMathHull.cpp
* Buffer::getLabelList(): Speed up and simplify by using the tocBackend.
[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                 delete label_[i];
177 }
178
179
180 Inset * InsetMathHull::clone() const
181 {
182         return new InsetMathHull(*this);
183 }
184
185
186 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
187 {
188         if (this == &other)
189                 return *this;
190         InsetMathGrid::operator=(other);
191         type_  = other.type_;
192         nonum_ = other.nonum_;
193         for (size_t i = 0; i < label_.size(); ++i)
194                 delete label_[i];
195         label_ = other.label_;
196         for (size_t i = 0; i != label_.size(); ++i) {
197                 if (label_[i])
198                         label_[i] = new InsetLabel(*label_[i]);
199         }
200         preview_.reset(new RenderPreview(*other.preview_, this));
201
202         return *this;
203 }
204
205
206 void InsetMathHull::setBuffer(Buffer & buffer)
207 {
208         buffer_ = &buffer;
209         for (idx_type i = 0, n = nargs(); i != n; ++i) {
210                 MathData & data = cell(i);
211                 for (size_t j = 0; j != data.size(); ++j)
212                         data[j].nucleus()->setBuffer(buffer);
213         }
214
215         for (size_t i = 0; i != label_.size(); ++i) {
216                 if (label_[i])
217                         label_[i]->setBuffer(buffer);
218         }
219 }
220
221
222 void InsetMathHull::updateLabels(ParIterator const & it)
223 {
224         if (!buffer_) {
225                 //FIXME: buffer_ should be set at creation for this inset! Problem is
226                 // This inset is created at too many places (see Parser::parse1() in
227                 // MathParser.cpp).
228                 return;
229         }
230         for (size_t i = 0; i != label_.size(); ++i) {
231                 if (label_[i])
232                         label_[i]->updateLabels(it);
233         }
234 }
235
236
237 void InsetMathHull::addToToc(ParConstIterator const & pit) const
238 {
239         if (!buffer_) {
240                 //FIXME: buffer_ should be set at creation for this inset! Problem is
241                 // This inset is created at too many places (see Parser::parse1() in
242                 // MathParser.cpp).
243                 return;
244         }
245
246         // FIXME: it would be way better to directly use InsetLabel instead of this
247         // label list. But it should be possible to copy&paste the code in
248         // InsetLabel::addToToc() anyway.
249
250         Toc & toc = buffer().tocBackend().toc("equation");
251
252         for (row_type row = 0; row != nrows(); ++row) {
253                 if (nonum_[row])
254                         continue;
255                 if (label_[row])
256                         label_[row]->addToToc(pit);
257                 toc.push_back(TocItem(pit, 0, nicelabel(row)));
258         }
259 }
260
261
262 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
263 {
264         if (use_preview_) {
265                 edit(cur, true);
266                 return this;
267         }
268         return InsetMathNest::editXY(cur, x, y);
269 }
270
271
272 InsetMath::mode_type InsetMathHull::currentMode() const
273 {
274         if (type_ == hullNone)
275                 return UNDECIDED_MODE;
276         // definitely math mode ...
277         return MATH_MODE;
278 }
279
280
281 bool InsetMathHull::idxFirst(Cursor & cur) const
282 {
283         cur.idx() = 0;
284         cur.pos() = 0;
285         return true;
286 }
287
288
289 bool InsetMathHull::idxLast(Cursor & cur) const
290 {
291         cur.idx() = nargs() - 1;
292         cur.pos() = cur.lastpos();
293         return true;
294 }
295
296
297 char InsetMathHull::defaultColAlign(col_type col)
298 {
299         if (type_ == hullEqnArray)
300                 return "rcl"[col];
301         if (type_ == hullGather)
302                 return 'c';
303         if (type_ >= hullAlign)
304                 return "rl"[col & 1];
305         return 'c';
306 }
307
308
309 int InsetMathHull::defaultColSpace(col_type col)
310 {
311         if (type_ == hullAlign || type_ == hullAlignAt)
312                 return 0;
313         if (type_ == hullXAlignAt)
314                 return (col & 1) ? 20 : 0;
315         if (type_ == hullXXAlignAt || type_ == hullFlAlign)
316                 return (col & 1) ? 40 : 0;
317         return 0;
318 }
319
320
321 docstring InsetMathHull::standardFont() const
322 {
323         return from_ascii(type_ == hullNone ? "lyxnochange" : "mathnormal");
324 }
325
326
327 bool InsetMathHull::previewState(BufferView * bv) const
328 {
329         if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
330                 graphics::PreviewImage const * pimage =
331                         preview_->getPreviewImage(bv->buffer());
332                 return pimage && pimage->image();
333         }
334         return false;
335 }
336
337
338 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
339 {
340         if (previewState(mi.base.bv)) {
341                 preview_->metrics(mi, dim);
342                 // insert a one pixel gap in front of the formula
343                 dim.wid += 1;
344                 if (display())
345                         dim.des += displayMargin();
346                 // Cache the inset dimension. 
347                 setDimCache(mi, dim);
348                 return;
349         }
350
351         FontSetChanger dummy1(mi.base, standardFont());
352         StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
353
354         // let the cells adjust themselves
355         InsetMathGrid::metrics(mi, dim);
356
357         if (display()) {
358                 dim.asc += displayMargin();
359                 dim.des += displayMargin();
360         }
361
362         if (numberedType()) {
363                 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
364                 int l = 0;
365                 for (row_type row = 0; row < nrows(); ++row)
366                         l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
367
368                 if (l)
369                         dim.wid += 30 + l;
370         }
371
372         // make it at least as high as the current font
373         int asc = 0;
374         int des = 0;
375         math_font_max_dim(mi.base.font, asc, des);
376         dim.asc = max(dim.asc, asc);
377         dim.des = max(dim.des, des);
378         // Cache the inset dimension.
379         // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
380         setDimCache(mi, dim);
381 }
382
383
384 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
385 {
386         use_preview_ = previewState(pi.base.bv);
387         Dimension const dim = dimension(*pi.base.bv);
388
389         // background of mathed under focus is not painted because
390         // selection at the top level of nested inset is difficult to handle.
391         if (!editing(pi.base.bv))
392                 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
393                                 dim.asc + dim.des - 1, Color_mathbg);
394
395         if (use_preview_) {
396                 // one pixel gap in front
397                 preview_->draw(pi, x + 1, y);
398                 setPosCache(pi, x, y);
399                 return;
400         }
401
402         FontSetChanger dummy1(pi.base, standardFont());
403         StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
404         InsetMathGrid::draw(pi, x + 1, y);
405
406         if (numberedType()) {
407                 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
408                 for (row_type row = 0; row < nrows(); ++row) {
409                         int const yy = y + rowinfo_[row].offset_;
410                         FontSetChanger dummy(pi.base, from_ascii("mathrm"));
411                         docstring const nl = nicelabel(row);
412                         pi.draw(xx, yy, nl);
413                 }
414         }
415         setPosCache(pi, x, y);
416 }
417
418
419 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
420 {
421         if (display()) {
422                 InsetMathGrid::metricsT(mi, dim);
423         } else {
424                 odocstringstream os;
425                 WriteStream wi(os, false, true);
426                 write(wi);
427                 dim.wid = os.str().size();
428                 dim.asc = 1;
429                 dim.des = 0;
430         }
431 }
432
433
434 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
435 {
436         if (display()) {
437                 InsetMathGrid::drawT(pain, x, y);
438         } else {
439                 odocstringstream os;
440                 WriteStream wi(os, false, true);
441                 write(wi);
442                 pain.draw(x, y, os.str().c_str());
443         }
444 }
445
446
447 namespace {
448
449 docstring const latex_string(InsetMathHull const & inset)
450 {
451         odocstringstream ls;
452         WriteStream wi(ls, false, false);
453         inset.write(wi);
454         return ls.str();
455 }
456
457 } // namespace anon
458
459
460 void InsetMathHull::addPreview(graphics::PreviewLoader & ploader) const
461 {
462         if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
463                 docstring const snippet = latex_string(*this);
464                 preview_->addPreview(snippet, ploader);
465         }
466 }
467
468
469 bool InsetMathHull::notifyCursorLeaves(Cursor const & /*old*/, Cursor & cur)
470 {
471         if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
472                 Buffer const & buffer = cur.buffer();
473                 docstring const snippet = latex_string(*this);
474                 preview_->addPreview(snippet, buffer);
475                 preview_->startLoading(buffer);
476                 cur.updateFlags(Update::Force);
477         }
478         return false;
479 }
480
481
482 docstring InsetMathHull::label(row_type row) const
483 {
484         BOOST_ASSERT(row < nrows());
485         if (InsetLabel * il = label_[row])
486                 return il->screenLabel();
487         return docstring();
488 }
489
490
491 void InsetMathHull::label(row_type row, docstring const & label)
492 {
493         //lyxerr << "setting label '" << label << "' for row " << row << endl;
494         if (label_[row]) {
495                 label_[row]->updateCommand(label);
496                 return;
497         }
498         InsetCommandParams p(LABEL_CODE);
499         p["name"] = label;
500         label_[row] = new InsetLabel(p);
501         if (buffer_)
502                 label_[row]->setBuffer(buffer());
503 }
504
505
506 void InsetMathHull::numbered(row_type row, bool num)
507 {
508         nonum_[row] = !num;
509         if (nonum_[row] && label_[row]) {
510                 delete label_[row];
511                 label_[row] = 0;
512         }
513 }
514
515
516 bool InsetMathHull::numbered(row_type row) const
517 {
518         return !nonum_[row];
519 }
520
521
522 bool InsetMathHull::ams() const
523 {
524         return
525                 type_ == hullAlign ||
526                 type_ == hullFlAlign ||
527                 type_ == hullMultline ||
528                 type_ == hullGather ||
529                 type_ == hullAlignAt ||
530                 type_ == hullXAlignAt ||
531                 type_ == hullXXAlignAt;
532 }
533
534
535 Inset::DisplayType InsetMathHull::display() const
536 {
537         return (type_ != hullSimple && type_ != hullNone) ? AlignCenter : Inline;
538 }
539
540
541 bool InsetMathHull::numberedType() const
542 {
543         if (type_ == hullNone)
544                 return false;
545         if (type_ == hullSimple)
546                 return false;
547         if (type_ == hullXXAlignAt)
548                 return false;
549         for (row_type row = 0; row < nrows(); ++row)
550                 if (!nonum_[row])
551                         return true;
552         return false;
553 }
554
555
556 void InsetMathHull::validate(LaTeXFeatures & features) const
557 {
558         if (ams())
559                 features.require("amsmath");
560
561
562         // Validation is necessary only if not using AMS math.
563         // To be safe, we will always run mathedvalidate.
564         //if (features.amsstyle)
565         //  return;
566
567         features.require("boldsymbol");
568         //features.binom      = true;
569
570         InsetMathGrid::validate(features);
571 }
572
573
574 void InsetMathHull::header_write(WriteStream & os) const
575 {
576         bool n = numberedType();
577
578         switch(type_) {
579         case hullNone:
580                 break;
581
582         case hullSimple:
583                 os << '$';
584                 if (cell(0).empty())
585                         os << ' ';
586                 break;
587
588         case hullEquation:
589                 if (n)
590                         os << "\\begin{equation" << star(n) << "}\n";
591                 else
592                         os << "\\[\n";
593                 break;
594
595         case hullEqnArray:
596         case hullAlign:
597         case hullFlAlign:
598         case hullGather:
599         case hullMultline:
600                 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
601                 break;
602
603         case hullAlignAt:
604         case hullXAlignAt:
605                 os << "\\begin{" << hullName(type_) << star(n) << '}'
606                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
607                 break;
608
609         case hullXXAlignAt:
610                 os << "\\begin{" << hullName(type_) << '}'
611                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
612                 break;
613
614         default:
615                 os << "\\begin{unknown" << star(n) << '}';
616                 break;
617         }
618 }
619
620
621 void InsetMathHull::footer_write(WriteStream & os) const
622 {
623         bool n = numberedType();
624
625         switch(type_) {
626         case hullNone:
627                 os << "\n";
628                 break;
629
630         case hullSimple:
631                 os << '$';
632                 break;
633
634         case hullEquation:
635                 if (n)
636                         os << "\\end{equation" << star(n) << "}\n";
637                 else
638                         os << "\\]\n";
639                 break;
640
641         case hullEqnArray:
642         case hullAlign:
643         case hullFlAlign:
644         case hullAlignAt:
645         case hullXAlignAt:
646         case hullGather:
647         case hullMultline:
648                 os << "\\end{" << hullName(type_) << star(n) << "}\n";
649                 break;
650
651         case hullXXAlignAt:
652                 os << "\\end{" << hullName(type_) << "}\n";
653                 break;
654
655         default:
656                 os << "\\end{unknown" << star(n) << '}';
657                 break;
658         }
659 }
660
661
662 bool InsetMathHull::rowChangeOK() const
663 {
664         return
665                 type_ == hullEqnArray || type_ == hullAlign ||
666                 type_ == hullFlAlign || type_ == hullAlignAt ||
667                 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
668                 type_ == hullGather || type_ == hullMultline;
669 }
670
671
672 bool InsetMathHull::colChangeOK() const
673 {
674         return
675                 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
676                 type_ == hullXAlignAt || type_ == hullXXAlignAt;
677 }
678
679
680 void InsetMathHull::addRow(row_type row)
681 {
682         if (!rowChangeOK())
683                 return;
684         nonum_.insert(nonum_.begin() + row + 1, !numberedType());
685         label_.insert(label_.begin() + row + 1, dummy_pointer);
686         InsetMathGrid::addRow(row);
687 }
688
689
690 void InsetMathHull::swapRow(row_type row)
691 {
692         if (nrows() <= 1)
693                 return;
694         if (row + 1 == nrows())
695                 --row;
696         // gcc implements the standard std::vector<bool> which is *not* a container:
697         //   http://www.gotw.ca/publications/N1185.pdf
698         // As a results, it doesn't like this:
699         //      swap(nonum_[row], nonum_[row + 1]);
700         // so we do it manually:
701         bool const b = nonum_[row];
702         nonum_[row] = nonum_[row + 1];
703         nonum_[row + 1] = b;
704         swap(label_[row], label_[row + 1]);
705         InsetMathGrid::swapRow(row);
706 }
707
708
709 void InsetMathHull::delRow(row_type row)
710 {
711         if (nrows() <= 1 || !rowChangeOK())
712                 return;
713         InsetMathGrid::delRow(row);
714         // The last dummy row has no number info nor a label.
715         // Test nrows() + 1 because we have already erased the row.
716         if (row == nrows() + 1)
717                 row--;
718         nonum_.erase(nonum_.begin() + 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