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