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