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