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