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