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