]> git.lyx.org Git - lyx.git/blobdiff - src/mathed/InsetMathHull.cpp
Make undo action no-ops when the buffer is read-only
[lyx.git] / src / mathed / InsetMathHull.cpp
index 53a16e8d0f7b6d41a6f2746460b38ab92d4275b4..8fd2bdd24a3ac49cd7ba6236efd634ee3ed342ce 100644 (file)
 #include <config.h>
 
 #include "InsetMathHull.h"
-
 #include "InsetMathChar.h"
 #include "InsetMathColor.h"
+#include "InsetMathFrac.h"
+#include "InsetMathNest.h"
+#include "InsetMathScript.h"
 #include "MathExtern.h"
 #include "MathFactory.h"
 #include "MathStream.h"
@@ -23,6 +25,7 @@
 #include "BufferParams.h"
 #include "BufferView.h"
 #include "ColorSet.h"
+#include "Cursor.h"
 #include "CutAndPaste.h"
 #include "Encoding.h"
 #include "Exporter.h"
 #include "LaTeXFeatures.h"
 #include "LyXRC.h"
 #include "MacroTable.h"
-#include "output_xhtml.h"
+#include "InsetMathMacro.h"
+#include "InsetMathMacroTemplate.h"
+#include "MetricsInfo.h"
 #include "Paragraph.h"
 #include "ParIterator.h"
-#include "sgml.h"
+#include "xml.h"
+#include "TexRow.h"
 #include "TextClass.h"
 #include "TextPainter.h"
 #include "TocBackend.h"
 #include "insets/InsetRef.h"
 #include "insets/RenderPreview.h"
 
-#include "graphics/GraphicsImage.h"
 #include "graphics/PreviewImage.h"
 #include "graphics/PreviewLoader.h"
 
 #include "frontends/alert.h"
+#include "frontends/FontMetrics.h"
 #include "frontends/Painter.h"
 
 #include "support/convert.h"
-#include "support/lassert.h"
 #include "support/debug.h"
-#include "support/filetools.h"
 #include "support/gettext.h"
+#include "support/filetools.h"
+#include "support/lassert.h"
 #include "support/lstrings.h"
+#include "support/Changer.h"
 
 #include <sstream>
 
