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