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