@@ -73,17 +80,25 @@ namespace {
        int getCols(HullType type)
        {
                switch (type) {
-                       case hullEqnArray:
-                               return 3;
-                       case hullAlign:
-                       case hullFlAlign:
-                       case hullAlignAt:
-                       case hullXAlignAt:
-                       case hullXXAlignAt:
-                               return 2;
-                       default:
-                               return 1;
+               case hullEqnArray:
+                       return 3;
+               case hullAlign:
+               case hullFlAlign:
+               case hullAlignAt:
+               case hullXAlignAt:
+               case hullXXAlignAt:
+                       return 2;
+               case hullUnknown:
+               case hullNone:
+               case hullSimple:
+               case hullEquation:
+               case hullMultline:
+               case hullGather:
+               case hullRegexp:
+                       return 1;
                }
+               // avoid warning
+               return 0;
        }
 
 
@@ -92,7 +107,7 @@ namespace {
        size_t firstRelOp(MathData const & ar)
        {
                for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
-                       if ((*it)->isRelOp())
+                       if ((*it)->mathClass() == MC_REL)
                                return it - ar.begin();
                return ar.size();
        }
@@ -104,55 +119,41 @@ namespace {
        }
 
 
-} // end anon namespace
+       // writes a preamble for underlined or struck out math display
+       void writeMathdisplayPreamble(TeXMathStream & os)
+       {
+               if (os.strikeoutMath())
+                       return;
 
+               if (os.ulemCmd() == TeXMathStream::UNDERLINE)
+                       os << "\\raisebox{-\\belowdisplayshortskip}{"
+                             "\\parbox[b]{\\linewidth}{";
+               else if (os.ulemCmd() == TeXMathStream::STRIKEOUT)
+                       os << "\\parbox{\\linewidth}{";
+       }
 
-HullType hullType(docstring const & s)
-{
-       if (s == "none")      return hullNone;
-       if (s == "simple")    return hullSimple;
-       if (s == "equation")  return hullEquation;
-       if (s == "eqnarray")  return hullEqnArray;
-       if (s == "align")     return hullAlign;
-       if (s == "alignat")   return hullAlignAt;
-       if (s == "xalignat")  return hullXAlignAt;
-       if (s == "xxalignat") return hullXXAlignAt;
-       if (s == "multline")  return hullMultline;
-       if (s == "gather")    return hullGather;
-       if (s == "flalign")   return hullFlAlign;
-       if (s == "regexp")    return hullRegexp;
-       lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
-       return HullType(-1);
-}
 
+       // writes a postamble for underlined or struck out math display
+       void writeMathdisplayPostamble(TeXMathStream & os)
+       {
+               if (os.strikeoutMath())
+                       return;
 
-docstring hullName(HullType type)
-{
-       switch (type) {
-               case hullNone:       return from_ascii("none");
-               case hullSimple:     return from_ascii("simple");
-               case hullEquation:   return from_ascii("equation");
-               case hullEqnArray:   return from_ascii("eqnarray");
-               case hullAlign:      return from_ascii("align");
-               case hullAlignAt:    return from_ascii("alignat");
-               case hullXAlignAt:   return from_ascii("xalignat");
-               case hullXXAlignAt:  return from_ascii("xxalignat");
-               case hullMultline:   return from_ascii("multline");
-               case hullGather:     return from_ascii("gather");
-               case hullFlAlign:    return from_ascii("flalign");
-               case hullRegexp:     return from_ascii("regexp");
-               default:
-                       lyxerr << "unknown hull type '" << type << "'" << endl;
-                       return from_ascii("none");
+               if (os.ulemCmd() == TeXMathStream::UNDERLINE)
+                       os << "}}\\\\\n";
+               else if (os.ulemCmd() == TeXMathStream::STRIKEOUT)
+                       os << "}\\\\\n";
        }
-}
+
+} // namespace
+
 
 static InsetLabel * dummy_pointer = 0;
 
 InsetMathHull::InsetMathHull(Buffer * buf)
-       : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, NUMBER),
-    numbers_(1, empty_docstring()), label_(1, dummy_pointer),
-    preview_(new RenderPreview(this)), use_preview_(false)
+       : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, NONUMBER),
+         numbers_(1, empty_docstring()), label_(1, dummy_pointer),
+         preview_(new RenderPreview(this))
 {
        //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
        //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
@@ -165,9 +166,9 @@ InsetMathHull::InsetMathHull(Buffer * buf)
 
 
 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
-       : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, NUMBER),
-    numbers_(1, empty_docstring()), label_(1, dummy_pointer),
-    preview_(new RenderPreview(this)), use_preview_(false)
+       : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, NONUMBER),
+         numbers_(1, empty_docstring()), label_(1, dummy_pointer),
+         preview_(new RenderPreview(this))
 {
        buffer_ = buf;
        initMath();
@@ -183,8 +184,8 @@ InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
 
 InsetMathHull::~InsetMathHull()
 {
-       for (size_t i = 0; i < label_.size(); ++i)
-               delete label_[i];
+       for (auto & i : label_)
+               delete i;
 }
 
 
@@ -203,8 +204,8 @@ InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
        numbered_ = other.numbered_;
        numbers_ = other.numbers_;
        buffer_ = other.buffer_;
-       for (size_t i = 0; i < label_.size(); ++i)
-               delete label_[i];
+       for (auto & i : label_)
+               delete i;
        label_ = other.label_;
        for (size_t i = 0; i != label_.size(); ++i) {
                if (label_[i])
@@ -232,10 +233,10 @@ void InsetMathHull::setBuffer(Buffer & buffer)
 namespace {
        const char * counters_to_save[] = {"section", "chapter"};
        unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
-}
+} // namespace
 
 
-void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
+void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
 {
        if (!buffer_) {
                //FIXME: buffer_ should be set at creation for this inset! Problem is
@@ -268,8 +269,12 @@ void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
                                counter_map[eqstr] = cnts.value(eqstr);
                        for (size_t i = 0; i != label_.size(); ++i) {
                                if (numbered(i)) {
-                                       cnts.step(eqstr, utype);
-                                       numbers_[i] = cnts.theCounter(eqstr, lang);
+                                       Paragraph const & par = it.paragraph();
+                                       if (!par.isDeleted(it.pos())) {
+                                               cnts.step(eqstr, utype);
+                                               numbers_[i] = cnts.theCounter(eqstr, lang);
+                                       } else
+                                               numbers_[i] = from_ascii("#");
                                } else
                                        numbers_[i] = empty_docstring();
                        }
@@ -279,14 +284,15 @@ void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
        // now the labels
        for (size_t i = 0; i != label_.size(); ++i) {
                if (label_[i])
-                       label_[i]->updateBuffer(it, utype);
+                       label_[i]->updateBuffer(it, utype, deleted);
        }
        // pass down
-       InsetMathGrid::updateBuffer(it, utype);
+       InsetMathGrid::updateBuffer(it, utype, deleted);
 }
 
 
-void InsetMathHull::addToToc(DocIterator const & pit, bool output_active) const
+void InsetMathHull::addToToc(DocIterator const & pit, bool output_active,
+                                                        UpdateType utype, TocBackend & backend) const
 {
        if (!buffer_) {
                //FIXME: buffer_ should be set at creation for this inset! Problem is
@@ -295,21 +301,48 @@ void InsetMathHull::addToToc(DocIterator const & pit, bool output_active) const
                return;
        }
 
-       Toc & toc = buffer().tocBackend().toc("equation");
-
+       TocBuilder & b = backend.builder("equation");
+       // compute first and last item
+       row_type first = nrows();
+       for (row_type row = 0; row != nrows(); ++row)
+               if (numbered(row)) {
+                       first = row;
+                       break;
+               }
+       if (first == nrows())
+               // no equation
+               return;
+       row_type last = nrows() - 1;
+       for (; last != 0; --last)
+               if (numbered(last))
+                       break;
+       // add equation numbers
+       b.pushItem(pit, docstring(), output_active);
+       if (first != last)
+               b.argumentItem(bformat(from_ascii("(%1$s-%2$s)"),
+                                      numbers_[first], numbers_[last]));
        for (row_type row = 0; row != nrows(); ++row) {
                if (!numbered(row))
                        continue;
                if (label_[row])
-                       label_[row]->addToToc(pit, output_active);
-               toc.push_back(TocItem(pit, 0, nicelabel(row), output_active));
+                       label_[row]->addToToc(pit, output_active, utype, backend);
+               docstring label = nicelabel(row);
+               if (first == last)
+                       // this is the only equation
+                       b.argumentItem(label);
+               else {
+                       // insert as sub-items
+                       b.pushItem(pit, label, output_active);
+                       b.pop();
+               }
        }
+       b.pop();
 }
 
 
 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
 {
-       if (use_preview_) {
+       if (previewState(&cur.bv())) {
                edit(cur, true);
                return this;
        }
@@ -319,96 +352,103 @@ Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
 
 InsetMath::mode_type InsetMathHull::currentMode() const
 {
-       if (type_ == hullNone)
+       switch (type_) {
+       case hullNone:
                return UNDECIDED_MODE;
+
        // definitely math mode ...
+       case hullUnknown:
+       case hullSimple:
+       case hullEquation:
+       case hullMultline:
+       case hullGather:
+       case hullEqnArray:
+       case hullAlign:
+       case hullFlAlign:
+       case hullAlignAt:
+       case hullXAlignAt:
+       case hullXXAlignAt:
+       case hullRegexp:
+               return MATH_MODE;
+       }
+       // avoid warning
        return MATH_MODE;
 }
 
 
-bool InsetMathHull::idxFirst(Cursor & cur) const
-{
-       cur.idx() = 0;
-       cur.pos() = 0;
-       return true;
-}
-
-
-bool InsetMathHull::idxLast(Cursor & cur) const
+// FIXME: InsetMathGrid should be changed to let the real column alignment be
+// given by a virtual method like displayColAlign, because the values produced
+// by defaultColAlign can be invalidated by lfuns such as add-column. For the
+// moment the values produced by defaultColAlign are not used, notably because
+// alignment is not implemented in the LyXHTML output.
+char InsetMathHull::defaultColAlign(col_type col)
 {
-       cur.idx() = nargs() - 1;
-       cur.pos() = cur.lastpos();
-       return true;
+       return colAlign(type_, col);
 }
 
 
-char InsetMathHull::defaultColAlign(col_type col)
+char InsetMathHull::displayColAlign(idx_type idx) const
 {
-       if (type_ == hullEqnArray)
-               return "rcl"[col];
-       if (type_ == hullMultline)
-               return 'c';
-       if (type_ == hullGather)
+       switch (type_) {
+       case hullMultline: {
+               row_type const r = row(idx);
+               if (r == 0)
+                       return 'l';
+               if (r == nrows() - 1)
+                       return 'r';
                return 'c';
-       if (type_ >= hullAlign)
-               return "rl"[col & 1];
-       return 'c';
+       }
+       case hullEqnArray:
+       case hullGather:
+       case hullAlign:
+       case hullAlignAt:
+       case hullXAlignAt:
+       case hullXXAlignAt:
+       case hullFlAlign:
+               return colAlign(type_, col(idx));
+       default:
+               break;
+       }
+       return InsetMathGrid::displayColAlign(idx);
 }
 
 
-char InsetMathHull::displayColAlign(col_type col, row_type row) const
+int InsetMathHull::displayColSpace(col_type col) const
 {
-       if (type_ == hullMultline) {
-               if (row == 0)
-                       return 'l';
-               if (row == nrows() - 1)
-                       return 'r';
-       }
-       return InsetMathGrid::displayColAlign(col, row);
+       return colSpace(type_, col);
 }
 
 
+// FIXME: same comment as for defaultColAlign applies.
 int InsetMathHull::defaultColSpace(col_type col)
 {
-       if (type_ == hullAlign || type_ == hullAlignAt)
-               return 0;
-       if (type_ == hullXAlignAt)
-               return (col & 1) ? 20 : 0;
-       if (type_ == hullXXAlignAt || type_ == hullFlAlign)
-               return (col & 1) ? 40 : 0;
-       return 0;
+       return colSpace(type_, col);
 }
 
 
-docstring InsetMathHull::standardFont() const
+string InsetMathHull::standardFont() const
 {
-       docstring font_name;
        switch (type_) {
        case hullRegexp:
-               font_name = from_ascii("texttt");
-               break;
+               return "texttt";
        case hullNone:
-               font_name = from_ascii("lyxnochange");
-               break;
+               return "lyxnochange";
        default:
-               font_name = from_ascii("mathnormal");
+               return "mathnormal";
        }
-       return font_name;
 }
 
 
 ColorCode InsetMathHull::standardColor() const
 {
-       ColorCode color;
        switch (type_) {
        case hullRegexp:
        case hullNone:
-               color = Color_foreground;
-               break;
+               return Color_foreground;
+
        default:
-               color = Color_math;
+               return Color_math;
        }
-       return color;
 }
 
 
@@ -426,11 +466,27 @@ bool InsetMathHull::previewState(const BufferView *const bv) const
 
 
 namespace {
-static const int ERROR_FRAME_WIDTH = 2;
+const int ERROR_FRAME_WIDTH = 2;
+
+bool previewTooSmall(Dimension const & dim)
+{
+       return dim.width() <= 10 && dim.height() <= 10;
+}
 }
 
+
 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
 {
+       /* Compute \(above|below)displayskip
+          true value in LaTeX is 10pt plus 2pt minus 5pt (in normal size at 10pt)
+          But we use a fixed number of pixels and scale them with zoom.
+       */
+       int const bottom_display_margin = mi.base.bv->zoomedPixels(6);
+       int top_display_margin = bottom_display_margin;
+       // at start of paragraph, add an empty line
+       if (mi.vmode)
+               top_display_margin += theFontMetrics(mi.base.font).maxHeight() + 2;
+
        if (previewState(mi.base.bv)) {
                preview_->metrics(mi, dim);
                if (previewTooSmall(dim)) {
@@ -438,54 +494,58 @@ void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
                        dim.wid += 2 * ERROR_FRAME_WIDTH;
                        dim.asc += 2 * ERROR_FRAME_WIDTH;
                } else {
-                       // insert a one pixel gap in front of the formula
-                       dim.wid += 1;
-                       if (display())
-                               dim.des += displayMargin();
+                       // insert a gap in front of the formula
+                       // value was hardcoded to 1 pixel
+                       dim.wid += mi.base.bv->zoomedPixels(1) ;
+                       if (display()) {
+                               dim.asc += top_display_margin;
+                               dim.des += bottom_display_margin;
+                       }
                }
-               // Cache the inset dimension.
-               setDimCache(mi, dim);
                return;
        }
 
-       FontSetChanger dummy1(mi.base, standardFont());
-       StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
-
-       // let the cells adjust themselves
-       InsetMathGrid::metrics(mi, dim);
+       {
+               Changer dummy1 = mi.base.changeFontSet(standardFont());
+               Changer dummy2 = mi.base.font.changeStyle(display() ? DISPLAY_STYLE
+                                                                                                 : TEXT_STYLE);
 
-       if (display()) {
-               dim.asc += displayMargin();
-               dim.des += displayMargin();
+               // let the cells adjust themselves
+               InsetMathGrid::metrics(mi, dim);
        }
 
+       // Check whether the numbering interferes with the equations
        if (numberedType()) {
-               FontSetChanger dummy(mi.base, from_ascii("mathbf"));
-               int l = 0;
-               for (row_type row = 0; row < nrows(); ++row)
-                       l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
-
-               if (l)
-                       dim.wid += 30 + l;
+               BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
+               int extra_offset = 0;
+               for (row_type row = 0; row < nrows(); ++row) {
+                       rowinfo(row).offset[mi.base.bv] += extra_offset;
+                       if (!numbered(row))
+                               continue;
+                       docstring const nl = nicelabel(row);
+                       Dimension dimnl;
+                       mathed_string_dim(mi.base.font, nl, dimnl);
+                       int const ind = indent(*mi.base.bv);
+                       int const x = ind ? ind : (mi.base.textwidth - dim.wid) / 2;
+                       // for some reason metrics does not trigger at the
+                       // same point as draw, and therefore we use >= instead of >
+                       if ((math_number == BufferParams::LEFT && dimnl.wid >= x)
+                           || (math_number == BufferParams::RIGHT
+                               && dimnl.wid >= mi.base.textwidth - x - dim.wid)) {
+                               extra_offset += dimnl.height();
+                       }
+               }
+               dim.des += extra_offset;
        }
 
-       if (type_ == hullRegexp)
-               dim.wid += 2;
-       // make it at least as high as the current font
-       int asc = 0;
-       int des = 0;
-       math_font_max_dim(mi.base.font, asc, des);
-       dim.asc = max(dim.asc, asc);
-       dim.des = max(dim.des, des);
-       // Cache the inset dimension.
-       // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
-       setDimCache(mi, dim);
-}
 
+       if (display()) {
+               dim.asc += top_display_margin;
+               dim.des += bottom_display_margin;
+       }
 
-bool InsetMathHull::previewTooSmall(Dimension const & dim) const
-{
-       return dim.width() <= 10 && dim.height() <= 10;
+       // reserve some space for marker.
+       dim.wid += 2;
 }
 
 
@@ -502,62 +562,118 @@ ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
 }
 
 
+void InsetMathHull::drawMarkers(PainterInfo & pi, int x, int y) const
+{
+       ColorCode pen_color = mouseHovered(pi.base.bv) || editing(pi.base.bv)?
+               Color_mathframe : Color_mathcorners;
+       // If the corners have the same color as the background, do not paint them.
+       if (lcolor.getX11HexName(Color_mathbg) == lcolor.getX11HexName(pen_color))
+               return;
+
+       Inset::drawMarkers(pi, x, y);
+       Dimension const dim = dimension(*pi.base.bv);
+       int const t = x + dim.width() - 1;
+       int const a = y - dim.ascent();
+       pi.pain.line(x, a + 3, x, a, pen_color);
+       pi.pain.line(t, a + 3, t, a, pen_color);
+       pi.pain.line(x, a, x + 3, a, pen_color);
+       pi.pain.line(t - 3, a, t, a, pen_color);
+}
+
+
 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
 {
        Dimension const dim = dimension(*pi.base.bv);
        if (previewTooSmall(dim)) {
-               pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH, 
+               pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
                    dim.wid, dim.asc + dim.des, backgroundColor(pi));
                return;
-       } 
+       }
+
        pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
-                       dim.asc + dim.des - 1, pi.backgroundColor(this));
+                             dim.height() - 1, pi.backgroundColor(this));
 }
 
 
 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
 {
        BufferView const * const bv = pi.base.bv;
-       use_preview_ = previewState(bv);
+       Dimension const dim = dimension(*bv);
 
-       if (type_ == hullRegexp) {
-               Dimension const dim = dimension(*bv);
-               pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
-                       dim.width() - 2, dim.height() - 2, Color_regexpframe);
-       }
+       if (type_ == hullRegexp)
+               pi.pain.rectangle(x + 2, y - dim.ascent() + 1,
+                                 dim.width() - 3, dim.height() - 2, Color_regexpframe);
 
