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