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