-       if (use_preview_) {
-               Dimension const dim = dimension(*bv);
+       if (previewState(bv)) {
+               // Do not draw change tracking cue if taken care of by RowPainter
+               // already.
+               Changer dummy = !canPaintChange(*bv) ? changeVar(pi.change, Change())
+                       : noChange();
                if (previewTooSmall(dim)) {
                        // we have an extra frame
                        preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
                } else {
                        // one pixel gap in front
-                       preview_->draw(pi, x + 1, y);
+                       // value was hardcoded to 1 pixel
+                       int const gap = pi.base.bv->zoomedPixels(1) ;
+                       preview_->draw(pi, x + gap, y);
                }
-               setPosCache(pi, x, y);
                return;
        }
 
-       ColorCode color = pi.selected && lyxrc.use_system_colors
-                               ? Color_selectiontext : standardColor();
-       bool const really_change_color = pi.base.font.color() == Color_none;
-       ColorChanger dummy0(pi.base.font, color, really_change_color);
-       FontSetChanger dummy1(pi.base, standardFont());
-       StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
-
-       InsetMathGrid::draw(pi, x + 1, y);
-
+       // First draw the numbers
        if (numberedType()) {
-               int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
+               BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
                for (row_type row = 0; row < nrows(); ++row) {
-                       int const yy = y + rowinfo_[row].offset_;
-                       FontSetChanger dummy(pi.base, from_ascii("mathrm"));
+                       int yy = y + rowinfo(row).offset[bv];
                        docstring const nl = nicelabel(row);
-                       pi.draw(xx, yy, nl);
+                       Dimension dimnl;
+                       mathed_string_dim(pi.base.font, nl, dimnl);
+                       if (math_number == BufferParams::LEFT) {
+                               ColorCode const col = pi.selected_left
+                                       ? Color_selectiontext
+                                       : pi.base.font.color();
+                               Changer dummy0 = pi.base.font.changeColor(col);
+                               if (dimnl.wid > x - pi.leftx)
+                                       yy += rowinfo(row).descent + dimnl.asc;
+                               pi.pain.fillRectangle(pi.leftx, yy - dimnl.asc,
+                                       dimnl.width(), dimnl.height(),
+                                       pi.selected_left ? Color_selection : pi.background_color);
+                               pi.draw(pi.leftx, yy, nl);
+                       } else {
+                               ColorCode const col = pi.selected_right
+                                       ? Color_selectiontext
+                                       : pi.base.font.color();
+                               Changer dummy0 = pi.base.font.changeColor(col);
+                               if (dimnl.wid > pi.rightx - x - dim.wid)
+                                       yy += rowinfo(row).descent + dimnl.asc;
+                               pi.pain.fillRectangle(pi.rightx - dimnl.wid, yy - dimnl.asc,
+                                       dimnl.width(), dimnl.height(),
+                                       pi.selected_right ? Color_selection : pi.background_color);
+                               pi.draw(pi.rightx - dimnl.wid, yy, nl);
+                       }
                }
        }
-       setPosCache(pi, x, y);
+
+       // Then the equations
+       ColorCode color = pi.selected && lyxrc.use_system_colors
+               ? Color_selectiontext : standardColor();
+       bool const really_change_color = pi.base.font.color() == Color_none;
+       Changer dummy0 = really_change_color ? pi.base.font.changeColor(color)
+               : noChange();
+       Changer dummy1 = pi.base.changeFontSet(standardFont());
+       Changer dummy2 = pi.base.font.changeStyle(display() ? DISPLAY_STYLE
+                                                           : TEXT_STYLE);
+       InsetMathGrid::draw(pi, x + 1, y);
+       drawMarkers(pi, x, y);
+
+       // drawing change line
+       if (canPaintChange(*bv)) {
+               // like in metrics()
+               int const display_margin = display() ? pi.base.inPixels(Length(12, Length::PT)) : 0;
+               pi.change.paintCue(pi, x + 1, y + 1 - dim.asc + display_margin,
+                                   x + dim.wid, y + dim.des - display_margin);
+       }
 }
 
 
@@ -567,7 +683,8 @@ void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
                InsetMathGrid::metricsT(mi, dim);
        } else {
                odocstringstream os;
-               WriteStream wi(os, false, true, WriteStream::wsDefault);
+               otexrowstream ots(os);
+               TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault);
                write(wi);
                dim.wid = os.str().size();
                dim.asc = 1;
@@ -582,7 +699,8 @@ void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
                InsetMathGrid::drawT(pain, x, y);
        } else {
                odocstringstream os;
-               WriteStream wi(os, false, true, WriteStream::wsDefault);
+               otexrowstream ots(os);
+               TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault);
                write(wi);
                pain.draw(x, y, os.str().c_str());
        }
@@ -600,7 +718,8 @@ static docstring latexString(InsetMathHull const & inset)
        static Encoding const * encoding = 0;
        if (inset.isBufferValid())
                encoding = &(inset.buffer().params().encoding());
-       WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
+       otexrowstream ots(ls);
+       TeXMathStream wi(ots, false, true, TeXMathStream::wsPreview, encoding);
        inset.write(wi);
        return ls.str();
 }
@@ -622,6 +741,64 @@ void InsetMathHull::addPreview(DocIterator const & inset_pos,
 }
 
 
