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