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