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