+void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
+                               MacroNameSet & macros, MacroNameSet & defs) const
+{
+       MacroNameSet::iterator const end = macros.end();
+
+       for (size_t i = 0; i < md.size(); ++i) {
+               InsetMathMacro const * mi = md[i].nucleus()->asMacro();
+               InsetMathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
+               InsetMathScript const * si = md[i].nucleus()->asScriptInset();
+               InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
+               InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
+               InsetMathNest const * ni = md[i].nucleus()->asNestInset();
+               if (mi) {
+                       // Look for macros in the arguments of this macro.
+                       for (idx_type idx = 0; idx < mi->nargs(); ++idx)
+                               usedMacros(mi->cell(idx), pos, macros, defs);
+                       // Make sure this is a macro defined in the document
+                       // (as we also spot the macros in the symbols file)
+                       // or that we have not already accounted for it.
+                       docstring const name = mi->name();
+                       if (macros.find(name) == end)
+                               continue;
+                       macros.erase(name);
+                       // Look for macros in the definition of this macro.
+                       MathData ar(pos.buffer());
+                       MacroData const * data =
+                               pos.buffer()->getMacro(name, pos, true);
+                       if (data) {
+                               odocstringstream macro_def;
+                               data->write(macro_def, true);
+                               macro_def << endl;
+                               defs.insert(macro_def.str());
+                               asArray(data->definition(), ar);
+                       }
+                       usedMacros(ar, pos, macros, defs);
+               } else if (mt) {
+                       MathData ar(pos.buffer());
+                       asArray(mt->definition(), ar);
+                       usedMacros(ar, pos, macros, defs);
+               } else if (si) {
+                       if (!si->nuc().empty())
+                               usedMacros(si->nuc(), pos, macros, defs);
+                       if (si->hasDown())
+                               usedMacros(si->down(), pos, macros, defs);
+                       if (si->hasUp())
+                               usedMacros(si->up(), pos, macros, defs);
+               } else if (fi || gi) {
+                       idx_type nidx = fi ? fi->nargs() : gi->nargs();
+                       for (idx_type idx = 0; idx < nidx; ++idx)
+                               usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
+                                          pos, macros, defs);
+               } else if (ni) {
+                       usedMacros(ni->cell(0), pos, macros, defs);
+               }
+       }
+}
+
+
 void InsetMathHull::preparePreview(DocIterator const & pos,
                                    bool forexport) const
 {
@@ -635,16 +812,30 @@ void InsetMathHull::preparePreview(DocIterator const & pos,
        // collect macros at this position
        MacroNameSet macros;
        buffer->listMacroNames(macros);
-       MacroNameSet::iterator it = macros.begin();
-       MacroNameSet::iterator end = macros.end();
-       odocstringstream macro_preamble;
-       for (; it != end; ++it) {
-               MacroData const * data = buffer->getMacro(*it, pos, true);
-               if (data) {
-                       data->write(macro_preamble, true);
-                       macro_preamble << endl;
-               }
-       }
+
+       // collect definitions only for the macros used in this inset
+       MacroNameSet defs;
+       for (idx_type idx = 0; idx < nargs(); ++idx)
+               usedMacros(cell(idx), pos, macros, defs);
+
+       docstring macro_preamble;
+       for (auto const & defvar : defs)
+               macro_preamble.append(defvar);
+
+       // set the font series and size for this snippet
+       DocIterator dit = pos.getInnerText();
+       Paragraph const & par = dit.paragraph();
+       Font font = par.getFontSettings(buffer->params(), dit.pos());
+       font.fontInfo().realize(par.layout().font);
+       string const lsize = font.latexSize();
+       docstring setfont;
+       docstring endfont;
+       if (font.fontInfo().series() == BOLD_SERIES) {
+               setfont += from_ascii("\\textbf{");
+               endfont += '}';
+       }
+       if (lsize != "normalsize" && !prefixIs(lsize, "error"))
+               setfont += from_ascii("\\" + lsize + '\n');
 
        docstring setcnt;
        if (forexport && haveNumbers()) {
@@ -667,8 +858,8 @@ void InsetMathHull::preparePreview(DocIterator const & pos,
                                          '{' + convert<docstring>(num) + '}';
                }
        }
-       docstring const snippet = macro_preamble.str() +
-           setcnt + latexString(*this);
+       docstring const snippet = macro_preamble + setfont + setcnt
+                                 + latexString(*this) + endfont;
        LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
        preview_->addPreview(snippet, *buffer, forexport);
 }
@@ -750,45 +941,114 @@ bool InsetMathHull::numbered(row_type row) const
 bool InsetMathHull::ams() const
 {
        switch (type_) {
-               case hullAlign:
-               case hullFlAlign:
-               case hullMultline:
-               case hullGather:
-               case hullAlignAt:
-               case hullXAlignAt:
-               case hullXXAlignAt:
-                       return true;
-               case hullNone:
-               case hullSimple:
-               case hullEquation:
-               case hullEqnArray:
-               case hullRegexp:
-                       break;
+       case hullAlign:
+       case hullFlAlign:
+       case hullMultline:
+       case hullGather:
+       case hullAlignAt:
+       case hullXAlignAt:
+       case hullXXAlignAt:
+               return true;
+       case hullUnknown:
+       case hullRegexp:
+               return false;
+       case hullNone:
+       case hullSimple:
+       case hullEquation:
+       case hullEqnArray:
+               break;
        }
-       for (size_t row = 0; row < numbered_.size(); ++row)
-               if (numbered_[row] == NOTAG)
+       for (auto const & row : numbered_)
+               if (row == NOTAG)
                        return true;
        return false;
 }
 
 
-Inset::DisplayType InsetMathHull::display() const
+bool InsetMathHull::outerDisplay() const
 {
-       if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
+       switch (type_) {
+       case hullEquation:
+       case hullEqnArray:
+       case hullAlign:
+       case hullFlAlign:
+       case hullGather:
+       case hullMultline:
+               return true;
+       case hullNone:
+       case hullSimple:
+       case hullAlignAt:
+       case hullXAlignAt:
+       case hullXXAlignAt:
+       case hullUnknown:
+       case hullRegexp:
+               break;
+       }
+       return false;
+}
+
+
+int InsetMathHull::rowFlags() const
+{
+       switch (type_) {
+       case hullUnknown:
+       case hullSimple:
+       case hullNone:
+       case hullRegexp:
                return Inline;
-       return AlignCenter;
+       case hullEqnArray:
+       case hullAlign:
+       case hullFlAlign:
+       case hullAlignAt:
+       case hullXAlignAt:
+       case hullXXAlignAt:
+       case hullEquation:
+       case hullMultline:
+       case hullGather:
+               if (buffer().params().is_math_indent)
+                       return Display | AlignLeft;
+               else
+                       return Display;
+       }
+       // avoid warning
+       return Display;
+}
+
+
+int InsetMathHull::indent(BufferView const & bv) const
+{
+       // FIXME: set this in the textclass. This value is what the article class uses.
+       static Length default_indent(2.5, Length::EM);
+       if (display() && buffer().params().is_math_indent) {
+               Length const & len = buffer().params().getMathIndent();
+               if (len.empty())
+                       return bv.inPixels(default_indent);
+               else
+                       return bv.inPixels(len);
+       } else
+               return Inset::indent(bv);
 }
 
+
 bool InsetMathHull::numberedType() const
 {
-       if (type_ == hullNone)
-               return false;
-       if (type_ == hullSimple)
-               return false;
-       if (type_ == hullXXAlignAt)
-               return false;
-       if (type_ == hullRegexp)
+       switch (type_) {
+       case hullUnknown:
+       case hullNone:
+       case hullSimple:
+       case hullXXAlignAt:
+       case hullRegexp:
                return false;
+       case hullEqnArray:
+       case hullAlign:
+       case hullFlAlign:
+       case hullAlignAt:
+       case hullXAlignAt:
+       case hullEquation:
+       case hullMultline:
+       case hullGather:
+               break;
+       }
        for (row_type row = 0; row < nrows(); ++row)
                if (numbered(row))
                        return true;
@@ -804,14 +1064,17 @@ void InsetMathHull::validate(LaTeXFeatures & features) const
 
                if (type_ == hullRegexp) {
                        features.require("color");
-                       string frcol = lcolor.getLaTeXName(Color_regexpframe);
-                       string bgcol = "white";
+                       docstring frcol = from_utf8(lcolor.getLaTeXName(Color_regexpframe));
+                       docstring bgcol = from_ascii("white");
                        features.addPreambleSnippet(
-                               string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
-                               + frcol + string("}{")
-                               + bgcol + string("}{\\ensuremath{\\mathtt{#1}}}}"));
+                               "\\newcommand{\\regexp}[1]{\\fcolorbox{"
+                               + frcol + "}{"
+                               + bgcol + "}{\\ensuremath{\\mathtt{#1}}}}");
                        features.addPreambleSnippet(
-                               string("\\newcommand{\\endregexp}{}"));
+                               from_ascii("\\newcommand{\\endregexp}{}"));
+               } else if (outerDisplay() && features.inDeletedInset()) {
+                               features.require("tikz");
+                               features.require("ct-tikz-object-sout");
                }
 
                // Validation is necessary only if not using AMS math.
@@ -834,7 +1097,38 @@ void InsetMathHull::validate(LaTeXFeatures & features) const
 }
 
 
