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