]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathHull.cpp
f0fc1b41e10338dd0cf9d53e0f4b802e3f390ebe
[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, MATH_MODE);
1246         header_write(os);
1247         InsetMathGrid::write(os);
1248         footer_write(os);
1249 }
1250
1251
1252 void InsetMathHull::normalize(NormalStream & os) const
1253 {
1254         os << "[formula " << hullName(type_) << ' ';
1255         InsetMathGrid::normalize(os);
1256         os << "] ";
1257 }
1258
1259
1260 void InsetMathHull::infoize(odocstream & os) const
1261 {
1262         os << "Type: " << hullName(type_);
1263 }
1264
1265
1266 void InsetMathHull::check() const
1267 {
1268         LATTEST(numbered_.size() == nrows());
1269         LATTEST(numbers_.size() == nrows());
1270         LATTEST(label_.size() == nrows());
1271 }
1272
1273
1274 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1275 {
1276         docstring dlang;
1277         docstring extra;
1278         idocstringstream iss(func.argument());
1279         iss >> dlang >> extra;
1280         if (extra.empty())
1281                 extra = from_ascii("noextra");
1282         string const lang = to_ascii(dlang);
1283
1284         // FIXME: temporarily disabled
1285         //if (cur.selection()) {
1286         //      MathData ar;
1287         //      selGet(cur.ar);
1288         //      lyxerr << "use selection: " << ar << endl;
1289         //      insert(pipeThroughExtern(lang, extra, ar));
1290         //      return;
1291         //}
1292
1293         // only inline, display or eqnarray math is allowed
1294         if (getType() > hullEqnArray) {
1295                 frontend::Alert::warning(_("Bad math environment"),
1296                                 _("Computation cannot be performed for AMS "
1297                                   "math environments.\nChange the math "
1298                                   "formula type and try again."));
1299                 return;
1300         }
1301
1302         MathData eq;
1303         eq.push_back(MathAtom(new InsetMathChar('=')));
1304
1305         // go to first item in line
1306         cur.idx() -= cur.idx() % ncols();
1307         cur.pos() = 0;
1308
1309         if (getType() == hullSimple) {
1310                 size_type pos = cur.cell().find_last(eq);
1311                 MathData ar;
1312                 if (cur.inMathed() && cur.selection()) {
1313                         asArray(grabAndEraseSelection(cur), ar);
1314                 } else if (!pos == cur.cell().empty()) {
1315                         ar = cur.cell();
1316                         lyxerr << "use whole cell: " << ar << endl;
1317                 } else {
1318                         ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1319                         lyxerr << "use partial cell form pos: " << pos << endl;
1320                 }
1321                 cur.cell().append(eq);
1322                 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1323                 cur.pos() = cur.lastpos();
1324                 return;
1325         }
1326
1327         if (getType() == hullEquation) {
1328                 lyxerr << "use equation inset" << endl;
1329                 mutate(hullEqnArray);
1330                 MathData & ar = cur.cell();
1331                 lyxerr << "use cell: " << ar << endl;
1332                 ++cur.idx();
1333                 cur.cell() = eq;
1334                 ++cur.idx();
1335                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1336                 // move to end of line
1337                 cur.pos() = cur.lastpos();
1338                 return;
1339         }
1340
1341         {
1342                 lyxerr << "use eqnarray" << endl;
1343                 cur.idx() += 2 - cur.idx() % ncols();
1344                 cur.pos() = 0;
1345                 MathData ar = cur.cell();
1346                 lyxerr << "use cell: " << ar << endl;
1347                 // FIXME: temporarily disabled
1348                 addRow(cur.row());
1349                 ++cur.idx();
1350                 ++cur.idx();
1351                 cur.cell() = eq;
1352                 ++cur.idx();
1353                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1354                 cur.pos() = cur.lastpos();
1355         }
1356 }
1357
1358
1359 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1360 {
1361         //lyxerr << "action: " << cmd.action() << endl;
1362         switch (cmd.action()) {
1363
1364         case LFUN_FINISHED_BACKWARD:
1365         case LFUN_FINISHED_FORWARD:
1366         case LFUN_FINISHED_RIGHT:
1367         case LFUN_FINISHED_LEFT:
1368                 //lyxerr << "action: " << cmd.action() << endl;
1369                 InsetMathGrid::doDispatch(cur, cmd);
1370                 cur.undispatched();
1371                 break;
1372
1373         case LFUN_PARAGRAPH_BREAK:
1374                 // just swallow this
1375                 break;
1376
1377         case LFUN_NEWLINE_INSERT:
1378                 // some magic for the common case
1379                 if (type_ == hullSimple || type_ == hullEquation) {
1380                         cur.recordUndoInset();
1381                         bool const align =
1382                                 cur.bv().buffer().params().use_package("amsmath") == BufferParams::package_on;
1383                         mutate(align ? hullAlign : hullEqnArray);
1384                         // mutate() may change labels and such.
1385                         cur.forceBufferUpdate();
1386                         cur.idx() = nrows() * ncols() - 1;
1387                         cur.pos() = cur.lastpos();
1388                 }
1389                 InsetMathGrid::doDispatch(cur, cmd);
1390                 break;
1391
1392         case LFUN_MATH_NUMBER_TOGGLE: {
1393                 //lyxerr << "toggling all numbers" << endl;
1394                 cur.recordUndoInset();
1395                 bool old = numberedType();
1396                 if (type_ == hullMultline)
1397                         numbered(nrows() - 1, !old);
1398                 else
1399                         for (row_type row = 0; row < nrows(); ++row)
1400                                 numbered(row, !old);
1401
1402                 cur.message(old ? _("No number") : _("Number"));
1403                 cur.forceBufferUpdate();
1404                 break;
1405         }
1406
1407         case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1408                 cur.recordUndoInset();
1409                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1410                 bool old = numbered(r);
1411                 cur.message(old ? _("No number") : _("Number"));
1412                 numbered(r, !old);
1413                 cur.forceBufferUpdate();
1414                 break;
1415         }
1416
1417         case LFUN_LABEL_INSERT: {
1418                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1419                 docstring old_label = label(r);
1420                 docstring const default_label = from_ascii("eq:");
1421                 if (old_label.empty())
1422                         old_label = default_label;
1423
1424                 InsetCommandParams p(LABEL_CODE);
1425                 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1426                 string const data = InsetCommand::params2string(p);
1427
1428                 if (cmd.argument().empty())
1429                         cur.bv().showDialog("label", data);
1430                 else {
1431                         FuncRequest fr(LFUN_INSET_INSERT, data);
1432                         dispatch(cur, fr);
1433                 }
1434                 break;
1435         }
1436
1437         case LFUN_LABEL_COPY_AS_REF: {
1438                 row_type row;
1439                 if (cmd.argument().empty() && &cur.inset() == this)
1440                         // if there is no argument and we're inside math, we retrieve
1441                         // the row number from the cursor position.
1442                         row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1443                 else {
1444                         // if there is an argument, find the corresponding label, else
1445                         // check whether there is at least one label.
1446                         for (row = 0; row != nrows(); ++row)
1447                                 if (numbered_[row] && label_[row]
1448                                           && (cmd.argument().empty() || label(row) == cmd.argument()))
1449                                         break;
1450                 }
1451
1452                 if (row == nrows())
1453                         break;
1454
1455                 InsetCommandParams p(REF_CODE, "ref");
1456                 p["reference"] = label(row);
1457                 cap::clearSelection();
1458                 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1459                 break;
1460         }
1461
1462         case LFUN_WORD_DELETE_FORWARD:
1463         case LFUN_CHAR_DELETE_FORWARD:
1464                 if (col(cur.idx()) + 1 == ncols()
1465                     && cur.pos() == cur.lastpos()
1466                     && !cur.selection()) {
1467                         if (!label(row(cur.idx())).empty()) {
1468                                 cur.recordUndoInset();
1469                                 label(row(cur.idx()), docstring());
1470                         } else if (numbered(row(cur.idx()))) {
1471                                 cur.recordUndoInset();
1472                                 numbered(row(cur.idx()), false);
1473                                 cur.forceBufferUpdate();
1474                         } else {
1475                                 InsetMathGrid::doDispatch(cur, cmd);
1476                                 return;
1477                         }
1478                 } else {
1479                         InsetMathGrid::doDispatch(cur, cmd);
1480                         return;
1481                 }
1482                 break;
1483
1484         case LFUN_INSET_INSERT: {
1485                 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1486                 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1487                 string const name = cmd.getArg(0);
1488                 if (name == "label") {
1489                         InsetCommandParams p(LABEL_CODE);
1490                         InsetCommand::string2params(to_utf8(cmd.argument()), p);
1491                         docstring str = p["name"];
1492                         cur.recordUndoInset();
1493                         row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1494                         str = trim(str);
1495                         if (!str.empty())
1496                                 numbered(r, true);
1497                         docstring old = label(r);
1498                         if (str != old) {
1499                                 if (label_[r])
1500                                         // The label will take care of the reference update.
1501                                         label(r, str);
1502                                 else {
1503                                         label(r, str);
1504                                         // Newly created inset so initialize it.
1505                                         label_[r]->initView();
1506                                 }
1507                         }
1508                         cur.forceBufferUpdate();
1509                         break;
1510                 }
1511                 InsetMathGrid::doDispatch(cur, cmd);
1512                 return;
1513         }
1514
1515         case LFUN_MATH_EXTERN:
1516                 cur.recordUndoInset();
1517                 doExtern(cur, cmd);
1518                 break;
1519
1520         case LFUN_MATH_MUTATE: {
1521                 cur.recordUndoInset();
1522                 row_type row = cur.row();
1523                 col_type col = cur.col();
1524                 mutate(hullType(cmd.argument()));
1525                 cur.idx() = row * ncols() + col;
1526                 if (cur.idx() > cur.lastidx()) {
1527                         cur.idx() = cur.lastidx();
1528                         cur.pos() = cur.lastpos();
1529                 }
1530                 if (cur.pos() > cur.lastpos())
1531                         cur.pos() = cur.lastpos();
1532
1533                 cur.forceBufferUpdate();
1534                 // FIXME: find some more clever handling of the selection,
1535                 // i.e. preserve it.
1536                 cur.clearSelection();
1537                 //cur.dispatched(FINISHED);
1538                 break;
1539         }
1540
1541         case LFUN_MATH_DISPLAY: {
1542                 cur.recordUndoInset();
1543                 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1544                 cur.idx() = 0;
1545                 cur.pos() = cur.lastpos();
1546                 //cur.dispatched(FINISHED);
1547                 break;
1548         }
1549
1550         default:
1551                 InsetMathGrid::doDispatch(cur, cmd);
1552                 break;
1553         }
1554 }
1555
1556
1557 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1558                 FuncStatus & status) const
1559 {
1560         switch (cmd.action()) {
1561         case LFUN_FINISHED_BACKWARD:
1562         case LFUN_FINISHED_FORWARD:
1563         case LFUN_FINISHED_RIGHT:
1564         case LFUN_FINISHED_LEFT:
1565         case LFUN_UP:
1566         case LFUN_DOWN:
1567         case LFUN_NEWLINE_INSERT:
1568         case LFUN_MATH_EXTERN:
1569                 // we handle these
1570                 status.setEnabled(true);
1571                 return true;
1572
1573         // we never allow this in math, and we want to bind enter
1574         // to another actions in command-alternatives
1575         case LFUN_PARAGRAPH_BREAK:
1576                 status.setEnabled(false);
1577                 return true;
1578         case LFUN_MATH_MUTATE: {
1579                 HullType const ht = hullType(cmd.argument());
1580                 status.setOnOff(type_ == ht);
1581                 status.setEnabled(true);
1582
1583                 if (ht != hullSimple) {
1584                         Cursor tmpcur = cur;
1585                         while (!tmpcur.empty()) {
1586                                 InsetCode code = tmpcur.inset().lyxCode();
1587                                 if (code == BOX_CODE) {
1588                                         return true;
1589                                 } else if (code == TABULAR_CODE) {
1590                                         FuncRequest tmpcmd(LFUN_MATH_DISPLAY);
1591                                         if (tmpcur.getStatus(tmpcmd, status) && !status.enabled())
1592                                                 return true;
1593                                 }
1594                                 tmpcur.pop_back();
1595                         }
1596                 }
1597                 return true;
1598         }
1599         case LFUN_MATH_DISPLAY: {
1600                 bool enable = true;
1601                 if (cur.depth() > 1) {
1602                         Inset const & in = cur[cur.depth()-2].inset();
1603                         if (in.lyxCode() == SCRIPT_CODE)
1604                                 enable = display() != Inline;
1605                 }
1606                 status.setEnabled(enable);
1607                 return true;
1608         }
1609
1610         case LFUN_MATH_NUMBER_TOGGLE:
1611                 // FIXME: what is the right test, this or the one of
1612                 // LABEL_INSERT?
1613                 status.setEnabled(display() != Inline);
1614                 status.setOnOff(numberedType());
1615                 return true;
1616
1617         case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1618                 // FIXME: what is the right test, this or the one of
1619                 // LABEL_INSERT?
1620                 bool const enable = (type_ == hullMultline)
1621                         ? (nrows() - 1 == cur.row())
1622                         : display() != Inline;
1623                 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1624                 status.setEnabled(enable);
1625                 status.setOnOff(enable && numbered(r));
1626                 return true;
1627         }
1628
1629         case LFUN_LABEL_INSERT:
1630                 status.setEnabled(type_ != hullSimple);
1631                 return true;
1632
1633         case LFUN_LABEL_COPY_AS_REF: {
1634                 bool enabled = false;
1635                 row_type row;
1636                 if (cmd.argument().empty() && &cur.inset() == this) {
1637                         // if there is no argument and we're inside math, we retrieve
1638                         // the row number from the cursor position.
1639                         row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1640                         enabled = numberedType() && label_[row] && numbered_[row];
1641                 } else {
1642                         // if there is an argument, find the corresponding label, else
1643                         // check whether there is at least one label.
1644                         for (row_type row = 0; row != nrows(); ++row) {
1645                                 if (numbered_[row] && label_[row] && 
1646                                         (cmd.argument().empty() || label(row) == cmd.argument())) {
1647                                                 enabled = true;
1648                                                 break;
1649                                 }
1650                         }
1651                 }
1652                 status.setEnabled(enabled);
1653                 return true;
1654         }
1655
1656         case LFUN_INSET_INSERT:
1657                 if (cmd.getArg(0) == "label") {
1658                         status.setEnabled(type_ != hullSimple);
1659                         return true;
1660                 }
1661                 return InsetMathGrid::getStatus(cur, cmd, status);
1662
1663         case LFUN_INSET_MODIFY: {
1664                 istringstream is(to_utf8(cmd.argument()));
1665                 string s;
1666                 is >> s;
1667                 if (s != "tabular")
1668                         return InsetMathGrid::getStatus(cur, cmd, status);
1669                 is >> s;
1670                 if (!rowChangeOK()
1671                     && (s == "append-row"
1672                         || s == "delete-row"
1673                         || s == "copy-row")) {
1674                         status.message(bformat(
1675                                 from_utf8(N_("Can't change number of rows in '%1$s'")),
1676                                 hullName(type_)));
1677                         status.setEnabled(false);
1678                         return true;
1679                 }
1680                 if (!colChangeOK()
1681                     && (s == "append-column"
1682                         || s == "delete-column"
1683                         || s == "copy-column")) {
1684                         status.message(bformat(
1685                                 from_utf8(N_("Can't change number of columns in '%1$s'")),
1686                                 hullName(type_)));
1687                         status.setEnabled(false);
1688                         return true;
1689                 }
1690                 if ((type_ == hullSimple
1691                   || type_ == hullEquation
1692                   || type_ == hullNone) &&
1693                     (s == "add-hline-above" || s == "add-hline-below")) {
1694                         status.message(bformat(
1695                                 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1696                                 hullName(type_)));
1697                         status.setEnabled(false);
1698                         return true;
1699                 }
1700                 if (s == "add-vline-left" || s == "add-vline-right") {
1701                         status.message(bformat(
1702                                 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1703                                 hullName(type_)));
1704                         status.setEnabled(false);
1705                         return true;
1706                 }
1707                 if (s == "valign-top" || s == "valign-middle"
1708                  || s == "valign-bottom" || s == "align-left"
1709                  || s == "align-center" || s == "align-right") {
1710                         status.setEnabled(false);
1711                         return true;
1712                 }
1713                 return InsetMathGrid::getStatus(cur, cmd, status);
1714         }
1715
1716         default:
1717                 return InsetMathGrid::getStatus(cur, cmd, status);
1718         }
1719
1720         // This cannot really happen, but inserted to shut-up gcc
1721         return InsetMathGrid::getStatus(cur, cmd, status);
1722 }
1723
1724
1725 /////////////////////////////////////////////////////////////////////
1726
1727
1728
1729 // simply scrap this function if you want
1730 void InsetMathHull::mutateToText()
1731 {
1732 #if 0
1733         // translate to latex
1734         ostringstream os;
1735         latex(os, false, false);
1736         string str = os.str();
1737
1738         // insert this text
1739         Text * lt = view_->cursor().innerText();
1740         string::const_iterator cit = str.begin();
1741         string::const_iterator end = str.end();
1742         for (; cit != end; ++cit)
1743                 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1744
1745         // remove ourselves
1746         //dispatch(LFUN_ESCAPE);
1747 #endif
1748 }
1749
1750
1751 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1752         docstring const & font)
1753 {
1754         // this whole function is a hack and won't work for incremental font
1755         // changes...
1756         cur.recordUndo();
1757         if (cur.inset().asInsetMath()->name() == font)
1758                 cur.handleFont(to_utf8(font));
1759         else {
1760                 cur.handleNest(createInsetMath(font, cur.buffer()));
1761                 cur.insert(arg);
1762         }
1763 }
1764
1765
1766 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1767 {
1768         cur.recordUndo();
1769         Font font;
1770         bool b;
1771         font.fromString(to_utf8(arg), b);
1772         if (font.fontInfo().color() != Color_inherit) {
1773                 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1774                 cur.handleNest(at, 0);
1775         }
1776 }
1777
1778
1779 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1780 {
1781         cur.push(*this);
1782         bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1783                 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1784         enter_front ? idxFirst(cur) : idxLast(cur);
1785         // The inset formula dimension is not necessarily the same as the
1786         // one of the instant preview image, so we have to indicate to the
1787         // BufferView that a metrics update is needed.
1788         cur.screenUpdateFlags(Update::Force);
1789 }
1790
1791
1792 void InsetMathHull::revealCodes(Cursor & cur) const
1793 {
1794         if (!cur.inMathed())
1795                 return;
1796         odocstringstream os;
1797         cur.info(os);
1798         cur.message(os.str());
1799 /*
1800         // write something to the minibuffer
1801         // translate to latex
1802         cur.markInsert(bv);
1803         ostringstream os;
1804         write(os);
1805         string str = os.str();
1806         cur.markErase(bv);
1807         string::size_type pos = 0;
1808         string res;
1809         for (string::iterator it = str.begin(); it != str.end(); ++it) {
1810                 if (*it == '\n')
1811                         res += ' ';
1812                 else if (*it == '\0') {
1813                         res += "  -X-  ";
1814                         pos = it - str.begin();
1815                 }
1816                 else
1817                         res += *it;
1818         }
1819         if (pos > 30)
1820                 res = res.substr(pos - 30);
1821         if (res.size() > 60)
1822                 res = res.substr(0, 60);
1823         cur.message(res);
1824 */
1825 }
1826
1827
1828 /////////////////////////////////////////////////////////////////////
1829
1830
1831 #if 0
1832 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1833                                      bool, bool)
1834 {
1835         // FIXME: completely broken
1836         static InsetMathHull * lastformula = 0;
1837         static CursorBase current = DocIterator(ibegin(nucleus()));
1838         static MathData ar;
1839         static string laststr;
1840
1841         if (lastformula != this || laststr != str) {
1842                 //lyxerr << "reset lastformula to " << this << endl;
1843                 lastformula = this;
1844                 laststr = str;
1845                 current = ibegin(nucleus());
1846                 ar.clear();
1847                 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1848         } else {
1849                 increment(current);
1850         }
1851         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1852
1853         for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1854                 CursorSlice & top = it.back();
1855                 MathData const & a = top.asInsetMath()->cell(top.idx_);
1856                 if (a.matchpart(ar, top.pos_)) {
1857                         bv->cursor().setSelection(it, ar.size());
1858                         current = it;
1859                         top.pos_ += ar.size();
1860                         bv->update();
1861                         return true;
1862                 }
1863         }
1864
1865         //lyxerr << "not found!" << endl;
1866         lastformula = 0;
1867         return false;
1868 }
1869 #endif
1870
1871
1872 void InsetMathHull::write(ostream & os) const
1873 {
1874         odocstringstream oss;
1875         WriteStream wi(oss, false, false, WriteStream::wsDefault);
1876         oss << "Formula ";
1877         write(wi);
1878         os << to_utf8(oss.str());
1879 }
1880
1881
1882 void InsetMathHull::read(Lexer & lex)
1883 {
1884         MathAtom at;
1885         mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1886         operator=(*at->asHullInset());
1887 }
1888
1889
1890 bool InsetMathHull::readQuiet(Lexer & lex)
1891 {
1892         MathAtom at;
1893         bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1894         if (success)
1895                 operator=(*at->asHullInset());
1896         return success;
1897 }
1898
1899
1900 int InsetMathHull::plaintext(odocstringstream & os,
1901         OutputParams const & op, size_t max_length) const
1902 {
1903         // disables ASCII-art for export of equations. See #2275.
1904         if (0 && display()) {
1905                 Dimension dim;
1906                 TextMetricsInfo mi;
1907                 metricsT(mi, dim);
1908                 TextPainter tpain(dim.width(), dim.height());
1909                 drawT(tpain, 0, dim.ascent());
1910                 tpain.show(os, 3);
1911                 // reset metrics cache to "real" values
1912                 //metrics();
1913                 return tpain.textheight();
1914         }
1915
1916         odocstringstream oss;
1917         Encoding const * const enc = encodings.fromLyXName("utf8");
1918         WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1919
1920         // Fix Bug #6139
1921         if (type_ == hullRegexp)
1922                 write(wi);
1923         else {
1924                 for (row_type r = 0; r < nrows(); ++r) {
1925                         for (col_type c = 0; c < ncols(); ++c)
1926                                 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
1927                         // if it's for the TOC, we write just the first line
1928                         // and do not include the newline.
1929                         if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
1930                                 break;
1931                         wi << "\n";
1932                 }
1933         }
1934         docstring const str = oss.str();
1935         os << str;
1936         return str.size();
1937 }
1938
1939
1940 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1941 {
1942         MathStream ms(os);
1943         int res = 0;
1944         docstring name;
1945         if (getType() == hullSimple)
1946                 name = from_ascii("inlineequation");
1947         else
1948                 name = from_ascii("informalequation");
1949
1950         docstring bname = name;
1951         if (!label(0).empty())
1952                 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1953
1954         ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1955
1956         odocstringstream ls;
1957         if (runparams.flavor == OutputParams::XML) {
1958                 ms << MTag("alt role='tex' ");
1959                 // Workaround for db2latex: db2latex always includes equations with
1960                 // \ensuremath{} or \begin{display}\end{display}
1961                 // so we strip LyX' math environment
1962                 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1963                 InsetMathGrid::write(wi);
1964                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
1965                 ms << ETag("alt");
1966                 ms << MTag("math");
1967                 ms << ETag("alt");
1968                 ms << MTag("math");
1969                 InsetMathGrid::mathmlize(ms);
1970                 ms << ETag("math");
1971         } else {
1972                 TexRow texrow;
1973                 texrow.reset();
1974                 otexstream ols(ls, texrow);
1975                 ms << MTag("alt role='tex'");
1976                 latex(ols, runparams);
1977                 res = texrow.rows();
1978                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
1979                 ms << ETag("alt");
1980         }
1981
1982         ms << from_ascii("<graphic fileref=\"eqn/");
1983         if (!label(0).empty())
1984                 ms << sgml::cleanID(buffer(), runparams, label(0));
1985         else
1986                 ms << sgml::uniqueID(from_ascii("anon"));
1987
1988         if (runparams.flavor == OutputParams::XML)
1989                 ms << from_ascii("\"/>");
1990         else
1991                 ms << from_ascii("\">");
1992
1993         ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1994
1995         return ms.line() + res;
1996 }
1997
1998
1999 bool InsetMathHull::haveNumbers() const
2000 {
2001         bool havenumbers = false;
2002         // inline formulas are never numbered (bug 7351 part 3)
2003         if (getType() == hullSimple)
2004                 return havenumbers;
2005         for (size_t i = 0; i != numbered_.size(); ++i) {
2006                 if (numbered_[i]) {
2007                         havenumbers = true;
2008                         break;
2009                 }
2010         }
2011         return havenumbers;
2012 }
2013
2014
2015 // FIXME XHTML
2016 // We need to do something about alignment here.
2017 //
2018 // This duplicates code from InsetMathGrid, but
2019 // we need access here to number information,
2020 // and we simply do not have that in InsetMathGrid.
2021 void InsetMathHull::htmlize(HtmlStream & os) const
2022 {
2023         bool const havenumbers = haveNumbers();
2024         bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2025
2026         if (!havetable) {
2027                 os << cell(index(0, 0));
2028                 return;
2029         }
2030
2031         os << MTag("table", "class='mathtable'");
2032         for (row_type row = 0; row < nrows(); ++row) {
2033                 os << MTag("tr");
2034                 for (col_type col = 0; col < ncols(); ++col) {
2035                         os << MTag("td");
2036                         os << cell(index(row, col));
2037                         os << ETag("td");
2038                 }
2039                 if (havenumbers) {
2040                         os << MTag("td");
2041                         docstring const & num = numbers_[row];
2042                         if (!num.empty())
2043                                 os << '(' << num << ')';
2044                   os << ETag("td");
2045                 }
2046                 os << ETag("tr");
2047         }
2048         os << ETag("table");
2049 }
2050
2051
2052 // this duplicates code from InsetMathGrid, but
2053 // we need access here to number information,
2054 // and we simply do not have that in InsetMathGrid.
2055 void InsetMathHull::mathmlize(MathStream & os) const
2056 {
2057         bool const havenumbers = haveNumbers();
2058         bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2059
2060         if (havetable)
2061                 os << MTag("mtable");
2062         char const * const celltag = havetable ? "mtd" : "mrow";
2063         // FIXME There does not seem to be wide support at the moment
2064         // for mlabeledtr, so we have to use just mtr for now.
2065         // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2066         char const * const rowtag = "mtr";
2067         for (row_type row = 0; row < nrows(); ++row) {
2068                 if (havetable)
2069                         os << MTag(rowtag);
2070                 for (col_type col = 0; col < ncols(); ++col) {
2071                         os << MTag(celltag)
2072                            << cell(index(row, col))
2073                            << ETag(celltag);
2074                 }
2075                 // fleqn?
2076                 if (havenumbers) {
2077                         os << MTag("mtd");
2078                         docstring const & num = numbers_[row];
2079                         if (!num.empty())
2080                                 os << '(' << num << ')';
2081                   os << ETag("mtd");
2082                 }
2083                 if (havetable)
2084                         os << ETag(rowtag);
2085         }
2086         if (havetable)
2087                 os << ETag("mtable");
2088 }
2089
2090
2091 void InsetMathHull::mathAsLatex(WriteStream & os) const
2092 {
2093         MathEnsurer ensurer(os, false);
2094         bool havenumbers = haveNumbers();
2095         bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2096
2097         if (!havetable) {
2098                 os << cell(index(0, 0));
2099                 return;
2100         }
2101
2102         os << "<table class='mathtable'>";
2103         for (row_type row = 0; row < nrows(); ++row) {
2104                 os << "<tr>";
2105                 for (col_type col = 0; col < ncols(); ++col) {
2106                         os << "<td class='math'>";
2107                         os << cell(index(row, col));
2108                         os << "</td>";
2109                 }
2110                 if (havenumbers) {
2111                         os << "<td>";
2112                         docstring const & num = numbers_[row];
2113                         if (!num.empty())
2114                                 os << '(' << num << ')';
2115                   os << "</td>";
2116                 }
2117                 os << "</tr>";
2118         }
2119         os << "</table>";
2120 }
2121
2122
2123 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2124 {
2125         BufferParams::MathOutput const mathtype = 
2126                 buffer().masterBuffer()->params().html_math_output;
2127
2128         bool success = false;
2129
2130         // we output all the labels just at the beginning of the equation.
2131         // this should be fine.
2132         for (size_t i = 0; i != label_.size(); ++i) {
2133                 InsetLabel const * const il = label_[i];
2134                 if (!il)
2135                         continue;
2136                 il->xhtml(xs, op);
2137         }
2138
2139         // FIXME Eventually we would like to do this inset by inset.
2140         if (mathtype == BufferParams::MathML) {
2141                 odocstringstream os;
2142                 MathStream ms(os);
2143                 try {
2144                         mathmlize(ms);
2145                         success = true;
2146                 } catch (MathExportException const &) {}
2147                 if (success) {
2148                         if (getType() == hullSimple)
2149                                 xs << html::StartTag("math", 
2150                                                         "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2151                         else 
2152                                 xs << html::StartTag("math", 
2153                                       "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2154                         xs << XHTMLStream::ESCAPE_NONE
2155                                  << os.str()
2156                                  << html::EndTag("math");
2157                 }
2158         } else if (mathtype == BufferParams::HTML) {
2159                 odocstringstream os;
2160                 HtmlStream ms(os);
2161                 try {
2162                         htmlize(ms);
2163                         success = true;
2164                 } catch (MathExportException const &) {}
2165                 if (success) {
2166                         string const tag = (getType() == hullSimple) ? "span" : "div";
2167                         xs << html::StartTag(tag, "class='formula'", true)
2168                            << XHTMLStream::ESCAPE_NONE
2169                            << os.str()
2170                            << html::EndTag(tag);
2171                 }
2172         }
2173         
2174         // what we actually want is this:
2175         // if (
2176         //     ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML) 
2177         //       && !success)
2178         //     || mathtype == BufferParams::Images
2179         //    )
2180         // but what follows is equivalent, since we'll enter only if either (a) we 
2181         // tried and failed with MathML or HTML or (b) didn't try yet at all but
2182         // aren't doing LaTeX, in which case we are doing Images.
2183         if (!success && mathtype != BufferParams::LaTeX) {
2184                 graphics::PreviewImage const * pimage = 0;
2185                 if (!op.dryrun) {
2186                         loadPreview(docit_);
2187                         pimage = preview_->getPreviewImage(buffer());
2188                         // FIXME Do we always have png?
2189                 }
2190
2191                 if (pimage || op.dryrun) {
2192                         string const filename = pimage ? pimage->filename().onlyFileName()
2193                                                        : "previewimage.png";
2194                         if (pimage) {
2195                                 // if we are not in the master buffer, then we need to see that the
2196                                 // generated image is copied there; otherwise, preview fails.
2197                                 Buffer const * mbuf = buffer().masterBuffer();
2198                                 if (mbuf != &buffer()) {
2199                                         string mbtmp = mbuf->temppath();
2200                                         FileName const mbufimg(support::addName(mbtmp, filename));
2201                                         pimage->filename().copyTo(mbufimg);
2202                                 }
2203                                 // add the file to the list of files to be exported
2204                                 op.exportdata->addExternalFile("xhtml", pimage->filename());
2205                         }
2206
2207                         string const tag = (getType() == hullSimple) ? "span" : "div";
2208                         xs << html::CR()
2209                            << html::StartTag(tag)
2210                                  << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2211                                  << html::EndTag(tag)
2212                                  << html::CR();
2213                         success = true;
2214                 }
2215         }
2216         
2217         // so we'll pass this test if we've failed everything else, or
2218         // if mathtype was LaTeX, since we won't have entered any of the
2219         // earlier branches
2220         if (!success /* || mathtype != BufferParams::LaTeX */) {
2221                 // Unfortunately, we cannot use latexString() because we do not want
2222                 // $...$ or whatever.
2223                 odocstringstream ls;
2224                 WriteStream wi(ls, false, true, WriteStream::wsPreview);
2225                 ModeSpecifier specifier(wi, MATH_MODE);
2226                 mathAsLatex(wi);
2227                 docstring const latex = ls.str();
2228                 
2229                 // class='math' allows for use of jsMath
2230                 // http://www.math.union.edu/~dpvc/jsMath/
2231                 // FIXME XHTML
2232                 // probably should allow for some kind of customization here
2233                 string const tag = (getType() == hullSimple) ? "span" : "div";
2234                 xs << html::StartTag(tag, "class='math'")
2235                    << latex 
2236                    << html::EndTag(tag)
2237                    << html::CR();
2238         }
2239         return docstring();
2240 }
2241
2242
2243 void InsetMathHull::toString(odocstream & os) const
2244 {
2245         odocstringstream ods;
2246         plaintext(ods, OutputParams(0));
2247         os << ods.str();
2248 }
2249
2250
2251 void InsetMathHull::forToc(docstring & os, size_t) const
2252 {
2253         odocstringstream ods;
2254         OutputParams op(0);
2255         op.for_toc = true;
2256         plaintext(ods, op);
2257         os += ods.str();
2258 }
2259
2260
2261 string InsetMathHull::contextMenuName() const
2262 {
2263         return "context-math";
2264 }
2265
2266
2267 void InsetMathHull::recordLocation(DocIterator const & di)
2268 {
2269         docit_ = di;
2270 }
2271
2272 } // namespace lyx