-void InsetMathHull::header_write(WriteStream & os) const
+CtObject InsetMathHull::getCtObject(OutputParams const & runparams) const
+{
+       CtObject res = CtObject::Normal;
+       switch(type_) {
+       case hullNone:
+       case hullSimple:
+       case hullAlignAt:
+       case hullXAlignAt:
+       case hullXXAlignAt:
+       case hullRegexp:
+       case hullUnknown:
+               break;
+
+       case hullEquation:
+       case hullEqnArray:
+       case hullAlign:
+       case hullFlAlign:
+       case hullGather:
+       case hullMultline: {
+               if (runparams.inulemcmd
+                   && (!runparams.local_font || runparams.local_font->fontInfo().strikeout() != FONT_ON))
+                       res = CtObject::UDisplayObject;
+               else
+                       res = CtObject::DisplayObject;
+               break;
+               }
+       }
+       return res;
+}
+
+
+void InsetMathHull::header_write(TeXMathStream & os) const
 {
        bool n = numberedType();
 
@@ -843,16 +1137,22 @@ void InsetMathHull::header_write(WriteStream & os) const
                break;
 
        case hullSimple:
+               if (os.ulemCmd())
+                       os << "\\mbox{";
                os << '$';
+               os.startOuterRow();
                if (cell(0).empty())
                        os << ' ';
                break;
 
        case hullEquation:
+               writeMathdisplayPreamble(os);
+               os << "\n";
+               os.startOuterRow();
                if (n)
-                       os << "\n\\begin{equation" << star(n) << "}\n";
+                       os << "\\begin{equation" << star(n) << "}\n";
                else
-                       os << "\n\\[\n";
+                       os << "\\[\n";
                break;
 
        case hullEqnArray:
@@ -860,17 +1160,24 @@ void InsetMathHull::header_write(WriteStream & os) const
        case hullFlAlign:
        case hullGather:
        case hullMultline:
-               os << "\n\\begin{" << hullName(type_) << star(n) << "}\n";
+               writeMathdisplayPreamble(os);
+               os << "\n";
+               os.startOuterRow();
+               os << "\\begin{" << hullName(type_) << star(n) << "}\n";
                break;
 
        case hullAlignAt:
        case hullXAlignAt:
-               os << "\n\\begin{" << hullName(type_) << star(n) << '}'
+               os << "\n";
+               os.startOuterRow();
+               os << "\\begin{" << hullName(type_) << star(n) << '}'
                  << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
                break;
 
        case hullXXAlignAt:
-               os << "\n\\begin{" << hullName(type_) << '}'
+               os << "\n";
+               os.startOuterRow();
+               os << "\\begin{" << hullName(type_) << '}'
                  << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
                break;
 
@@ -878,14 +1185,16 @@ void InsetMathHull::header_write(WriteStream & os) const
                os << "\\regexp{";
                break;
 
-       default:
-               os << "\n\\begin{unknown" << star(n) << "}\n";
+       case hullUnknown:
+               os << "\n";
+               os.startOuterRow();
+               os << "\\begin{unknown" << star(n) << "}\n";
                break;
        }
 }
 
 
-void InsetMathHull::footer_write(WriteStream & os) const
+void InsetMathHull::footer_write(TeXMathStream & os) const
 {
        bool n = numberedType();
 
@@ -896,27 +1205,42 @@ void InsetMathHull::footer_write(WriteStream & os) const
 
        case hullSimple:
                os << '$';
+               if (os.ulemCmd())
+                       os << "}";
                break;
 
        case hullEquation:
+               os << "\n";
+               os.startOuterRow();
                if (n)
-                       os << "\n\\end{equation" << star(n) << "}\n";
+                       os << "\\end{equation" << star(n) << "}\n";
                else
-                       os << "\n\\]\n";
+                       os << "\\]\n";
+               writeMathdisplayPostamble(os);
                break;
 
        case hullEqnArray:
        case hullAlign:
        case hullFlAlign:
-       case hullAlignAt:
-       case hullXAlignAt:
        case hullGather:
        case hullMultline:
-               os << "\n\\end{" << hullName(type_) << star(n) << "}\n";
+               os << "\n";
+               os.startOuterRow();
+               os << "\\end{" << hullName(type_) << star(n) << "}\n";
+               writeMathdisplayPostamble(os);
+               break;
+
+       case hullAlignAt:
+       case hullXAlignAt:
+               os << "\n";
+               os.startOuterRow();
+               os << "\\end{" << hullName(type_) << star(n) << "}\n";
                break;
 
        case hullXXAlignAt:
-               os << "\n\\end{" << hullName(type_) << "}\n";
+               os << "\n";
+               os.startOuterRow();
+               os << "\\end{" << hullName(type_) << "}\n";
                break;
 
        case hullRegexp:
@@ -924,10 +1248,35 @@ void InsetMathHull::footer_write(WriteStream & os) const
                os << "\\endregexp{}}";
                break;
 
-       default:
-               os << "\n\\end{unknown" << star(n) << "}\n";
+       case hullUnknown:
+               os << "\n";
+               os.startOuterRow();
+               os << "\\end{unknown" << star(n) << "}\n";
+               break;
+       }
+}
+
+
+bool InsetMathHull::allowsTabularFeatures() const
+{
+       switch (type_) {
+       case hullEqnArray:
+       case hullAlign:
+       case hullAlignAt:
+       case hullXAlignAt:
+       case hullXXAlignAt:
+       case hullFlAlign:
+       case hullMultline:
+       case hullGather:
+               return true;
+       case hullNone:
+       case hullSimple:
+       case hullEquation:
+       case hullRegexp:
+       case hullUnknown:
                break;
        }
+       return false;
 }
 
 
@@ -1132,10 +1481,46 @@ void InsetMathHull::setType(HullType type)
 }
 
 
