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