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