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