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