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