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