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