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