+bool InsetMathHull::isMutable(HullType type)
+{
+       switch (type) {
+       case hullNone:
+       case hullSimple:
+       case hullEquation:
+       case hullEqnArray:
+       case hullAlign:
+       case hullFlAlign:
+       case hullAlignAt:
+       case hullXAlignAt:
+       case hullXXAlignAt:
+       case hullMultline:
+       case hullGather:
+               return true;
+       case hullUnknown:
+       case hullRegexp:
+               return false;
+       }
+       // avoid warning
+       return false;
+}
+
+
 void InsetMathHull::mutate(HullType newtype)
 {
        //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
 
+       if (newtype == type_)
+               return;
+
+       // This guards the algorithm below it, which is designed with certain types
+       // in mind.
+       if (!isMutable(newtype) || !isMutable(type_)) {
+               lyxerr << "mutation from '" << to_utf8(hullName(type_))
+                      << "' to '" << to_utf8(hullName(newtype))
+                      << "' not implemented" << endl;
+               return;
+       }
+
        // we try to move along the chain
        // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
        //                                     ^                                     |
@@ -1144,119 +1529,155 @@ void InsetMathHull::mutate(HullType newtype)
        // directly supported because it handles labels and numbering for
        // "down mutation".
 
-       if (newtype == type_) {
-               // done
-       }
-
-       else if (newtype < hullNone) {
-               // unknown type
-               dump();
-       }
-
-       else if (type_ == hullNone) {
+       switch (type_) {
+       case hullNone:
                setType(hullSimple);
                numbered(0, false);
                mutate(newtype);
-       }
+               break;
 
-       else if (type_ == hullSimple) {
+       case hullSimple:
                if (newtype == hullNone) {
                        setType(hullNone);
                        numbered(0, false);
                } else {
                        setType(hullEquation);
-                       numbered(0, label_[0] ? true : false);
+                       numbered(0, label_[0] != nullptr);
                        mutate(newtype);
                }
-       }
+               break;
 
-       else if (type_ == hullEquation) {
-               if (newtype < type_) {
+       case hullEquation:
+               switch (newtype) {
+               case hullNone:
+               case hullSimple:
                        setType(hullSimple);
                        numbered(0, false);
                        mutate(newtype);
-               } else if (newtype == hullEqnArray) {
+                       break;
+               case hullEqnArray:
                        // split it "nicely" on the first relop
                        splitTo3Cols();
                        setType(hullEqnArray);
-               } else if (newtype == hullMultline || newtype == hullGather) {
+                       break;
+               case hullMultline:
+               case hullGather:
                        setType(newtype);
-               } else {
+                       break;
+               default:
+                       // *align*
                        // split it "nicely"
                        splitTo2Cols();
                        setType(hullAlign);
                        mutate(newtype);
+                       break;
                }
-       }
+               break;
 
-       else if (type_ == hullEqnArray) {
-               if (newtype < type_) {
+       case hullEqnArray:
+               switch (newtype) {
+               case hullNone:
+               case hullSimple:
+               case hullEquation:
                        glueall(newtype);
                        mutate(newtype);
-               } else { // align & Co.
+                       break;
+               default:
+                       // align & Co.
                        changeCols(2);
                        setType(hullAlign);
                        mutate(newtype);
+                       break;
                }
-       }
+               break;
 
-       else if (type_ ==  hullAlign || type_ == hullAlignAt ||
-                type_ == hullXAlignAt || type_ == hullFlAlign) {
-               if (newtype < hullAlign) {
+       case hullAlign:
+       case hullAlignAt:
+       case hullXAlignAt:
+       case hullFlAlign:
+               switch (newtype) {
+               case hullNone:
+               case hullSimple:
+               case hullEquation:
+               case hullEqnArray:
                        changeCols(3);
                        setType(hullEqnArray);
                        mutate(newtype);
-               } else if (newtype == hullGather || newtype == hullMultline) {
+                       break;
+               case hullGather:
+               case hullMultline:
                        changeCols(1);
                        setType(newtype);
-               } else if (newtype ==   hullXXAlignAt) {
+                       break;
+               case hullXXAlignAt:
                        for (row_type row = 0; row < nrows(); ++row)
                                numbered(row, false);
                        setType(newtype);
-               } else {
+                       break;
+               default:
                        setType(newtype);
+                       break;
                }
-       }
+               break;
 
-       else if (type_ == hullXXAlignAt) {
+       case hullXXAlignAt:
                for (row_type row = 0; row < nrows(); ++row)
                        numbered(row, false);
-               if (newtype < hullAlign) {
+               switch (newtype) {
+               case hullNone:
+               case hullSimple:
+               case hullEquation:
+               case hullEqnArray:
                        changeCols(3);
                        setType(hullEqnArray);
                        mutate(newtype);
-               } else if (newtype == hullGather || newtype == hullMultline) {
+                       break;
+               case hullGather:
+               case hullMultline:
                        changeCols(1);
                        setType(newtype);
-               } else {
+                       break;
+               default:
                        setType(newtype);
+                       break;
                }
-       }
+               break;
 
-       else if (type_ == hullMultline || type_ == hullGather) {
-               if (newtype == hullGather || newtype == hullMultline)
+       case hullMultline:
+       case hullGather:
+               switch (newtype) {
+               case hullGather:
+               case hullMultline:
                        setType(newtype);
-               else if (newtype == hullAlign || newtype == hullFlAlign  ||
-                        newtype == hullAlignAt || newtype == hullXAlignAt) {
+                       break;
+               case hullAlign:
+               case hullFlAlign:
+               case hullAlignAt:
+               case hullXAlignAt:
                        splitTo2Cols();
                        setType(newtype);
-               } else if (newtype ==   hullXXAlignAt) {
+                       break;
+               case hullXXAlignAt:
                        splitTo2Cols();
                        for (row_type row = 0; row < nrows(); ++row)
                                numbered(row, false);
                        setType(newtype);
-               } else {
+                       break;
+               default:
+                       // first we mutate to EqnArray
                        splitTo3Cols();
                        setType(hullEqnArray);
                        mutate(newtype);
+                       break;
                }
-       }
+               break;
 
-       else {
-               lyxerr << "mutation from '" << to_utf8(hullName(type_))
-                      << "' to '" << to_utf8(hullName(newtype))
-                      << "' not implemented" << endl;
-       }
+       default:
+               // we passed the guard so we should not be here
+               LYXERR0("Mutation not implemented, but should have been.");
+               LASSERT(false, return);
+               break;
+       }// switch
 }
 
 
@@ -1283,8 +1704,7 @@ docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
        return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
 }
 
-
-void InsetMathHull::write(WriteStream & os) const
+void InsetMathHull::write(TeXMathStream & os) const
 {
        ModeSpecifier specifier(os, MATH_MODE);
        header_write(os);
@@ -1317,13 +1737,11 @@ void InsetMathHull::check() const
 
 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
 {
-       docstring dlang;
-       docstring extra;
-       idocstringstream iss(func.argument());
-       iss >> dlang >> extra;
+       //FIXME: sort out whether we want std::string or docstring for those
+       string const lang = func.getArg(0);
+       docstring extra = from_utf8(func.getArg(1));
        if (extra.empty())
                extra = from_ascii("noextra");
-       string const lang = to_ascii(dlang);
 
        // replace selection with result of computation
        if (reduceSelectionToOneCell(cur)) {
@@ -1335,7 +1753,12 @@ void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
        }
 
        // only inline, display or eqnarray math is allowed
-       if (getType() > hullEqnArray) {
+       switch (getType()) {
+       case hullSimple:
+       case hullEquation:
+       case hullEqnArray:
+               break;
+       default:
                frontend::Alert::warning(_("Bad math environment"),
                                _("Computation cannot be performed for AMS "
                                  "math environments.\nChange the math "
@@ -1420,7 +1843,7 @@ void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
                if (type_ == hullSimple || type_ == hullEquation) {
                        cur.recordUndoInset();
                        bool const align =
-                               cur.bv().buffer().params().use_package("amsmath") == BufferParams::package_on;
+                               cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
                        mutate(align ? hullAlign : hullEqnArray);
                        // mutate() may change labels and such.
                        cur.forceBufferUpdate();
@@ -1582,12 +2005,25 @@ void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
        case LFUN_MATH_DISPLAY: {
                cur.recordUndoInset();
                mutate(type_ == hullSimple ? hullEquation : hullSimple);
-               cur.idx() = 0;
-               cur.pos() = cur.lastpos();
-               //cur.dispatched(FINISHED);
+               // if the cursor is in a cell that got merged, move it to
+               // start of the hull inset.
+               if (cur.idx() > 0) {
+                       cur.idx() = 0;
+                       cur.pos() = 0;
+               }
+               if (cur.pos() > cur.lastpos())
+                       cur.pos() = cur.lastpos();
+
                break;
        }
 
+       case LFUN_TABULAR_FEATURE:
+               if (!allowsTabularFeatures())
+                       cur.undispatched();
+               else
+                       InsetMathGrid::doDispatch(cur, cmd);
+               break;
+
        default:
                InsetMathGrid::doDispatch(cur, cmd);
                break;
@@ -1595,6 +2031,21 @@ void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
 }
 
 
+namespace {
+
+bool allowDisplayMath(Cursor const & cur)
+{
+       LATTEST(cur.depth() > 1);
+       Cursor tmpcur = cur;
+       tmpcur.pop();
+       FuncStatus status;
+       FuncRequest cmd(LFUN_MATH_DISPLAY);
+       return tmpcur.getStatus(cmd, status) && status.enabled();
+}
+
+} // namespace
+
+
 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
                FuncStatus & status) const
 {
@@ -1619,39 +2070,22 @@ bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
        case LFUN_MATH_MUTATE: {
                HullType const ht = hullType(cmd.argument());
                status.setOnOff(type_ == ht);
-               status.setEnabled(true);
+               status.setEnabled(isMutable(ht) && isMutable(type_));
 
-               if (ht != hullSimple) {
-                       Cursor tmpcur = cur;
-                       while (!tmpcur.empty()) {
-                               InsetCode code = tmpcur.inset().lyxCode();
-                               if (code == BOX_CODE) {
-                                       return true;
-                               } else if (code == TABULAR_CODE) {
-                                       FuncRequest tmpcmd(LFUN_MATH_DISPLAY);
-                                       if (tmpcur.getStatus(tmpcmd, status) && !status.enabled())
-                                               return true;
-                               }
-                               tmpcur.pop_back();
-                       }
-               }
+               if (ht != hullSimple && status.enabled())
+                       status.setEnabled(allowDisplayMath(cur));
                return true;
        }
        case LFUN_MATH_DISPLAY: {
-               bool enable = true;
-               if (cur.depth() > 1) {
-                       Inset const & in = cur[cur.depth()-2].inset();
-                       if (in.lyxCode() == SCRIPT_CODE)
-                               enable = display() != Inline;
-               }
-               status.setEnabled(enable);
+               status.setEnabled(display() || allowDisplayMath(cur));
+               status.setOnOff(display());
                return true;
        }
 
        case LFUN_MATH_NUMBER_TOGGLE:
                // FIXME: what is the right test, this or the one of
                // LABEL_INSERT?
-               status.setEnabled(display() != Inline);
+               status.setEnabled(display());
                status.setOnOff(numberedType());
                return true;
 
@@ -1660,7 +2094,7 @@ bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
                // LABEL_INSERT?
                bool const enable = (type_ == hullMultline)
                        ? (nrows() - 1 == cur.row())
-                       : display() != Inline;
+                       : display();
                row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
                status.setEnabled(enable);
                status.setOnOff(enable && numbered(r));
@@ -1673,11 +2107,10 @@ bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
 
        case LFUN_LABEL_COPY_AS_REFERENCE: {
                bool enabled = false;
-               row_type row;
                if (cmd.argument().empty() && &cur.inset() == this) {
                        // if there is no argument and we're inside math, we retrieve
                        // the row number from the cursor position.
-                       row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
+                       row_type row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
                        enabled = numberedType() && label_[row] && numbered(row);
                } else {
                        // if there is an argument, find the corresponding label, else
@@ -1701,13 +2134,10 @@ bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
                }
                return InsetMathGrid::getStatus(cur, cmd, status);
 
-       case LFUN_INSET_MODIFY: {
-               istringstream is(to_utf8(cmd.argument()));
-               string s;
-               is >> s;
-               if (s != "tabular")
-                       return InsetMathGrid::getStatus(cur, cmd, status);
-               is >> s;
+       case LFUN_TABULAR_FEATURE: {
+               if (!allowsTabularFeatures())
+                       return false;
+               string s = cmd.getArg(0);
                if (!rowChangeOK()
                    && (s == "append-row"
                        || s == "delete-row"
@@ -1728,16 +2158,6 @@ bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
                        status.setEnabled(false);
                        return true;
                }
-               if ((type_ == hullSimple
-                 || type_ == hullEquation
-                 || type_ == hullNone) &&
-                   (s == "add-hline-above" || s == "add-hline-below")) {
-                       status.message(bformat(
-                               from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
-                               hullName(type_)));
-                       status.setEnabled(false);
-                       return true;
-               }
                if (s == "add-vline-left" || s == "add-vline-right") {
                        status.message(bformat(
                                from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
@@ -1757,9 +2177,24 @@ bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
        default:
                return InsetMathGrid::getStatus(cur, cmd, status);
        }
+}
+
 
-       // This cannot really happen, but inserted to shut-up gcc
-       return InsetMathGrid::getStatus(cur, cmd, status);
+int InsetMathHull::leftMargin() const
+{
+       return (getType() == hullSimple) ? 0 : InsetMathGrid::leftMargin();
+}
+
+
+int InsetMathHull::rightMargin() const
+{
+       return (getType() == hullSimple) ? 0 : InsetMathGrid::rightMargin();
+}
+
+
+int InsetMathHull::border() const
+{
+       return (getType() == hullSimple) ? 0 : InsetMathGrid::border();
 }
 
 
@@ -1812,17 +2247,14 @@ void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
        font.fromString(to_utf8(arg), b);
        if (font.fontInfo().color() != Color_inherit) {
                MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
-               cur.handleNest(at, 0);
+               cur.handleNest(at);
        }
 }
 
 
 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
 {
-       cur.push(*this);
-       bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
-               (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
-       enter_front ? idxFirst(cur) : idxLast(cur);
+       InsetMathNest::edit(cur, front, entry_from);
        // The inset formula dimension is not necessarily the same as the
        // one of the instant preview image, so we have to indicate to the
        // BufferView that a metrics update is needed.
@@ -1830,42 +2262,6 @@ void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
 }
 
 
-void InsetMathHull::revealCodes(Cursor & cur) const
-{
-       if (!cur.inMathed())
-               return;
-       odocstringstream os;
-       cur.info(os);
-       cur.message(os.str());
-/*
-       // write something to the minibuffer
-       // translate to latex
-       cur.markInsert(bv);
-       ostringstream os;
-       write(os);
-       string str = os.str();
-       cur.markErase(bv);
-       string::size_type pos = 0;
-       string res;
-       for (string::iterator it = str.begin(); it != str.end(); ++it) {
-               if (*it == '\n')
-                       res += ' ';
-               else if (*it == '\0') {
-                       res += "  -X-  ";
-                       pos = it - str.begin();
-               }
-               else
-                       res += *it;
-       }
-       if (pos > 30)
-               res = res.substr(pos - 30);
-       if (res.size() > 60)
-               res = res.substr(0, 60);
-       cur.message(res);
-*/
-}
-
-
 /////////////////////////////////////////////////////////////////////
 
 
@@ -1913,7 +2309,8 @@ bool InsetMathHull::searchForward(BufferView * bv, string const & str,
 void InsetMathHull::write(ostream & os) const
 {
        odocstringstream oss;
-       WriteStream wi(oss, false, false, WriteStream::wsDefault);
+       otexrowstream ots(oss);
+       TeXMathStream wi(ots, false, false, TeXMathStream::wsDefault);
        oss << "Formula ";
        write(wi);
        os << to_utf8(oss.str());
@@ -1941,8 +2338,8 @@ bool InsetMathHull::readQuiet(Lexer & lex)
 int InsetMathHull::plaintext(odocstringstream & os,
         OutputParams const & op, size_t max_length) const
 {
-       // disables ASCII-art for export of equations. See #2275.
-       if (0 && display()) {
+       // Try enabling this now that there is a flag as requested at #2275.
+       if (buffer().isExporting() && display()) {
                Dimension dim;
                TextMetricsInfo mi;
                metricsT(mi, dim);
@@ -1955,8 +2352,9 @@ int InsetMathHull::plaintext(odocstringstream & os,
        }
 
        odocstringstream oss;
+       otexrowstream ots(oss);
        Encoding const * const enc = encodings.fromLyXName("utf8");
-       WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
+       TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault, enc);
 
        // Fix Bug #6139
        if (type_ == hullRegexp)
@@ -1969,7 +2367,7 @@ int InsetMathHull::plaintext(odocstringstream & os,
                        // and do not include the newline.
                        if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
                                break;
-                        if (r < nrows() - 1)
+                       if (r < nrows() - 1)
                                wi << "\n";
                }
        }
@@ -1979,62 +2377,105 @@ int InsetMathHull::plaintext(odocstringstream & os,
 }
 
 
-int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
-{
-       MathStream ms(os);
-       int res = 0;
+void InsetMathHull::docbook(XMLStream & xs, OutputParams const & runparams) const {
+       // Choose the tag around the MathML equation.
        docstring name;
+       bool doCR = false;
        if (getType() == hullSimple)
                name = from_ascii("inlineequation");
-       else
+       else {
+               doCR = true; // This is a block equation, always have <informalequation> on its own line.
                name = from_ascii("informalequation");
+       }
 
-       docstring bname = name;
-       if (!label(0).empty())
-               bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
+       // DocBook also has <equation>, but it comes with a title.
+       // TODO: recognise \tag from amsmath? This would allow having <equation> with a proper title.
 
-       ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
+       docstring attr;
 
-       odocstringstream ls;
-       if (runparams.flavor == OutputParams::XML) {
-               ms << MTag("alt role='tex' ");
-               // Workaround for db2latex: db2latex always includes equations with
-               // \ensuremath{} or \begin{display}\end{display}
-               // so we strip LyX' math environment
-               WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
-               InsetMathGrid::write(wi);
-               ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
-               ms << ETag("alt");
-               ms << MTag("math");
-               ms << ETag("alt");
-               ms << MTag("math");
-               InsetMathGrid::mathmlize(ms);
-               ms << ETag("math");
-       } else {
-               TexRow texrow;
-               texrow.reset();
-               otexstream ols(ls, texrow);
-               ms << MTag("alt role='tex'");
-               latex(ols, runparams);
-               res = texrow.rows();
-               ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
-               ms << ETag("alt");
+       bool mathmlNamespaceInline = buffer().params().docbook_mathml_prefix == BufferParams::NoPrefix;
+       if (mathmlNamespaceInline)
+               attr += "xmlns=\"http://www.w3.org/1998/Math/MathML\"";
+
+       for (row_type i = 0; i < nrows(); ++i) {
+               if (!label(i).empty()) {
+                       if (!attr.empty())
+                               attr += " ";
+
+                       attr += "xml:id=\"" + xml::cleanID(label(i)) + "\"";
+                       break;
+               }
+       }
+
+       if (doCR)
+               if (!xs.isLastTagCR())
+                       xs << xml::CR();
+
+       xs << xml::StartTag(name, attr);
+       xs << xml::CR();
+
+       // With DocBook 5, MathML must be within its own namespace (defined in Buffer.cpp::writeDocBookSource, except when
+       // it should be inlined).
+       // Output everything in a separate stream so that this does not interfere with the standard flow of DocBook tags.
+       std::string mathmlNamespacePrefix;
+       if (!mathmlNamespaceInline) {
+               if (buffer().params().docbook_mathml_prefix == BufferParams::MPrefix)
+                       mathmlNamespacePrefix = "m";
+               else if (buffer().params().docbook_mathml_prefix == BufferParams::MMLPrefix)
+                       mathmlNamespacePrefix = "mml";
        }
 
-       ms << from_ascii("<graphic fileref=\"eqn/");
-       if (!label(0).empty())
-               ms << sgml::cleanID(buffer(), runparams, label(0));
-       else
-               ms << sgml::uniqueID(from_ascii("anon"));
+       odocstringstream osmath;
+       MathMLStream ms(osmath, mathmlNamespacePrefix, true);
 
-       if (runparams.flavor == OutputParams::XML)
-               ms << from_ascii("\"/>");
-       else
-               ms << from_ascii("\">");
+       // Output the MathML subtree.
+       // TeX transcription. Avoid MTag/ETag so that there are no extraneous spaces.
+       ms << "<" << from_ascii("alt") << " role='tex'" << ">";
+       // Workaround for db2latex: db2latex always includes equations with
+       // \ensuremath{} or \begin{display}\end{display}
+       // so we strip LyX' math environment
+       odocstringstream ls;
+       otexstream ols(ls);
+       TeXMathStream wi(ols, false, false, TeXMathStream::wsDefault, runparams.encoding);
+       InsetMathGrid::write(wi);
+       ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
+       ms << "</" << from_ascii("alt") << ">";
+
+       // Actual transformation of the formula into MathML. This translation may fail (for example, due to custom macros).
+       // The new output stream is required to deal with the errors: first write completely the formula into this
+       // temporary stream; then, if it is possible without error, then copy it back to the "real" stream. Otherwise,
+       // some incomplete tags might be put into the real stream.
+       try {
+               // First, generate the MathML expression. If there is an error in the generation, this block is not fully
+               // executed, and the formula is not output to the DocBook stream.
+               odocstringstream ostmp;
+               MathMLStream mstmp(ostmp, ms.xmlns(), ms.xmlMode());
+               mathmlize(mstmp);
+
+               // Choose the display style for the formula, to be output as an attribute near the formula root.
+               std::string mathmlAttr;
+               if (getType() == hullSimple)
+                       mathmlAttr = "display=\"inline\"";
+               else
+                       mathmlAttr = "display=\"block\"";
 
-       ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
+               // Then, output the formula.
+               ms << MTag("math", mathmlAttr);
+               ms.cr();
+               osmath << ostmp.str(); // osmath is not a XMLStream, so no need for XMLStream::ESCAPE_NONE.
+               ms << ETag("math");
+       } catch (MathExportException const &) {
+               ms.cr();
+               osmath << "<mathphrase>MathML export failed. Please report this as a bug to the LyX developers: "
+                       "https://www.lyx.org/trac.</mathphrase>";
+       }
 
-       return ms.line() + res;
+       // Output the complete formula to the DocBook stream.
+       xs << XMLStream::ESCAPE_NONE << osmath.str();
+       xs << xml::CR();
+       xs << xml::EndTag(name);
+       if (doCR)
+               xs << xml::CR();
 }
 
 
@@ -2094,43 +2535,54 @@ void InsetMathHull::htmlize(HtmlStream & os) const
 // this duplicates code from InsetMathGrid, but
 // we need access here to number information,
 // and we simply do not have that in InsetMathGrid.
-void InsetMathHull::mathmlize(MathStream & os) const
-{
-       bool const havenumbers = haveNumbers();
-       bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
+void InsetMathHull::mathmlize(MathMLStream & ms) const
+{
+       bool const havetable = haveNumbers() || nrows() > 1 || ncols() > 1;
+
+    if (havetable) {
+        if (getType() == hullSimple) {
+               ms << MTag("mtable");
+        } else if (getType() >= hullAlign && getType() <= hullXXAlignAt) {
+            string alignment;
+            for (col_type col = 0; col < ncols(); ++col) {
+                alignment += (col % 2) ? "left " : "right ";
+            }
+            ms << MTag("mtable", "displaystyle='true' columnalign='" + alignment + "'");
+           } else {
+               ms << MTag("mtable", "displaystyle='true'");
+        }
+    }
 
-       if (havetable)
-               os << MTag("mtable");
        char const * const celltag = havetable ? "mtd" : "mrow";
        // FIXME There does not seem to be wide support at the moment
        // for mlabeledtr, so we have to use just mtr for now.
-       // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
+       // char const * const rowtag = haveNumbers() ? "mlabeledtr" : "mtr";
        char const * const rowtag = "mtr";
        for (row_type row = 0; row < nrows(); ++row) {
                if (havetable)
-                       os << MTag(rowtag);
+                       ms << MTag(rowtag);
                for (col_type col = 0; col < ncols(); ++col) {
-                       os << MTag(celltag)
+                       ms << MTag(celltag)
                           << cell(index(row, col))
                           << ETag(celltag);
                }
                // fleqn?
-               if (havenumbers) {
-                       os << MTag("mtd");
+               if (haveNumbers()) {
+                       ms << MTag("mtd");
                        docstring const & num = numbers_[row];
                        if (!num.empty())
-                               os << '(' << num << ')';
-                 os << ETag("mtd");
+                               ms << MTagInline("mtext") << '(' << num << ')' << ETagInline("mtext");
+                   ms << ETag("mtd");
                }
                if (havetable)
-                       os << ETag(rowtag);
+                       ms << ETag(rowtag);
        }
        if (havetable)
-               os << ETag("mtable");
+               ms << ETag("mtable");
 }
 
 
-void InsetMathHull::mathAsLatex(WriteStream & os) const
+void InsetMathHull::mathAsLatex(TeXMathStream & os) const
 {
        MathEnsurer ensurer(os, false);
        bool havenumbers = haveNumbers();
@@ -2162,7 +2614,7 @@ void InsetMathHull::mathAsLatex(WriteStream & os) const
 }
 
 
-docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
+docstring InsetMathHull::xhtml(XMLStream & xs, OutputParams const & op) const
 {
        BufferParams::MathOutput const mathtype =
                buffer().masterBuffer()->params().html_math_output;
@@ -2181,21 +2633,21 @@ docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
        // FIXME Eventually we would like to do this inset by inset.
        if (mathtype == BufferParams::MathML) {
                odocstringstream os;
-               MathStream ms(os);
+               MathMLStream ms(os);
                try {
                        mathmlize(ms);
                        success = true;
                } catch (MathExportException const &) {}
                if (success) {
                        if (getType() == hullSimple)
-                               xs << html::StartTag("math",
+                               xs << xml::StartTag("math",
                                                        "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
                        else
-                               xs << html::StartTag("math",
+                               xs << xml::StartTag("math",
                                      "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
-                       xs << XHTMLStream::ESCAPE_NONE
+                       xs << XMLStream::ESCAPE_NONE
                                 << os.str()
-                                << html::EndTag("math");
+                                << xml::EndTag("math");
                }
        } else if (mathtype == BufferParams::HTML) {
                odocstringstream os;
@@ -2206,10 +2658,10 @@ docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
                } catch (MathExportException const &) {}
                if (success) {
                        string const tag = (getType() == hullSimple) ? "span" : "div";
-                       xs << html::StartTag(tag, "class='formula'", true)
-                          << XHTMLStream::ESCAPE_NONE
+                       xs << xml::StartTag(tag, "class='formula'", true)
+                          << XMLStream::ESCAPE_NONE
                           << os.str()
-                          << html::EndTag(tag);
+                          << xml::EndTag(tag);
                }
        }
 
@@ -2221,7 +2673,9 @@ docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
        //    )
        // but what follows is equivalent, since we'll enter only if either (a) we
        // tried and failed with MathML or HTML or (b) didn't try yet at all but
-       // aren't doing LaTeX, in which case we are doing Images.
+       // aren't doing LaTeX.
+       //
+       // so this is for Images.
        if (!success && mathtype != BufferParams::LaTeX) {
                graphics::PreviewImage const * pimage = 0;
                if (!op.dryrun) {
@@ -2247,11 +2701,11 @@ docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
                        }
 
                        string const tag = (getType() == hullSimple) ? "span" : "div";
-                       xs << html::CR()
-                          << html::StartTag(tag)
-                                << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
-                                << html::EndTag(tag)
-                                << html::CR();
+                       xs << xml::CR()
+                          << xml::StartTag(tag, "style = \"text-align: center;\"")
+                          << xml::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
+                          << xml::EndTag(tag)
+                          << xml::CR();
                        success = true;
                }
        }
@@ -2263,7 +2717,8 @@ docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
                // Unfortunately, we cannot use latexString() because we do not want
                // $...$ or whatever.
                odocstringstream ls;
-               WriteStream wi(ls, false, true, WriteStream::wsPreview);
+               otexrowstream ots(ls);
+               TeXMathStream wi(ots, false, true, TeXMathStream::wsPreview);
                ModeSpecifier specifier(wi, MATH_MODE);
                mathAsLatex(wi);
                docstring const latex = ls.str();
@@ -2273,10 +2728,10 @@ docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
                // FIXME XHTML
                // probably should allow for some kind of customization here
                string const tag = (getType() == hullSimple) ? "span" : "div";
-               xs << html::StartTag(tag, "class='math'")
+               xs << xml::StartTag(tag, "class='math'")
                   << latex
-                  << html::EndTag(tag)
-                  << html::CR();
+                  << xml::EndTag(tag)
+                  << xml::CR();
        }
        return docstring();
 }
@@ -2290,11 +2745,13 @@ void InsetMathHull::toString(odocstream & os) const
 }
 
 
-void InsetMathHull::forOutliner(docstring & os, size_t) const
+void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
 {
        odocstringstream ods;
        OutputParams op(0);
        op.for_toc = true;
+       // FIXME: this results in spilling TeX into the LyXHTML output since the
+       // outliner is used to generate the LyXHTML list of figures/etc.
        plaintext(ods, op);
        os += ods.str();
 }
@@ -2311,4 +2768,12 @@ void InsetMathHull::recordLocation(DocIterator const & di)
        docit_ = di;
 }
 
+
+bool InsetMathHull::canPaintChange(BufferView const &) const
+{
+       // We let RowPainter do it seamlessly for inline insets
+       return display();
+}
+
+
 } // namespace lyx