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