]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathHull.cpp
a9dd9fd5c0efac0fcfa0c8507391d104059da0d0
[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 #include "InsetMathChar.h"
15 #include "InsetMathColor.h"
16 #include "InsetMathFrac.h"
17 #include "InsetMathNest.h"
18 #include "InsetMathScript.h"
19 #include "MathExtern.h"
20 #include "MathFactory.h"
21 #include "MathStream.h"
22 #include "MathSupport.h"
23
24 #include "Buffer.h"
25 #include "BufferParams.h"
26 #include "BufferView.h"
27 #include "ColorSet.h"
28 #include "Cursor.h"
29 #include "CutAndPaste.h"
30 #include "Encoding.h"
31 #include "Exporter.h"
32 #include "FuncRequest.h"
33 #include "FuncStatus.h"
34 #include "Language.h"
35 #include "LaTeXFeatures.h"
36 #include "LyXRC.h"
37 #include "MacroTable.h"
38 #include "InsetMathMacro.h"
39 #include "InsetMathMacroTemplate.h"
40 #include "MetricsInfo.h"
41 #include "Paragraph.h"
42 #include "ParIterator.h"
43 #include "xml.h"
44 #include "TexRow.h"
45 #include "TextClass.h"
46 #include "TextPainter.h"
47 #include "TocBackend.h"
48
49 #include "insets/InsetLabel.h"
50 #include "insets/InsetRef.h"
51 #include "insets/RenderPreview.h"
52
53 #include "graphics/PreviewImage.h"
54 #include "graphics/PreviewLoader.h"
55
56 #include "frontends/alert.h"
57 #include "frontends/FontMetrics.h"
58 #include "frontends/Painter.h"
59
60 #include "support/convert.h"
61 #include "support/debug.h"
62 #include "support/gettext.h"
63 #include "support/filetools.h"
64 #include "support/lassert.h"
65 #include "support/lstrings.h"
66 #include "support/Changer.h"
67
68 #include <sstream>
69
70 using namespace std;
71 using namespace lyx::support;
72
73 namespace lyx {
74
75 using cap::grabAndEraseSelection;
76 using cap::reduceSelectionToOneCell;
77
78 namespace {
79
80         int getCols(HullType type)
81         {
82                 switch (type) {
83                 case hullEqnArray:
84                         return 3;
85                 case hullAlign:
86                 case hullFlAlign:
87                 case hullAlignAt:
88                 case hullXAlignAt:
89                 case hullXXAlignAt:
90                         return 2;
91                 case hullUnknown:
92                 case hullNone:
93                 case hullSimple:
94                 case hullEquation:
95                 case hullMultline:
96                 case hullGather:
97                 case hullRegexp:
98                         return 1;
99                 }
100                 // avoid warning
101                 return 0;
102         }
103
104
105         // returns position of first relation operator in the array
106         // used for "intelligent splitting"
107         size_t firstRelOp(MathData const & ar)
108         {
109                 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
110                         if ((*it)->mathClass() == MC_REL)
111                                 return it - ar.begin();
112                 return ar.size();
113         }
114
115
116         char const * star(bool numbered)
117         {
118                 return numbered ? "" : "*";
119         }
120
121
122         // writes a preamble for underlined or struck out math display
123         void writeMathdisplayPreamble(TeXMathStream & os)
124         {
125                 if (os.strikeoutMath())
126                         return;
127
128                 if (os.ulemCmd() == TeXMathStream::UNDERLINE)
129                         os << "\\raisebox{-\\belowdisplayshortskip}{"
130                               "\\parbox[b]{\\linewidth}{";
131                 else if (os.ulemCmd() == TeXMathStream::STRIKEOUT)
132                         os << "\\parbox{\\linewidth}{";
133         }
134
135
136         // writes a postamble for underlined or struck out math display
137         void writeMathdisplayPostamble(TeXMathStream & os)
138         {
139                 if (os.strikeoutMath())
140                         return;
141
142                 if (os.ulemCmd() == TeXMathStream::UNDERLINE)
143                         os << "}}\\\\\n";
144                 else if (os.ulemCmd() == TeXMathStream::STRIKEOUT)
145                         os << "}\\\\\n";
146         }
147
148 } // namespace
149
150
151 static InsetLabel * dummy_pointer = 0;
152
153 InsetMathHull::InsetMathHull(Buffer * buf)
154         : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, NONUMBER),
155           numbers_(1, empty_docstring()), label_(1, dummy_pointer),
156           preview_(new RenderPreview(this))
157 {
158         //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
159         //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
160         //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
161         //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
162         buffer_ = buf;
163         initMath();
164         setDefaults();
165 }
166
167
168 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
169         : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, NONUMBER),
170           numbers_(1, empty_docstring()), label_(1, dummy_pointer),
171           preview_(new RenderPreview(this))
172 {
173         buffer_ = buf;
174         initMath();
175         setDefaults();
176 }
177
178
179 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
180 {
181         operator=(other);
182 }
183
184
185 InsetMathHull::~InsetMathHull()
186 {
187         for (auto & i : label_)
188                 delete i;
189 }
190
191
192 Inset * InsetMathHull::clone() const
193 {
194         return new InsetMathHull(*this);
195 }
196
197
198 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
199 {
200         if (this == &other)
201                 return *this;
202         InsetMathGrid::operator=(other);
203         type_  = other.type_;
204         numbered_ = other.numbered_;
205         numbers_ = other.numbers_;
206         buffer_ = other.buffer_;
207         for (auto & i : label_)
208                 delete i;
209         label_ = other.label_;
210         for (size_t i = 0; i != label_.size(); ++i) {
211                 if (label_[i])
212                         label_[i] = new InsetLabel(*label_[i]);
213         }
214         preview_.reset(new RenderPreview(*other.preview_, this));
215
216         return *this;
217 }
218
219
220 void InsetMathHull::setBuffer(Buffer & buffer)
221 {
222         InsetMathGrid::setBuffer(buffer);
223
224         for (size_t i = 0; i != label_.size(); ++i) {
225                 if (label_[i])
226                         label_[i]->setBuffer(buffer);
227         }
228 }
229
230
231 // FIXME This should really be controlled by the TOC level, or
232 // something of the sort.
233 namespace {
234         const char * counters_to_save[] = {"section", "chapter"};
235         unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
236 } // namespace
237
238
239 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
240 {
241         if (!buffer_) {
242                 //FIXME: buffer_ should be set at creation for this inset! Problem is
243                 // This inset is created at too many places (see Parser::parse1() in
244                 // MathParser.cpp).
245                 return;
246         }
247
248         // if any of the equations are numbered, then we want to save the values
249         // of some of the counters.
250         if (haveNumbers()) {
251                 BufferParams const & bp = buffer_->params();
252                 string const & lang = it->getParLanguage(bp)->code();
253                 Counters & cnts =
254                         buffer_->masterBuffer()->params().documentClass().counters();
255
256                 // this has to be done separately
257                 docstring const eqstr = from_ascii("equation");
258                 if (cnts.hasCounter(eqstr)) {
259                         for (size_t i = 0; i != label_.size(); ++i) {
260                                 docstring const oldnumber = numbers_[i];
261                                 if (numbered(i)) {
262                                         Paragraph const & par = it.paragraph();
263                                         if (!par.isDeleted(it.pos())) {
264                                                 cnts.step(eqstr, utype);
265                                                 numbers_[i] = cnts.theCounter(eqstr, lang);
266                                         } else
267                                                 numbers_[i] = from_ascii("#");
268                                 } else
269                                         numbers_[i] = empty_docstring();
270                                 // If the numbering has changed, trigger a new preview
271                                 if (oldnumber != numbers_[i] && RenderPreview::previewMath()) {
272                                         // Do we need to remove it first?
273                                         //preview_->removePreview(*buffer_);
274                                         preparePreview(it);
275                                 }
276                         }
277                 }
278         }
279
280         // now the labels
281         for (size_t i = 0; i != label_.size(); ++i) {
282                 if (label_[i])
283                         label_[i]->updateBuffer(it, utype, deleted);
284         }
285         // pass down
286         InsetMathGrid::updateBuffer(it, utype, deleted);
287 }
288
289
290 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active,
291                                                          UpdateType utype, TocBackend & backend) const
292 {
293         if (!buffer_) {
294                 //FIXME: buffer_ should be set at creation for this inset! Problem is
295                 // This inset is created at too many places (see Parser::parse1() in
296                 // MathParser.cpp).
297                 return;
298         }
299
300         TocBuilder & b = backend.builder("equation");
301         // compute first and last item
302         row_type first = nrows();
303         for (row_type row = 0; row != nrows(); ++row)
304                 if (numbered(row)) {
305                         first = row;
306                         break;
307                 }
308         if (first == nrows())
309                 // no equation
310                 return;
311         row_type last = nrows() - 1;
312         for (; last != 0; --last)
313                 if (numbered(last))
314                         break;
315         // add equation numbers
316         b.pushItem(pit, docstring(), output_active);
317         if (first != last)
318                 b.argumentItem(bformat(from_ascii("(%1$s-%2$s)"),
319                                        numbers_[first], numbers_[last]));
320         for (row_type row = 0; row != nrows(); ++row) {
321                 if (!numbered(row))
322                         continue;
323                 if (label_[row])
324                         label_[row]->addToToc(pit, output_active, utype, backend);
325                 docstring label = nicelabel(row);
326                 if (first == last)
327                         // this is the only equation
328                         b.argumentItem(label);
329                 else {
330                         // insert as sub-items
331                         b.pushItem(pit, label, output_active);
332                         b.pop();
333                 }
334         }
335         b.pop();
336 }
337
338
339 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
340 {
341         if (previewState(&cur.bv())) {
342                 edit(cur, true);
343                 return this;
344         }
345         return InsetMathNest::editXY(cur, x, y);
346 }
347
348
349 InsetMath::mode_type InsetMathHull::currentMode() const
350 {
351         switch (type_) {
352         case hullNone:
353                 return UNDECIDED_MODE;
354
355         // definitely math mode ...
356         case hullUnknown:
357         case hullSimple:
358         case hullEquation:
359         case hullMultline:
360         case hullGather:
361         case hullEqnArray:
362         case hullAlign:
363         case hullFlAlign:
364         case hullAlignAt:
365         case hullXAlignAt:
366         case hullXXAlignAt:
367         case hullRegexp:
368                 return MATH_MODE;
369         }
370         // avoid warning
371         return MATH_MODE;
372 }
373
374
375 // FIXME: InsetMathGrid should be changed to let the real column alignment be
376 // given by a virtual method like displayColAlign, because the values produced
377 // by defaultColAlign can be invalidated by lfuns such as add-column. For the
378 // moment the values produced by defaultColAlign are not used, notably because
379 // alignment is not implemented in the LyXHTML output.
380 char InsetMathHull::defaultColAlign(col_type col)
381 {
382         return colAlign(type_, col);
383 }
384
385
386 char InsetMathHull::displayColAlign(idx_type idx) const
387 {
388         switch (type_) {
389         case hullMultline: {
390                 row_type const r = row(idx);
391                 if (r == 0)
392                         return 'l';
393                 if (r == nrows() - 1)
394                         return 'r';
395                 return 'c';
396         }
397         case hullEqnArray:
398         case hullGather:
399         case hullAlign:
400         case hullAlignAt:
401         case hullXAlignAt:
402         case hullXXAlignAt:
403         case hullFlAlign:
404                 return colAlign(type_, col(idx));
405         default:
406                 break;
407         }
408         return InsetMathGrid::displayColAlign(idx);
409 }
410
411
412 int InsetMathHull::displayColSpace(col_type col) const
413 {
414         return colSpace(type_, col);
415 }
416
417
418 // FIXME: same comment as for defaultColAlign applies.
419 int InsetMathHull::defaultColSpace(col_type col)
420 {
421         return colSpace(type_, col);
422 }
423
424
425 string InsetMathHull::standardFont() const
426 {
427         switch (type_) {
428         case hullRegexp:
429                 return "texttt";
430         case hullNone:
431                 return "lyxnochange";
432         default:
433                 return "mathnormal";
434         }
435 }
436
437
438 ColorCode InsetMathHull::standardColor() const
439 {
440         switch (type_) {
441         case hullRegexp:
442         case hullNone:
443                 return Color_foreground;
444
445         default:
446                 return Color_math;
447         }
448 }
449
450
451 bool InsetMathHull::previewState(const BufferView *const bv) const
452 {
453         if (!editing(bv) && RenderPreview::previewMath()
454             && type_ != hullRegexp)
455         {
456                 graphics::PreviewImage const * pimage =
457                         preview_->getPreviewImage(bv->buffer());
458                 return pimage && pimage->image();
459         }
460         return false;
461 }
462
463
464 namespace {
465 const int ERROR_FRAME_WIDTH = 2;
466
467 bool previewTooSmall(Dimension const & dim)
468 {
469         return dim.width() <= 10 && dim.height() <= 10;
470 }
471 }
472
473
474 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
475 {
476         /* Compute \(above|below)displayskip
477            true value in LaTeX is 10pt plus 2pt minus 5pt (in normal size at 10pt)
478            But we use a fixed number of pixels and scale them with zoom.
479         */
480         int const bottom_display_margin = mi.base.bv->zoomedPixels(6);
481         int top_display_margin = bottom_display_margin;
482         // at start of paragraph, add an empty line
483         if (mi.vmode)
484                 top_display_margin += theFontMetrics(mi.base.font).maxHeight() + 2;
485
486         if (previewState(mi.base.bv)) {
487                 preview_->metrics(mi, dim);
488                 if (previewTooSmall(dim)) {
489                         // preview image is too small
490                         dim.wid += 2 * ERROR_FRAME_WIDTH;
491                         dim.asc += 2 * ERROR_FRAME_WIDTH;
492                 } else {
493                         // insert a gap in front of the formula
494                         // value was hardcoded to 1 pixel
495                         dim.wid += mi.base.bv->zoomedPixels(1) ;
496                         if (display()) {
497                                 dim.asc += top_display_margin;
498                                 dim.des += bottom_display_margin;
499                         }
500                 }
501                 return;
502         }
503
504         {
505                 Changer dummy1 = mi.base.changeFontSet(standardFont());
506                 Changer dummy2 = mi.base.font.changeStyle(display() ? DISPLAY_STYLE
507                                                                                                   : TEXT_STYLE);
508
509                 // let the cells adjust themselves
510                 InsetMathGrid::metrics(mi, dim);
511         }
512
513         // Check whether the numbering interferes with the equations
514         if (numberedType()) {
515                 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
516                 int extra_offset = 0;
517                 for (row_type row = 0; row < nrows(); ++row) {
518                         rowinfo(row).offset[mi.base.bv] += extra_offset;
519                         docstring const nl = nicelabel(row);
520                         if (nl.empty())
521                                 continue;
522                         Dimension dimnl;
523                         mathed_string_dim(mi.base.font, nl, dimnl);
524                         int const ind = indent(*mi.base.bv);
525                         int const x = ind ? ind : (mi.base.textwidth - dim.wid) / 2;
526                         // for some reason metrics does not trigger at the
527                         // same point as draw, and therefore we use >= instead of >
528                         if ((math_number == BufferParams::LEFT && dimnl.wid >= x)
529                             || (math_number == BufferParams::RIGHT
530                                 && dimnl.wid >= mi.base.textwidth - x - dim.wid)) {
531                                 extra_offset += dimnl.height();
532                         }
533                 }
534                 dim.des += extra_offset;
535         }
536
537
538         if (display()) {
539                 dim.asc += top_display_margin;
540                 dim.des += bottom_display_margin;
541         }
542
543         // reserve some space for marker.
544         dim.wid += 2;
545 }
546
547
548 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
549 {
550         BufferView const * const bv = pi.base.bv;
551         if (previewState(bv)) {
552                 Dimension const dim = dimension(*pi.base.bv);
553                 if (previewTooSmall(dim))
554                         return Color_error;
555                 return graphics::PreviewLoader::backgroundColor();
556         }
557         return Color_mathbg;
558 }
559
560
561 void InsetMathHull::drawMarkers(PainterInfo & pi, int x, int y) const
562 {
563         ColorCode pen_color = mouseHovered(pi.base.bv) || editing(pi.base.bv)?
564                 Color_mathframe : Color_mathcorners;
565         // If the corners have the same color as the background, do not paint them.
566         if (lcolor.getX11HexName(Color_mathbg) == lcolor.getX11HexName(pen_color))
567                 return;
568
569         Inset::drawMarkers(pi, x, y);
570         Dimension const dim = dimension(*pi.base.bv);
571         int const t = x + dim.width() - 1;
572         int const a = y - dim.ascent();
573         pi.pain.line(x, a + 3, x, a, pen_color);
574         pi.pain.line(t, a + 3, t, a, pen_color);
575         pi.pain.line(x, a, x + 3, a, pen_color);
576         pi.pain.line(t - 3, a, t, a, pen_color);
577 }
578
579
580 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
581 {
582         Dimension const dim = dimension(*pi.base.bv);
583         if (previewTooSmall(dim)) {
584                 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
585                     dim.wid, dim.asc + dim.des, backgroundColor(pi));
586                 return;
587         }
588
589         pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
590                               dim.height() - 1, pi.backgroundColor(this));
591 }
592
593
594 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
595 {
596         BufferView const * const bv = pi.base.bv;
597         Dimension const dim = dimension(*bv);
598
599         if (type_ == hullRegexp)
600                 pi.pain.rectangle(x + 2, y - dim.ascent() + 1,
601                                   dim.width() - 3, dim.height() - 2, Color_regexpframe);
602
603         if (previewState(bv)) {
604                 // Do not draw change tracking cue if taken care of by RowPainter
605                 // already.
606                 Changer dummy = !canPaintChange(*bv) ? changeVar(pi.change, Change())
607                         : noChange();
608                 if (previewTooSmall(dim)) {
609                         // we have an extra frame
610                         preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
611                 } else {
612                         // one pixel gap in front
613                         // value was hardcoded to 1 pixel
614                         int const gap = pi.base.bv->zoomedPixels(1) ;
615                         preview_->draw(pi, x + gap, y);
616                 }
617                 return;
618         }
619
620         // First draw the numbers
621         if (numberedType()) {
622                 BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
623                 for (row_type row = 0; row < nrows(); ++row) {
624                         int yy = y + rowinfo(row).offset[bv];
625                         docstring const nl = nicelabel(row);
626                         Dimension dimnl;
627                         mathed_string_dim(pi.base.font, nl, dimnl);
628                         if (math_number == BufferParams::LEFT) {
629                                 ColorCode const col = pi.selected_left
630                                         ? Color_selectiontext
631                                         : pi.base.font.color();
632                                 Changer dummy0 = pi.base.font.changeColor(col);
633                                 if (dimnl.wid > x - pi.leftx)
634                                         yy += rowinfo(row).descent + dimnl.asc;
635                                 pi.pain.fillRectangle(pi.leftx, yy - dimnl.asc,
636                                         dimnl.width(), dimnl.height(),
637                                         pi.selected_left ? Color_selection : pi.background_color);
638                                 pi.draw(pi.leftx, yy, nl);
639                         } else {
640                                 ColorCode const col = pi.selected_right
641                                         ? Color_selectiontext
642                                         : pi.base.font.color();
643                                 Changer dummy0 = pi.base.font.changeColor(col);
644                                 if (dimnl.wid > pi.rightx - x - dim.wid)
645                                         yy += rowinfo(row).descent + dimnl.asc;
646                                 pi.pain.fillRectangle(pi.rightx - dimnl.wid, yy - dimnl.asc,
647                                         dimnl.width(), dimnl.height(),
648                                         pi.selected_right ? Color_selection : pi.background_color);
649                                 pi.draw(pi.rightx - dimnl.wid, yy, nl);
650                         }
651                 }
652         }
653
654         // Then the equations
655         ColorCode color = pi.selected && lyxrc.use_system_colors
656                 ? Color_selectiontext : standardColor();
657         bool const really_change_color = pi.base.font.color() == Color_none;
658         Changer dummy0 = really_change_color ? pi.base.font.changeColor(color)
659                 : noChange();
660         Changer dummy1 = pi.base.changeFontSet(standardFont());
661         Changer dummy2 = pi.base.font.changeStyle(display() ? DISPLAY_STYLE
662                                                             : TEXT_STYLE);
663         InsetMathGrid::draw(pi, x + 1, y);
664         drawMarkers(pi, x, y);
665
666         // drawing change line
667         if (canPaintChange(*bv)) {
668                 // like in metrics()
669                 int const display_margin = display() ? pi.base.inPixels(Length(12, Length::PT)) : 0;
670                 pi.change.paintCue(pi, x + 1, y + 1 - dim.asc + display_margin,
671                                     x + dim.wid, y + dim.des - display_margin);
672         }
673 }
674
675
676 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
677 {
678         if (display()) {
679                 InsetMathGrid::metricsT(mi, dim);
680         } else {
681                 odocstringstream os;
682                 otexrowstream ots(os);
683                 TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault);
684                 write(wi);
685                 dim.wid = os.str().size();
686                 dim.asc = 1;
687                 dim.des = 0;
688         }
689 }
690
691
692 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
693 {
694         if (display()) {
695                 InsetMathGrid::drawT(pain, x, y);
696         } else {
697                 odocstringstream os;
698                 otexrowstream ots(os);
699                 TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault);
700                 write(wi);
701                 pain.draw(x, y, os.str().c_str());
702         }
703 }
704
705
706 static docstring latexString(InsetMathHull const & inset)
707 {
708         odocstringstream ls;
709         // This has to be static, because a preview snippet or a math
710         // macro containing math in text mode (such as $\text{$\phi$}$ or
711         // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
712         // first time as a whole, and the second time only the inner math.
713         // In this last case inset.buffer() would be invalid.
714         static Encoding const * encoding = 0;
715         if (inset.isBufferValid())
716                 encoding = &(inset.buffer().params().encoding());
717         otexrowstream ots(ls);
718         TeXMathStream wi(ots, false, true, TeXMathStream::wsPreview, encoding);
719         inset.write(wi);
720         return ls.str();
721 }
722
723
724 void InsetMathHull::initUnicodeMath() const
725 {
726         // Trigger classification of the unicode symbols in this inset
727         docstring const dummy = latexString(*this);
728 }
729
730
731 void InsetMathHull::addPreview(DocIterator const & inset_pos,
732         graphics::PreviewLoader & /*ploader*/) const
733 {
734         if (RenderPreview::previewMath()) {
735                 preparePreview(inset_pos);
736         }
737 }
738
739
740 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
741                                MacroNameSet & macros, MacroNameSet & defs) const
742 {
743         MacroNameSet::iterator const end = macros.end();
744
745         for (size_t i = 0; i < md.size(); ++i) {
746                 InsetMathMacro const * mi = md[i].nucleus()->asMacro();
747                 InsetMathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
748                 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
749                 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
750                 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
751                 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
752                 if (mi) {
753                         // Look for macros in the arguments of this macro.
754                         for (idx_type idx = 0; idx < mi->nargs(); ++idx)
755                                 usedMacros(mi->cell(idx), pos, macros, defs);
756                         // Make sure this is a macro defined in the document
757                         // (as we also spot the macros in the symbols file)
758                         // or that we have not already accounted for it.
759                         docstring const name = mi->name();
760                         if (macros.find(name) == end)
761                                 continue;
762                         macros.erase(name);
763                         // Look for macros in the definition of this macro.
764                         MathData ar(pos.buffer());
765                         MacroData const * data =
766                                 pos.buffer()->getMacro(name, pos, true);
767                         if (data) {
768                                 odocstringstream macro_def;
769                                 data->write(macro_def, true);
770                                 macro_def << endl;
771                                 defs.insert(macro_def.str());
772                                 asArray(data->definition(), ar);
773                         }
774                         usedMacros(ar, pos, macros, defs);
775                 } else if (mt) {
776                         MathData ar(pos.buffer());
777                         asArray(mt->definition(), ar);
778                         usedMacros(ar, pos, macros, defs);
779                 } else if (si) {
780                         if (!si->nuc().empty())
781                                 usedMacros(si->nuc(), pos, macros, defs);
782                         if (si->hasDown())
783                                 usedMacros(si->down(), pos, macros, defs);
784                         if (si->hasUp())
785                                 usedMacros(si->up(), pos, macros, defs);
786                 } else if (fi || gi) {
787                         idx_type nidx = fi ? fi->nargs() : gi->nargs();
788                         for (idx_type idx = 0; idx < nidx; ++idx)
789                                 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
790                                            pos, macros, defs);
791                 } else if (ni) {
792                         usedMacros(ni->cell(0), pos, macros, defs);
793                 }
794         }
795 }
796
797
798 void InsetMathHull::preparePreview(DocIterator const & pos,
799                                    bool forexport) const
800 {
801         // there is no need to do all the macro stuff if we're not
802         // actually going to generate the preview.
803         if (!RenderPreview::previewMath() && !forexport)
804                 return;
805
806         Buffer const * buffer = pos.buffer();
807
808         // collect macros at this position
809         MacroNameSet macros;
810         buffer->listMacroNames(macros);
811
812         // collect definitions only for the macros used in this inset
813         MacroNameSet defs;
814         for (idx_type idx = 0; idx < nargs(); ++idx)
815                 usedMacros(cell(idx), pos, macros, defs);
816
817         docstring macro_preamble;
818         for (auto const & defvar : defs)
819                 macro_preamble.append(defvar);
820
821         // set the font series and size for this snippet
822         DocIterator dit = pos.getInnerText();
823         Paragraph const & par = dit.paragraph();
824         Font font = par.getFontSettings(buffer->params(), dit.pos());
825         font.fontInfo().realize(par.layout().font);
826         string const lsize = font.latexSize();
827         docstring setfont;
828         docstring endfont;
829         if (font.fontInfo().series() == BOLD_SERIES) {
830                 setfont += from_ascii("\\textbf{");
831                 endfont += '}';
832         }
833         if (lsize != "normalsize" && !prefixIs(lsize, "error"))
834                 setfont += from_ascii("\\" + lsize + '\n');
835
836         docstring const snippet = macro_preamble + setfont + latexString(*this) + endfont;
837         LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
838         preview_->addPreview(snippet, *buffer, forexport);
839 }
840
841
842 void InsetMathHull::reloadPreview(DocIterator const & pos) const
843 {
844         preparePreview(pos);
845         preview_->startLoading(*pos.buffer());
846 }
847
848
849 void InsetMathHull::loadPreview(DocIterator const & pos) const
850 {
851         bool const forexport = true;
852         preparePreview(pos, forexport);
853         preview_->startLoading(*pos.buffer(), forexport);
854 }
855
856
857 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
858 {
859         if (RenderPreview::previewMath()) {
860                 reloadPreview(old);
861                 cur.screenUpdateFlags(Update::Force);
862         }
863         return false;
864 }
865
866
867 docstring InsetMathHull::label(row_type row) const
868 {
869         LASSERT(row < nrows(), return docstring());
870         if (InsetLabel * il = label_[row])
871                 return il->screenLabel();
872         return docstring();
873 }
874
875
876 void InsetMathHull::label(row_type row, docstring const & label)
877 {
878         //lyxerr << "setting label '" << label << "' for row " << row << endl;
879         if (label_[row]) {
880                 if (label.empty()) {
881                         delete label_[row];
882                         label_[row] = dummy_pointer;
883                 } else {
884                         if (buffer_)
885                                 label_[row]->updateLabelAndRefs(label);
886                         else
887                                 label_[row]->setParam("name", label);
888                 }
889                 return;
890         }
891         InsetCommandParams p(LABEL_CODE);
892         p["name"] = label;
893         label_[row] = new InsetLabel(buffer_, p);
894         if (buffer_)
895                 label_[row]->setBuffer(buffer());
896 }
897
898
899 void InsetMathHull::numbered(row_type row, Numbered num)
900 {
901         numbered_[row] = num;
902 }
903
904
905 bool InsetMathHull::numbered(row_type row) const
906 {
907         return numbered_[row] == NUMBER;
908 }
909
910
911 bool InsetMathHull::ams() const
912 {
913         switch (type_) {
914         case hullAlign:
915         case hullFlAlign:
916         case hullMultline:
917         case hullGather:
918         case hullAlignAt:
919         case hullXAlignAt:
920         case hullXXAlignAt:
921                 return true;
922         case hullUnknown:
923         case hullRegexp:
924                 return false;
925         case hullNone:
926         case hullSimple:
927         case hullEquation:
928         case hullEqnArray:
929                 break;
930         }
931         for (auto const & row : numbered_)
932                 if (row == NOTAG)
933                         return true;
934         return false;
935 }
936
937
938 bool InsetMathHull::outerDisplay() const
939 {
940         switch (type_) {
941         case hullEquation:
942         case hullEqnArray:
943         case hullAlign:
944         case hullFlAlign:
945         case hullGather:
946         case hullMultline:
947                 return true;
948         case hullNone:
949         case hullSimple:
950         case hullAlignAt:
951         case hullXAlignAt:
952         case hullXXAlignAt:
953         case hullUnknown:
954         case hullRegexp:
955                 break;
956         }
957         return false;
958 }
959
960
961 int InsetMathHull::rowFlags() const
962 {
963         switch (type_) {
964         case hullUnknown:
965         case hullSimple:
966         case hullNone:
967         case hullRegexp:
968                 return Inline;
969         case hullEqnArray:
970         case hullAlign:
971         case hullFlAlign:
972         case hullAlignAt:
973         case hullXAlignAt:
974         case hullXXAlignAt:
975         case hullEquation:
976         case hullMultline:
977         case hullGather:
978                 if (buffer().params().is_math_indent)
979                         return Display | AlignLeft;
980                 else
981                         return Display;
982         }
983         // avoid warning
984         return Display;
985 }
986
987
988 int InsetMathHull::indent(BufferView const & bv) const
989 {
990         // FIXME: set this in the textclass. This value is what the article class uses.
991         static Length default_indent(2.5, Length::EM);
992         if (display() && buffer().params().is_math_indent) {
993                 Length const & len = buffer().params().getMathIndent();
994                 if (len.empty())
995                         return bv.inPixels(default_indent);
996                 else
997                         return bv.inPixels(len);
998         } else
999                 return Inset::indent(bv);
1000 }
1001
1002
1003 bool InsetMathHull::numberedType() const
1004 {
1005         switch (type_) {
1006         case hullUnknown:
1007         case hullNone:
1008         case hullSimple:
1009         case hullXXAlignAt:
1010         case hullRegexp:
1011                 return false;
1012         case hullEqnArray:
1013         case hullAlign:
1014         case hullFlAlign:
1015         case hullAlignAt:
1016         case hullXAlignAt:
1017         case hullEquation:
1018         case hullMultline:
1019         case hullGather:
1020                 break;
1021         }
1022         for (row_type row = 0; row < nrows(); ++row)
1023                 if (numbered(row))
1024                         return true;
1025         return false;
1026 }
1027
1028
1029 void InsetMathHull::validate(LaTeXFeatures & features) const
1030 {
1031         if (features.runparams().isLaTeX()) {
1032                 if (ams())
1033                         features.require("amsmath");
1034
1035                 if (type_ == hullRegexp) {
1036                         features.require("color");
1037                         docstring frcol = from_utf8(lcolor.getLaTeXName(Color_regexpframe));
1038                         docstring bgcol = from_ascii("white");
1039                         features.addPreambleSnippet(
1040                                 "\\newcommand{\\regexp}[1]{\\fcolorbox{"
1041                                 + frcol + "}{"
1042                                 + bgcol + "}{\\ensuremath{\\mathtt{#1}}}}");
1043                         features.addPreambleSnippet(
1044                                 from_ascii("\\newcommand{\\endregexp}{}"));
1045                 } else if (outerDisplay() && features.inDeletedInset()) {
1046                                 features.require("tikz");
1047                                 features.require("ct-tikz-object-sout");
1048                 }
1049
1050                 // Validation is necessary only if not using AMS math.
1051                 // To be safe, we will always run mathedvalidate.
1052                 //if (features.amsstyle)
1053                 //  return;
1054
1055                 //features.binom      = true;
1056         } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
1057                 // it would be better to do this elsewhere, but we can't validate in
1058                 // InsetMathMatrix and we have no way, outside MathExtern, to know if
1059                 // we even have any matrices.
1060                                 features.addCSSSnippet(
1061                                         "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
1062                                         "table.matrix td{padding: 0.25px;}\n"
1063                                         "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
1064                                         "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
1065         }
1066         InsetMathGrid::validate(features);
1067 }
1068
1069
1070 CtObject InsetMathHull::getCtObject(OutputParams const & runparams) const
1071 {
1072         CtObject res = CtObject::Normal;
1073         switch(type_) {
1074         case hullNone:
1075         case hullSimple:
1076         case hullAlignAt:
1077         case hullXAlignAt:
1078         case hullXXAlignAt:
1079         case hullRegexp:
1080         case hullUnknown:
1081                 break;
1082
1083         case hullEquation:
1084         case hullEqnArray:
1085         case hullAlign:
1086         case hullFlAlign:
1087         case hullGather:
1088         case hullMultline: {
1089                 if (runparams.inulemcmd
1090                     && (!runparams.local_font || runparams.local_font->fontInfo().strikeout() != FONT_ON))
1091                         res = CtObject::UDisplayObject;
1092                 else
1093                         res = CtObject::DisplayObject;
1094                 break;
1095                 }
1096         }
1097         return res;
1098 }
1099
1100
1101 void InsetMathHull::header_write(TeXMathStream & os) const
1102 {
1103         bool n = numberedType();
1104
1105         switch(type_) {
1106         case hullNone:
1107                 break;
1108
1109         case hullSimple:
1110                 if (os.ulemCmd())
1111                         os << "\\mbox{";
1112                 os << '$';
1113                 os.startOuterRow();
1114                 if (cell(0).empty())
1115                         os << ' ';
1116                 break;
1117
1118         case hullEquation:
1119                 writeMathdisplayPreamble(os);
1120                 os << "\n";
1121                 os.startOuterRow();
1122                 if (n)
1123                         os << "\\begin{equation" << star(n) << "}\n";
1124                 else
1125                         os << "\\[\n";
1126                 break;
1127
1128         case hullEqnArray:
1129         case hullAlign:
1130         case hullFlAlign:
1131         case hullGather:
1132         case hullMultline:
1133                 writeMathdisplayPreamble(os);
1134                 os << "\n";
1135                 os.startOuterRow();
1136                 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1137                 break;
1138
1139         case hullAlignAt:
1140         case hullXAlignAt:
1141                 os << "\n";
1142                 os.startOuterRow();
1143                 os << "\\begin{" << hullName(type_) << star(n) << '}'
1144                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1145                 break;
1146
1147         case hullXXAlignAt:
1148                 os << "\n";
1149                 os.startOuterRow();
1150                 os << "\\begin{" << hullName(type_) << '}'
1151                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1152                 break;
1153
1154         case hullRegexp:
1155                 os << "\\regexp{";
1156                 break;
1157
1158         case hullUnknown:
1159                 os << "\n";
1160                 os.startOuterRow();
1161                 os << "\\begin{unknown" << star(n) << "}\n";
1162                 break;
1163         }
1164 }
1165
1166
1167 void InsetMathHull::footer_write(TeXMathStream & os) const
1168 {
1169         bool n = numberedType();
1170
1171         switch(type_) {
1172         case hullNone:
1173                 os << "\n";
1174                 break;
1175
1176         case hullSimple:
1177                 os << '$';
1178                 if (os.ulemCmd())
1179                         os << "}";
1180                 break;
1181
1182         case hullEquation:
1183                 os << "\n";
1184                 os.startOuterRow();
1185                 if (n)
1186                         os << "\\end{equation" << star(n) << "}\n";
1187                 else
1188                         os << "\\]\n";
1189                 writeMathdisplayPostamble(os);
1190                 break;
1191
1192         case hullEqnArray:
1193         case hullAlign:
1194         case hullFlAlign:
1195         case hullGather:
1196         case hullMultline:
1197                 os << "\n";
1198                 os.startOuterRow();
1199                 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1200                 writeMathdisplayPostamble(os);
1201                 break;
1202
1203         case hullAlignAt:
1204         case hullXAlignAt:
1205                 os << "\n";
1206                 os.startOuterRow();
1207                 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1208                 break;
1209
1210         case hullXXAlignAt:
1211                 os << "\n";
1212                 os.startOuterRow();
1213                 os << "\\end{" << hullName(type_) << "}\n";
1214                 break;
1215
1216         case hullRegexp:
1217                 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1218                 os << "\\endregexp{}}";
1219                 break;
1220
1221         case hullUnknown:
1222                 os << "\n";
1223                 os.startOuterRow();
1224                 os << "\\end{unknown" << star(n) << "}\n";
1225                 break;
1226         }
1227 }
1228
1229
1230 bool InsetMathHull::allowsTabularFeatures() const
1231 {
1232         switch (type_) {
1233         case hullEqnArray:
1234         case hullAlign:
1235         case hullAlignAt:
1236         case hullXAlignAt:
1237         case hullXXAlignAt:
1238         case hullFlAlign:
1239         case hullMultline:
1240         case hullGather:
1241                 return true;
1242         case hullNone:
1243         case hullSimple:
1244         case hullEquation:
1245         case hullRegexp:
1246         case hullUnknown:
1247                 break;
1248         }
1249         return false;
1250 }
1251
1252
1253 bool InsetMathHull::rowChangeOK() const
1254 {
1255         return
1256                 type_ == hullEqnArray || type_ == hullAlign ||
1257                 type_ == hullFlAlign || type_ == hullAlignAt ||
1258                 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1259                 type_ == hullGather || type_ == hullMultline;
1260 }
1261
1262
1263 bool InsetMathHull::colChangeOK() const
1264 {
1265         return
1266                 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1267                 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1268 }
1269
1270
1271 void InsetMathHull::addRow(row_type row)
1272 {
1273         if (!rowChangeOK())
1274                 return;
1275
1276         bool numbered = numberedType();
1277         // Move the number and raw pointer, do not call label() (bug 7511)
1278         InsetLabel * label = dummy_pointer;
1279         docstring number = empty_docstring();
1280         if (type_ == hullMultline) {
1281                 if (row + 1 == nrows())  {
1282                         numbered_[row] = NONUMBER;
1283                         swap(label, label_[row]);
1284                         swap(number, numbers_[row]);
1285                 } else
1286                         numbered = false;
1287         }
1288
1289         numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1290         numbers_.insert(numbers_.begin() + row + 1, number);
1291         label_.insert(label_.begin() + row + 1, label);
1292         InsetMathGrid::addRow(row);
1293 }
1294
1295
1296 void InsetMathHull::swapRow(row_type row)
1297 {
1298         if (nrows() <= 1)
1299                 return;
1300         if (row + 1 == nrows())
1301                 --row;
1302         swap(numbered_[row], numbered_[row + 1]);
1303         swap(numbers_[row], numbers_[row + 1]);
1304         swap(label_[row], label_[row + 1]);
1305         InsetMathGrid::swapRow(row);
1306 }
1307
1308
1309 void InsetMathHull::delRow(row_type row)
1310 {
1311         if (nrows() <= 1 || !rowChangeOK())
1312                 return;
1313         if (row + 1 == nrows() && type_ == hullMultline) {
1314                 swap(numbered_[row - 1], numbered_[row]);
1315                 swap(numbers_[row - 1], numbers_[row]);
1316                 swap(label_[row - 1], label_[row]);
1317                 InsetMathGrid::delRow(row);
1318                 return;
1319         }
1320         InsetMathGrid::delRow(row);
1321         // The last dummy row has no number info nor a label.
1322         // Test nrows() + 1 because we have already erased the row.
1323         if (row == nrows() + 1)
1324                 row--;
1325         numbered_.erase(numbered_.begin() + row);
1326         numbers_.erase(numbers_.begin() + row);
1327         delete label_[row];
1328         label_.erase(label_.begin() + row);
1329 }
1330
1331
1332 void InsetMathHull::addCol(col_type col)
1333 {
1334         if (!colChangeOK())
1335                 return;
1336         InsetMathGrid::addCol(col);
1337 }
1338
1339
1340 void InsetMathHull::delCol(col_type col)
1341 {
1342         if (ncols() <= 1 || !colChangeOK())
1343                 return;
1344         InsetMathGrid::delCol(col);
1345 }
1346
1347
1348 docstring InsetMathHull::nicelabel(row_type row) const
1349 {
1350         if (!numbered(row)) {
1351                 if (!label_[row])
1352                         return docstring();
1353                 return '[' + label_[row]->screenLabel() + ']';
1354         }
1355         docstring const & val = numbers_[row];
1356         if (!label_[row])
1357                 return '(' + val + ')';
1358         return '(' + val + ',' + label_[row]->screenLabel() + ')';
1359 }
1360
1361
1362 void InsetMathHull::glueall(HullType type)
1363 {
1364         MathData ar;
1365         for (idx_type i = 0; i < nargs(); ++i)
1366                 ar.append(cell(i));
1367         InsetLabel * label = 0;
1368         if (type == hullEquation) {
1369                 // preserve first non-empty label
1370                 for (row_type row = 0; row < nrows(); ++row) {
1371                         if (label_[row]) {
1372                                 label = label_[row];
1373                                 label_[row] = 0;
1374                                 break;
1375                         }
1376                 }
1377         }
1378         *this = InsetMathHull(buffer_, hullSimple);
1379         label_[0] = label;
1380         cell(0) = ar;
1381         setDefaults();
1382 }
1383
1384
1385 void InsetMathHull::splitTo2Cols()
1386 {
1387         LASSERT(ncols() == 1, return);
1388         InsetMathGrid::addCol(1);
1389         for (row_type row = 0; row < nrows(); ++row) {
1390                 idx_type const i = 2 * row;
1391                 pos_type pos = firstRelOp(cell(i));
1392                 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1393                 cell(i).erase(pos, cell(i).size());
1394         }
1395 }
1396
1397
1398 void InsetMathHull::splitTo3Cols()
1399 {
1400         LASSERT(ncols() < 3, return);
1401         if (ncols() < 2)
1402                 splitTo2Cols();
1403         InsetMathGrid::addCol(2);
1404         for (row_type row = 0; row < nrows(); ++row) {
1405                 idx_type const i = 3 * row + 1;
1406                 if (!cell(i).empty()) {
1407                         cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1408                         cell(i).erase(1, cell(i).size());
1409                 }
1410         }
1411 }
1412
1413
1414 void InsetMathHull::changeCols(col_type cols)
1415 {
1416         if (ncols() == cols)
1417                 return;
1418         else if (ncols() < cols) {
1419                 // split columns
1420                 if (cols < 3)
1421                         splitTo2Cols();
1422                 else {
1423                         splitTo3Cols();
1424                         while (ncols() < cols)
1425                                 InsetMathGrid::addCol(ncols());
1426                 }
1427                 return;
1428         }
1429
1430         // combine columns
1431         for (row_type row = 0; row < nrows(); ++row) {
1432                 idx_type const i = row * ncols();
1433                 for (col_type col = cols; col < ncols(); ++col) {
1434                         cell(i + cols - 1).append(cell(i + col));
1435                 }
1436         }
1437         // delete columns
1438         while (ncols() > cols) {
1439                 InsetMathGrid::delCol(ncols() - 1);
1440         }
1441 }
1442
1443
1444 HullType InsetMathHull::getType() const
1445 {
1446         return type_;
1447 }
1448
1449
1450 void InsetMathHull::setType(HullType type)
1451 {
1452         type_ = type;
1453         setDefaults();
1454 }
1455
1456
1457 bool InsetMathHull::isMutable(HullType type)
1458 {
1459         switch (type) {
1460         case hullNone:
1461         case hullSimple:
1462         case hullEquation:
1463         case hullEqnArray:
1464         case hullAlign:
1465         case hullFlAlign:
1466         case hullAlignAt:
1467         case hullXAlignAt:
1468         case hullXXAlignAt:
1469         case hullMultline:
1470         case hullGather:
1471                 return true;
1472         case hullUnknown:
1473         case hullRegexp:
1474                 return false;
1475         }
1476         // avoid warning
1477         return false;
1478 }
1479
1480
1481 void InsetMathHull::mutate(HullType newtype)
1482 {
1483         //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1484
1485         if (newtype == type_)
1486                 return;
1487
1488         // This guards the algorithm below it, which is designed with certain types
1489         // in mind.
1490         if (!isMutable(newtype) || !isMutable(type_)) {
1491                 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1492                        << "' to '" << to_utf8(hullName(newtype))
1493                        << "' not implemented" << endl;
1494                 return;
1495         }
1496
1497         // we try to move along the chain
1498         // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1499         //                                     ^                                     |
1500         //                                     +-------------------------------------+
1501         // we use eqnarray as intermediate type for mutations that are not
1502         // directly supported because it handles labels and numbering for
1503         // "down mutation".
1504
1505         switch (type_) {
1506         case hullNone:
1507                 setType(hullSimple);
1508                 numbered(0, false);
1509                 mutate(newtype);
1510                 break;
1511
1512         case hullSimple:
1513                 if (newtype == hullNone) {
1514                         setType(hullNone);
1515                         numbered(0, false);
1516                 } else {
1517                         setType(hullEquation);
1518                         numbered(0, label_[0] != nullptr);
1519                         mutate(newtype);
1520                 }
1521                 break;
1522
1523         case hullEquation:
1524                 switch (newtype) {
1525                 case hullNone:
1526                 case hullSimple:
1527                         setType(hullSimple);
1528                         numbered(0, false);
1529                         mutate(newtype);
1530                         break;
1531                 case hullEqnArray:
1532                         // split it "nicely" on the first relop
1533                         splitTo3Cols();
1534                         setType(hullEqnArray);
1535                         break;
1536                 case hullMultline:
1537                 case hullGather:
1538                         setType(newtype);
1539                         break;
1540                 default:
1541                         // *align*
1542                         // split it "nicely"
1543                         splitTo2Cols();
1544                         setType(hullAlign);
1545                         mutate(newtype);
1546                         break;
1547                 }
1548                 break;
1549
1550         case hullEqnArray:
1551                 switch (newtype) {
1552                 case hullNone:
1553                 case hullSimple:
1554                 case hullEquation:
1555                         glueall(newtype);
1556                         mutate(newtype);
1557                         break;
1558                 default:
1559                         // align & Co.
1560                         changeCols(2);
1561                         setType(hullAlign);
1562                         mutate(newtype);
1563                         break;
1564                 }
1565                 break;
1566
1567         case hullAlign:
1568         case hullAlignAt:
1569         case hullXAlignAt:
1570         case hullFlAlign:
1571                 switch (newtype) {
1572                 case hullNone:
1573                 case hullSimple:
1574                 case hullEquation:
1575                 case hullEqnArray:
1576                         changeCols(3);
1577                         setType(hullEqnArray);
1578                         mutate(newtype);
1579                         break;
1580                 case hullGather:
1581                 case hullMultline:
1582                         changeCols(1);
1583                         setType(newtype);
1584                         break;
1585                 case hullXXAlignAt:
1586                         for (row_type row = 0; row < nrows(); ++row)
1587                                 numbered(row, false);
1588                         setType(newtype);
1589                         break;
1590                 default:
1591                         setType(newtype);
1592                         break;
1593                 }
1594                 break;
1595
1596         case hullXXAlignAt:
1597                 for (row_type row = 0; row < nrows(); ++row)
1598                         numbered(row, false);
1599                 switch (newtype) {
1600                 case hullNone:
1601                 case hullSimple:
1602                 case hullEquation:
1603                 case hullEqnArray:
1604                         changeCols(3);
1605                         setType(hullEqnArray);
1606                         mutate(newtype);
1607                         break;
1608                 case hullGather:
1609                 case hullMultline:
1610                         changeCols(1);
1611                         setType(newtype);
1612                         break;
1613                 default:
1614                         setType(newtype);
1615                         break;
1616                 }
1617                 break;
1618
1619         case hullMultline:
1620         case hullGather:
1621                 switch (newtype) {
1622                 case hullGather:
1623                 case hullMultline:
1624                         setType(newtype);
1625                         break;
1626                 case hullAlign:
1627                 case hullFlAlign:
1628                 case hullAlignAt:
1629                 case hullXAlignAt:
1630                         splitTo2Cols();
1631                         setType(newtype);
1632                         break;
1633                 case hullXXAlignAt:
1634                         splitTo2Cols();
1635                         for (row_type row = 0; row < nrows(); ++row)
1636                                 numbered(row, false);
1637                         setType(newtype);
1638                         break;
1639                 default:
1640                         // first we mutate to EqnArray
1641                         splitTo3Cols();
1642                         setType(hullEqnArray);
1643                         mutate(newtype);
1644                         break;
1645                 }
1646                 break;
1647
1648         default:
1649                 // we passed the guard so we should not be here
1650                 LYXERR0("Mutation not implemented, but should have been.");
1651                 LASSERT(false, return);
1652                 break;
1653         }// switch
1654 }
1655
1656
1657 void InsetMathHull::eol(TeXMathStream & os, row_type row, bool fragile, bool latex,
1658                         bool last_eoln) const
1659 {
1660         if (numberedType()) {
1661                 if (label_[row]) {
1662                         docstring const name =
1663                                 latex ? escape(label_[row]->getParam("name"))
1664                                       : label_[row]->getParam("name");
1665                         os << "\\label{" + name + '}';
1666                 }
1667                 if (type_ != hullMultline) {
1668                         if (numbered_[row]  == NONUMBER)
1669                                 os << "\\nonumber ";
1670                         else if (numbered_[row]  == NOTAG)
1671                                 os<< "\\notag ";
1672                 }
1673                 if (os.output() == TeXMathStream::wsPreview && !numbers_[row].empty()) {
1674                         os << "\\global\\def\\theequation{" << numbers_[row] << "}\n";
1675                 }
1676
1677         }
1678         // Never add \\ on the last empty line of eqnarray and friends
1679         last_eoln = false;
1680         InsetMathGrid::eol(os, row, fragile, latex, last_eoln);
1681 }
1682
1683 void InsetMathHull::write(TeXMathStream & os) const
1684 {
1685         ModeSpecifier specifier(os, MATH_MODE);
1686         header_write(os);
1687         InsetMathGrid::write(os);
1688         footer_write(os);
1689 }
1690
1691
1692 void InsetMathHull::normalize(NormalStream & os) const
1693 {
1694         os << "[formula " << hullName(type_) << ' ';
1695         InsetMathGrid::normalize(os);
1696         os << "] ";
1697 }
1698
1699
1700 void InsetMathHull::infoize(odocstream & os) const
1701 {
1702         os << bformat(_("Type: %1$s"), hullName(type_));
1703 }
1704
1705
1706 void InsetMathHull::check() const
1707 {
1708         LATTEST(numbered_.size() == nrows());
1709         LATTEST(numbers_.size() == nrows());
1710         LATTEST(label_.size() == nrows());
1711 }
1712
1713
1714 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1715 {
1716         //FIXME: sort out whether we want std::string or docstring for those
1717         string const lang = func.getArg(0);
1718         docstring extra = from_utf8(func.getArg(1));
1719         if (extra.empty())
1720                 extra = from_ascii("noextra");
1721
1722         // replace selection with result of computation
1723         if (reduceSelectionToOneCell(cur)) {
1724                 MathData ar;
1725                 asArray(grabAndEraseSelection(cur), ar);
1726                 lyxerr << "use selection: " << ar << endl;
1727                 cur.insert(pipeThroughExtern(lang, extra, ar));
1728                 return;
1729         }
1730
1731         // only inline, display or eqnarray math is allowed
1732         switch (getType()) {
1733         case hullSimple:
1734         case hullEquation:
1735         case hullEqnArray:
1736                 break;
1737         default:
1738                 frontend::Alert::warning(_("Bad math environment"),
1739                                 _("Computation cannot be performed for AMS "
1740                                   "math environments.\nChange the math "
1741                                   "formula type and try again."));
1742                 return;
1743         }
1744
1745         MathData eq;
1746         eq.push_back(MathAtom(new InsetMathChar('=')));
1747
1748         // go to first item in line
1749         cur.idx() -= cur.idx() % ncols();
1750         cur.pos() = 0;
1751
1752         if (getType() == hullSimple) {
1753                 size_type pos = cur.cell().find_last(eq);
1754                 MathData ar;
1755                 if (pos == cur.cell().size()) {
1756                         ar = cur.cell();
1757                         lyxerr << "use whole cell: " << ar << endl;
1758                 } else {
1759                         ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1760                         lyxerr << "use partial cell form pos: " << pos << endl;
1761                 }
1762                 cur.cell().append(eq);
1763                 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1764                 cur.pos() = cur.lastpos();
1765                 return;
1766         }
1767
1768         if (getType() == hullEquation) {
1769                 lyxerr << "use equation inset" << endl;
1770                 mutate(hullEqnArray);
1771                 MathData & ar = cur.cell();
1772                 lyxerr << "use cell: " << ar << endl;
1773                 ++cur.idx();
1774                 cur.cell() = eq;
1775                 ++cur.idx();
1776                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1777                 // move to end of line
1778                 cur.pos() = cur.lastpos();
1779                 return;
1780         }
1781
1782         {
1783                 lyxerr << "use eqnarray" << endl;
1784                 cur.idx() += 2 - cur.idx() % ncols();
1785                 cur.pos() = 0;
1786                 MathData ar = cur.cell();
1787                 lyxerr << "use cell: " << ar << endl;
1788                 // FIXME: temporarily disabled
1789                 addRow(cur.row());
1790                 ++cur.idx();
1791                 ++cur.idx();
1792                 cur.cell() = eq;
1793                 ++cur.idx();
1794                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1795                 cur.pos() = cur.lastpos();
1796         }
1797 }
1798
1799
1800 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1801 {
1802         //lyxerr << "action: " << cmd.action() << endl;
1803         switch (cmd.action()) {
1804
1805         case LFUN_FINISHED_BACKWARD:
1806         case LFUN_FINISHED_FORWARD:
1807         case LFUN_FINISHED_RIGHT:
1808         case LFUN_FINISHED_LEFT:
1809                 //lyxerr << "action: " << cmd.action() << endl;
1810                 InsetMathGrid::doDispatch(cur, cmd);
1811                 break;
1812
1813         case LFUN_PARAGRAPH_BREAK:
1814                 // just swallow this
1815                 break;
1816
1817         case LFUN_NEWLINE_INSERT:
1818                 // some magic for the common case
1819                 if (type_ == hullSimple || type_ == hullEquation) {
1820                         cur.recordUndoInset();
1821                         bool const align =
1822                                 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1823                         mutate(align ? hullAlign : hullEqnArray);
1824                         // mutate() may change labels and such.
1825                         cur.forceBufferUpdate();
1826                         cur.idx() = nrows() * ncols() - 1;
1827                         cur.pos() = cur.lastpos();
1828                 }
1829                 InsetMathGrid::doDispatch(cur, cmd);
1830                 break;
1831
1832         case LFUN_MATH_NUMBER_TOGGLE: {
1833                 //lyxerr << "toggling all numbers" << endl;
1834                 cur.recordUndoInset();
1835                 bool old = numberedType();
1836                 if (type_ == hullMultline)
1837                         numbered(nrows() - 1, !old);
1838                 else
1839                         for (row_type row = 0; row < nrows(); ++row)
1840                                 numbered(row, !old);
1841
1842                 cur.message(old ? _("No number") : _("Number"));
1843                 cur.forceBufferUpdate();
1844                 break;
1845         }
1846
1847         case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1848                 cur.recordUndoInset();
1849                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1850                 bool old = numbered(r);
1851                 cur.message(old ? _("No number") : _("Number"));
1852                 numbered(r, !old);
1853                 cur.forceBufferUpdate();
1854                 break;
1855         }
1856
1857         case LFUN_LABEL_INSERT: {
1858                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1859                 docstring old_label = label(r);
1860                 docstring const default_label = from_ascii("eq:");
1861                 if (old_label.empty())
1862                         old_label = default_label;
1863
1864                 InsetCommandParams p(LABEL_CODE);
1865                 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1866                 string const data = InsetCommand::params2string(p);
1867
1868                 if (cmd.argument().empty())
1869                         cur.bv().showDialog("label", data);
1870                 else {
1871                         FuncRequest fr(LFUN_INSET_INSERT, data);
1872                         dispatch(cur, fr);
1873                 }
1874                 break;
1875         }
1876
1877         case LFUN_LABEL_COPY_AS_REFERENCE: {
1878                 row_type row;
1879                 if (cmd.argument().empty() && &cur.inset() == this)
1880                         // if there is no argument and we're inside math, we retrieve
1881                         // the row number from the cursor position.
1882                         row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1883                 else {
1884                         // if there is an argument, find the corresponding label, else
1885                         // check whether there is at least one label.
1886                         for (row = 0; row != nrows(); ++row)
1887                                 if (label_[row]
1888                                           && (cmd.argument().empty() || label(row) == cmd.argument()))
1889                                         break;
1890                 }
1891
1892                 if (row == nrows())
1893                         break;
1894
1895                 InsetCommandParams p(REF_CODE, "ref");
1896                 p["reference"] = label(row);
1897                 cap::clearSelection();
1898                 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1899                 break;
1900         }
1901
1902         case LFUN_WORD_DELETE_FORWARD:
1903         case LFUN_CHAR_DELETE_FORWARD:
1904                 if (col(cur.idx()) + 1 == ncols()
1905                     && cur.pos() == cur.lastpos()
1906                     && !cur.selection()) {
1907                         if (!label(row(cur.idx())).empty()) {
1908                                 cur.recordUndoInset();
1909                                 label(row(cur.idx()), docstring());
1910                         } else if (numbered(row(cur.idx()))) {
1911                                 cur.recordUndoInset();
1912                                 numbered(row(cur.idx()), false);
1913                                 cur.forceBufferUpdate();
1914                         } else {
1915                                 InsetMathGrid::doDispatch(cur, cmd);
1916                                 return;
1917                         }
1918                 } else {
1919                         InsetMathGrid::doDispatch(cur, cmd);
1920                         return;
1921                 }
1922                 break;
1923
1924         case LFUN_INSET_INSERT: {
1925                 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1926                 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1927                 string const name = cmd.getArg(0);
1928                 if (name == "label") {
1929                         InsetCommandParams p(LABEL_CODE);
1930                         InsetCommand::string2params(to_utf8(cmd.argument()), p);
1931                         docstring str = p["name"];
1932                         cur.recordUndoInset();
1933                         row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1934                         str = trim(str);
1935                         if (!str.empty())
1936                                 numbered(r, true);
1937                         docstring old = label(r);
1938                         if (str != old) {
1939                                 if (label_[r])
1940                                         // The label will take care of the reference update.
1941                                         label(r, str);
1942                                 else {
1943                                         label(r, str);
1944                                         // Newly created inset so initialize it.
1945                                         label_[r]->initView();
1946                                 }
1947                         }
1948                         cur.forceBufferUpdate();
1949                         break;
1950                 }
1951                 InsetMathGrid::doDispatch(cur, cmd);
1952                 return;
1953         }
1954
1955         case LFUN_MATH_EXTERN:
1956                 cur.recordUndoInset();
1957                 doExtern(cur, cmd);
1958                 break;
1959
1960         case LFUN_MATH_MUTATE: {
1961                 cur.recordUndoInset();
1962                 row_type row = cur.row();
1963                 col_type col = cur.col();
1964                 mutate(hullType(cmd.argument()));
1965                 cur.idx() = row * ncols() + col;
1966                 if (cur.idx() > cur.lastidx()) {
1967                         cur.idx() = cur.lastidx();
1968                         cur.pos() = cur.lastpos();
1969                 }
1970                 if (cur.pos() > cur.lastpos())
1971                         cur.pos() = cur.lastpos();
1972
1973                 cur.forceBufferUpdate();
1974                 // FIXME: find some more clever handling of the selection,
1975                 // i.e. preserve it.
1976                 cur.clearSelection();
1977                 //cur.dispatched(FINISHED);
1978                 break;
1979         }
1980
1981         case LFUN_MATH_DISPLAY: {
1982                 cur.recordUndoInset();
1983                 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1984                 // if the cursor is in a cell that got merged, move it to
1985                 // start of the hull inset.
1986                 if (cur.idx() > 0) {
1987                         cur.idx() = 0;
1988                         cur.pos() = 0;
1989                 }
1990                 if (cur.pos() > cur.lastpos())
1991                         cur.pos() = cur.lastpos();
1992
1993                 break;
1994         }
1995
1996         case LFUN_TABULAR_FEATURE:
1997                 if (!allowsTabularFeatures())
1998                         cur.undispatched();
1999                 else
2000                         InsetMathGrid::doDispatch(cur, cmd);
2001                 break;
2002
2003         default:
2004                 InsetMathGrid::doDispatch(cur, cmd);
2005                 break;
2006         }
2007 }
2008
2009
2010 namespace {
2011
2012 bool allowDisplayMath(Cursor const & cur)
2013 {
2014         LATTEST(cur.depth() > 1);
2015         Cursor tmpcur = cur;
2016         tmpcur.pop();
2017         FuncStatus status;
2018         FuncRequest cmd(LFUN_MATH_DISPLAY);
2019         return tmpcur.getStatus(cmd, status) && status.enabled();
2020 }
2021
2022 } // namespace
2023
2024
2025 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
2026                 FuncStatus & status) const
2027 {
2028         switch (cmd.action()) {
2029         case LFUN_FINISHED_BACKWARD:
2030         case LFUN_FINISHED_FORWARD:
2031         case LFUN_FINISHED_RIGHT:
2032         case LFUN_FINISHED_LEFT:
2033         case LFUN_UP:
2034         case LFUN_DOWN:
2035         case LFUN_NEWLINE_INSERT:
2036         case LFUN_MATH_EXTERN:
2037                 // we handle these
2038                 status.setEnabled(true);
2039                 return true;
2040
2041         // we never allow this in math, and we want to bind enter
2042         // to another actions in command-alternatives
2043         case LFUN_PARAGRAPH_BREAK:
2044                 status.setEnabled(false);
2045                 return true;
2046         case LFUN_MATH_MUTATE: {
2047                 HullType const ht = hullType(cmd.argument());
2048                 status.setOnOff(type_ == ht);
2049                 status.setEnabled(isMutable(ht) && isMutable(type_));
2050
2051                 if (ht != hullSimple && status.enabled())
2052                         status.setEnabled(allowDisplayMath(cur));
2053                 return true;
2054         }
2055         case LFUN_MATH_DISPLAY: {
2056                 status.setEnabled(display() || allowDisplayMath(cur));
2057                 status.setOnOff(display());
2058                 return true;
2059         }
2060
2061         case LFUN_MATH_NUMBER_TOGGLE:
2062                 // FIXME: what is the right test, this or the one of
2063                 // LABEL_INSERT?
2064                 status.setEnabled(display());
2065                 status.setOnOff(numberedType());
2066                 return true;
2067
2068         case LFUN_MATH_NUMBER_LINE_TOGGLE: {
2069                 // FIXME: what is the right test, this or the one of
2070                 // LABEL_INSERT?
2071                 bool const enable = (type_ == hullMultline)
2072                         ? (nrows() - 1 == cur.row())
2073                         : display();
2074                 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2075                 status.setEnabled(enable);
2076                 status.setOnOff(enable && numbered(r));
2077                 return true;
2078         }
2079
2080         case LFUN_LABEL_INSERT:
2081                 status.setEnabled(type_ != hullSimple);
2082                 return true;
2083
2084         case LFUN_LABEL_COPY_AS_REFERENCE: {
2085                 bool enabled = false;
2086                 if (cmd.argument().empty() && &cur.inset() == this) {
2087                         // if there is no argument and we're inside math, we retrieve
2088                         // the row number from the cursor position.
2089                         row_type row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2090                         enabled = numberedType() && label_[row];
2091                 } else {
2092                         // if there is an argument, find the corresponding label, else
2093                         // check whether there is at least one label.
2094                         for (row_type row = 0; row != nrows(); ++row) {
2095                                 if (label_[row] &&
2096                                         (cmd.argument().empty() || label(row) == cmd.argument())) {
2097                                                 enabled = true;
2098                                                 break;
2099                                 }
2100                         }
2101                 }
2102                 status.setEnabled(enabled);
2103                 return true;
2104         }
2105
2106         case LFUN_INSET_INSERT:
2107                 if (cmd.getArg(0) == "label") {
2108                         status.setEnabled(type_ != hullSimple);
2109                         return true;
2110                 }
2111                 return InsetMathGrid::getStatus(cur, cmd, status);
2112
2113         case LFUN_TABULAR_FEATURE: {
2114                 if (!allowsTabularFeatures())
2115                         return false;
2116                 string s = cmd.getArg(0);
2117                 if (!rowChangeOK()
2118                     && (s == "append-row"
2119                         || s == "delete-row"
2120                         || s == "copy-row")) {
2121                         status.message(bformat(
2122                                 from_utf8(N_("Can't change number of rows in '%1$s'")),
2123                                 hullName(type_)));
2124                         status.setEnabled(false);
2125                         return true;
2126                 }
2127                 if (!colChangeOK()
2128                     && (s == "append-column"
2129                         || s == "delete-column"
2130                         || s == "copy-column")) {
2131                         status.message(bformat(
2132                                 from_utf8(N_("Can't change number of columns in '%1$s'")),
2133                                 hullName(type_)));
2134                         status.setEnabled(false);
2135                         return true;
2136                 }
2137                 if (s == "add-vline-left" || s == "add-vline-right") {
2138                         status.message(bformat(
2139                                 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2140                                 hullName(type_)));
2141                         status.setEnabled(false);
2142                         return true;
2143                 }
2144                 if (s == "valign-top" || s == "valign-middle"
2145                  || s == "valign-bottom" || s == "align-left"
2146                  || s == "align-center" || s == "align-right") {
2147                         status.setEnabled(false);
2148                         return true;
2149                 }
2150                 return InsetMathGrid::getStatus(cur, cmd, status);
2151         }
2152
2153         default:
2154                 return InsetMathGrid::getStatus(cur, cmd, status);
2155         }
2156 }
2157
2158
2159 int InsetMathHull::leftMargin() const
2160 {
2161         return (getType() == hullSimple) ? 0 : InsetMathGrid::leftMargin();
2162 }
2163
2164
2165 int InsetMathHull::rightMargin() const
2166 {
2167         return (getType() == hullSimple) ? 0 : InsetMathGrid::rightMargin();
2168 }
2169
2170
2171 int InsetMathHull::border() const
2172 {
2173         return (getType() == hullSimple) ? 0 : InsetMathGrid::border();
2174 }
2175
2176
2177 /////////////////////////////////////////////////////////////////////
2178
2179
2180
2181 // simply scrap this function if you want
2182 void InsetMathHull::mutateToText()
2183 {
2184 #if 0
2185         // translate to latex
2186         ostringstream os;
2187         latex(os, false, false);
2188         string str = os.str();
2189
2190         // insert this text
2191         Text * lt = view_->cursor().innerText();
2192         string::const_iterator cit = str.begin();
2193         string::const_iterator end = str.end();
2194         for (; cit != end; ++cit)
2195                 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2196
2197         // remove ourselves
2198         //dispatch(LFUN_ESCAPE);
2199 #endif
2200 }
2201
2202
2203 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2204         docstring const & font)
2205 {
2206         // this whole function is a hack and won't work for incremental font
2207         // changes...
2208         cur.recordUndo();
2209         if (cur.inset().asInsetMath()->name() == font)
2210                 cur.handleFont(to_utf8(font));
2211         else {
2212                 cur.handleNest(createInsetMath(font, cur.buffer()));
2213                 cur.insert(arg);
2214         }
2215 }
2216
2217
2218 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2219 {
2220         cur.recordUndo();
2221         Font font;
2222         bool b;
2223         font.fromString(to_utf8(arg), b);
2224         if (font.fontInfo().color() != Color_inherit) {
2225                 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2226                 cur.handleNest(at);
2227         }
2228 }
2229
2230
2231 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2232 {
2233         cur.push(*this);
2234         bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
2235                 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
2236         enter_front ? idxFirst(cur) : idxLast(cur);
2237         // The inset formula dimension is not necessarily the same as the
2238         // one of the instant preview image, so we have to indicate to the
2239         // BufferView that a metrics update is needed.
2240         cur.screenUpdateFlags(Update::Force);
2241 }
2242
2243
2244 /////////////////////////////////////////////////////////////////////
2245
2246
2247 #if 0
2248 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2249                                      bool, bool)
2250 {
2251         // FIXME: completely broken
2252         static InsetMathHull * lastformula = 0;
2253         static CursorBase current = DocIterator(ibegin(nucleus()));
2254         static MathData ar;
2255         static string laststr;
2256
2257         if (lastformula != this || laststr != str) {
2258                 //lyxerr << "reset lastformula to " << this << endl;
2259                 lastformula = this;
2260                 laststr = str;
2261                 current = ibegin(nucleus());
2262                 ar.clear();
2263                 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2264         } else {
2265                 increment(current);
2266         }
2267         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2268
2269         for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2270                 CursorSlice & top = it.back();
2271                 MathData const & a = top.asInsetMath()->cell(top.idx_);
2272                 if (a.matchpart(ar, top.pos_)) {
2273                         bv->cursor().setSelection(it, ar.size());
2274                         current = it;
2275                         top.pos_ += ar.size();
2276                         bv->update();
2277                         return true;
2278                 }
2279         }
2280
2281         //lyxerr << "not found!" << endl;
2282         lastformula = 0;
2283         return false;
2284 }
2285 #endif
2286
2287
2288 void InsetMathHull::write(ostream & os) const
2289 {
2290         odocstringstream oss;
2291         otexrowstream ots(oss);
2292         TeXMathStream wi(ots, false, false, TeXMathStream::wsDefault);
2293         oss << "Formula ";
2294         write(wi);
2295         os << to_utf8(oss.str());
2296 }
2297
2298
2299 void InsetMathHull::read(Lexer & lex)
2300 {
2301         MathAtom at;
2302         mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2303         operator=(*at->asHullInset());
2304 }
2305
2306
2307 bool InsetMathHull::readQuiet(Lexer & lex)
2308 {
2309         MathAtom at;
2310         bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2311         if (success)
2312                 operator=(*at->asHullInset());
2313         return success;
2314 }
2315
2316
2317 int InsetMathHull::plaintext(odocstringstream & os,
2318         OutputParams const & op, size_t max_length) const
2319 {
2320         // Try enabling this now that there is a flag as requested at #2275.
2321         if (buffer().isExporting() && display()) {
2322                 Dimension dim;
2323                 TextMetricsInfo mi;
2324                 metricsT(mi, dim);
2325                 TextPainter tpain(dim.width(), dim.height());
2326                 drawT(tpain, 0, dim.ascent());
2327                 tpain.show(os, 3);
2328                 // reset metrics cache to "real" values
2329                 //metrics();
2330                 return tpain.textheight();
2331         }
2332
2333         odocstringstream oss;
2334         otexrowstream ots(oss);
2335         Encoding const * const enc = encodings.fromLyXName("utf8");
2336
2337         TeXMathStream::OutputType ot;
2338         if (op.find_effective())
2339                 ot = TeXMathStream::wsSearchAdv;
2340         else
2341                 ot = TeXMathStream::wsDefault;
2342         // Fix Bug #6139
2343         if (type_ == hullRegexp) {
2344                 TeXMathStream wi(ots, false, true, ot, enc);
2345                 write(wi);
2346         }
2347         else {
2348                 TeXMathStream wi(ots, false, true, ot, enc);
2349                 for (row_type r = 0; r < nrows(); ++r) {
2350                         for (col_type c = 0; c < ncols(); ++c)
2351                                 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2352                         // if it's for the TOC, we write just the first line
2353                         // and do not include the newline.
2354                         if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2355                                 break;
2356                         if (r < nrows() - 1)
2357                                 wi << "\n";
2358                 }
2359         }
2360         docstring const str = oss.str();
2361         os << str;
2362         return str.size();
2363 }
2364
2365
2366 void InsetMathHull::docbook(XMLStream & xs, OutputParams const & runparams) const {
2367         // Choose the tag around the MathML equation.
2368         docstring name;
2369         bool doCR = false;
2370         if (getType() == hullSimple)
2371                 name = from_ascii("inlineequation");
2372         else {
2373                 doCR = true; // This is a block equation, always have <informalequation> on its own line.
2374                 name = from_ascii("informalequation");
2375         }
2376
2377         // DocBook also has <equation>, but it comes with a title.
2378         // TODO: recognise \tag from amsmath? This would allow having <equation> with a proper title.
2379
2380         docstring attr;
2381
2382         bool mathmlNamespaceInline = buffer().params().docbook_mathml_prefix == BufferParams::NoPrefix;
2383         if (mathmlNamespaceInline)
2384                 attr += "xmlns=\"http://www.w3.org/1998/Math/MathML\"";
2385
2386         for (row_type i = 0; i < nrows(); ++i) {
2387                 if (!label(i).empty()) {
2388                         if (!attr.empty())
2389                                 attr += " ";
2390
2391                         attr += "xml:id=\"" + xml::cleanID(label(i)) + "\"";
2392                         break;
2393                 }
2394         }
2395
2396         if (doCR)
2397                 if (!xs.isLastTagCR())
2398                         xs << xml::CR();
2399
2400         xs << xml::StartTag(name, attr);
2401         xs << xml::CR();
2402
2403         // With DocBook 5, MathML must be within its own namespace (defined in Buffer.cpp::writeDocBookSource, except when
2404         // it should be inlined).
2405         // Output everything in a separate stream so that this does not interfere with the standard flow of DocBook tags.
2406         std::string mathmlNamespacePrefix;
2407         if (!mathmlNamespaceInline) {
2408                 if (buffer().params().docbook_mathml_prefix == BufferParams::MPrefix)
2409                         mathmlNamespacePrefix = "m";
2410                 else if (buffer().params().docbook_mathml_prefix == BufferParams::MMLPrefix)
2411                         mathmlNamespacePrefix = "mml";
2412         }
2413
2414         odocstringstream osmath;
2415         MathMLStream ms(osmath, mathmlNamespacePrefix, true);
2416
2417         // Output the MathML subtree.
2418         // TeX transcription. Avoid MTag/ETag so that there are no extraneous spaces.
2419         ms << "<" << from_ascii("alt") << " role='tex'" << ">";
2420         // Workaround for db2latex: db2latex always includes equations with
2421         // \ensuremath{} or \begin{display}\end{display}
2422         // so we strip LyX' math environment
2423         odocstringstream ls;
2424         otexstream ols(ls);
2425         TeXMathStream wi(ols, false, false, TeXMathStream::wsDefault, runparams.encoding);
2426         InsetMathGrid::write(wi);
2427         ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
2428         ms << "</" << from_ascii("alt") << ">";
2429
2430         // Actual transformation of the formula into MathML. This translation may fail (for example, due to custom macros).
2431         // The new output stream is required to deal with the errors: first write completely the formula into this
2432         // temporary stream; then, if it is possible without error, then copy it back to the "real" stream. Otherwise,
2433         // some incomplete tags might be put into the real stream.
2434         try {
2435                 // First, generate the MathML expression. If there is an error in the generation, this block is not fully
2436                 // executed, and the formula is not output to the DocBook stream.
2437                 odocstringstream ostmp;
2438                 MathMLStream mstmp(ostmp, ms.xmlns(), ms.xmlMode());
2439                 mathmlize(mstmp);
2440
2441                 // Choose the display style for the formula, to be output as an attribute near the formula root.
2442                 std::string mathmlAttr;
2443                 if (getType() == hullSimple)
2444                         mathmlAttr = "display=\"inline\"";
2445                 else
2446                         mathmlAttr = "display=\"block\"";
2447
2448                 // Then, output the formula.
2449                 ms << MTag("math", mathmlAttr);
2450                 ms.cr();
2451                 osmath << ostmp.str(); // osmath is not a XMLStream, so no need for XMLStream::ESCAPE_NONE.
2452                 ms << ETag("math");
2453         } catch (MathExportException const &) {
2454                 ms.cr();
2455                 osmath << "<mathphrase>MathML export failed. Please report this as a bug to the LyX developers: "
2456                         "https://www.lyx.org/trac.</mathphrase>";
2457         }
2458
2459         // Output the complete formula to the DocBook stream.
2460         xs << XMLStream::ESCAPE_NONE << osmath.str();
2461         xs << xml::CR();
2462         xs << xml::EndTag(name);
2463         if (doCR)
2464                 xs << xml::CR();
2465 }
2466
2467
2468 bool InsetMathHull::haveNumbers() const
2469 {
2470         bool havenumbers = false;
2471         // inline formulas are never numbered (bug 7351 part 3)
2472         if (getType() == hullSimple)
2473                 return havenumbers;
2474         for (size_t i = 0; i != numbered_.size(); ++i) {
2475                 if (numbered(i)) {
2476                         havenumbers = true;
2477                         break;
2478                 }
2479         }
2480         return havenumbers;
2481 }
2482
2483
2484 // FIXME XHTML
2485 // We need to do something about alignment here.
2486 //
2487 // This duplicates code from InsetMathGrid, but
2488 // we need access here to number information,
2489 // and we simply do not have that in InsetMathGrid.
2490 void InsetMathHull::htmlize(HtmlStream & os) const
2491 {
2492         bool const havenumbers = haveNumbers();
2493         bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2494
2495         if (!havetable) {
2496                 os << cell(index(0, 0));
2497                 return;
2498         }
2499
2500         os << MTag("table", "class='mathtable'");
2501         for (row_type row = 0; row < nrows(); ++row) {
2502                 os << MTag("tr");
2503                 for (col_type col = 0; col < ncols(); ++col) {
2504                         os << MTag("td");
2505                         os << cell(index(row, col));
2506                         os << ETag("td");
2507                 }
2508                 if (havenumbers) {
2509                         os << MTag("td");
2510                         docstring const & num = numbers_[row];
2511                         if (!num.empty())
2512                                 os << '(' << num << ')';
2513                   os << ETag("td");
2514                 }
2515                 os << ETag("tr");
2516         }
2517         os << ETag("table");
2518 }
2519
2520
2521 // this duplicates code from InsetMathGrid, but
2522 // we need access here to number information,
2523 // and we simply do not have that in InsetMathGrid.
2524 void InsetMathHull::mathmlize(MathMLStream & ms) const
2525 {
2526         bool const havetable = haveNumbers() || nrows() > 1 || ncols() > 1;
2527
2528     if (havetable) {
2529         if (getType() == hullSimple) {
2530                 ms << MTag("mtable");
2531         } else if (getType() >= hullAlign && getType() <= hullXXAlignAt) {
2532             string alignment;
2533             for (col_type col = 0; col < ncols(); ++col) {
2534                 alignment += (col % 2) ? "left " : "right ";
2535             }
2536             ms << MTag("mtable", "displaystyle='true' columnalign='" + alignment + "'");
2537             } else {
2538                 ms << MTag("mtable", "displaystyle='true'");
2539         }
2540     }
2541
2542         char const * const celltag = havetable ? "mtd" : "mrow";
2543         // FIXME There does not seem to be wide support at the moment
2544         // for mlabeledtr, so we have to use just mtr for now.
2545         // char const * const rowtag = haveNumbers() ? "mlabeledtr" : "mtr";
2546         char const * const rowtag = "mtr";
2547         for (row_type row = 0; row < nrows(); ++row) {
2548                 if (havetable)
2549                         ms << MTag(rowtag);
2550                 for (col_type col = 0; col < ncols(); ++col) {
2551                         ms << MTag(celltag)
2552                            << cell(index(row, col))
2553                            << ETag(celltag);
2554                 }
2555                 // fleqn?
2556                 if (haveNumbers()) {
2557                         ms << MTag("mtd");
2558                         docstring const & num = numbers_[row];
2559                         if (!num.empty())
2560                                 ms << MTagInline("mtext") << '(' << num << ')' << ETagInline("mtext");
2561                     ms << ETag("mtd");
2562                 }
2563                 if (havetable)
2564                         ms << ETag(rowtag);
2565         }
2566         if (havetable)
2567                 ms << ETag("mtable");
2568 }
2569
2570
2571 void InsetMathHull::mathAsLatex(TeXMathStream & os) const
2572 {
2573         MathEnsurer ensurer(os, false);
2574         bool havenumbers = haveNumbers();
2575         bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2576
2577         if (!havetable) {
2578                 os << cell(index(0, 0));
2579                 return;
2580         }
2581
2582         os << "<table class='mathtable'>";
2583         for (row_type row = 0; row < nrows(); ++row) {
2584                 os << "<tr>";
2585                 for (col_type col = 0; col < ncols(); ++col) {
2586                         os << "<td class='math'>";
2587                         os << cell(index(row, col));
2588                         os << "</td>";
2589                 }
2590                 if (havenumbers) {
2591                         os << "<td>";
2592                         docstring const & num = numbers_[row];
2593                         if (!num.empty())
2594                                 os << '(' << num << ')';
2595                   os << "</td>";
2596                 }
2597                 os << "</tr>";
2598         }
2599         os << "</table>";
2600 }
2601
2602
2603 docstring InsetMathHull::xhtml(XMLStream & xs, OutputParams const & op) const
2604 {
2605         BufferParams::MathOutput const mathtype =
2606                 buffer().masterBuffer()->params().html_math_output;
2607
2608         bool success = false;
2609
2610         // we output all the labels just at the beginning of the equation.
2611         // this should be fine.
2612         for (size_t i = 0; i != label_.size(); ++i) {
2613                 InsetLabel const * const il = label_[i];
2614                 if (!il)
2615                         continue;
2616                 il->xhtml(xs, op);
2617         }
2618
2619         // FIXME Eventually we would like to do this inset by inset.
2620         if (mathtype == BufferParams::MathML) {
2621                 odocstringstream os;
2622                 MathMLStream ms(os);
2623                 try {
2624                         mathmlize(ms);
2625                         success = true;
2626                 } catch (MathExportException const &) {}
2627                 if (success) {
2628                         if (getType() == hullSimple)
2629                                 xs << xml::StartTag("math",
2630                                                         "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2631                         else
2632                                 xs << xml::StartTag("math",
2633                                       "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2634                         xs << XMLStream::ESCAPE_NONE
2635                                  << os.str()
2636                                  << xml::EndTag("math");
2637                 }
2638         } else if (mathtype == BufferParams::HTML) {
2639                 odocstringstream os;
2640                 HtmlStream ms(os);
2641                 try {
2642                         htmlize(ms);
2643                         success = true;
2644                 } catch (MathExportException const &) {}
2645                 if (success) {
2646                         string const tag = (getType() == hullSimple) ? "span" : "div";
2647                         xs << xml::StartTag(tag, "class='formula'", true)
2648                            << XMLStream::ESCAPE_NONE
2649                            << os.str()
2650                            << xml::EndTag(tag);
2651                 }
2652         }
2653
2654         // what we actually want is this:
2655         // if (
2656         //     ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2657         //       && !success)
2658         //     || mathtype == BufferParams::Images
2659         //    )
2660         // but what follows is equivalent, since we'll enter only if either (a) we
2661         // tried and failed with MathML or HTML or (b) didn't try yet at all but
2662         // aren't doing LaTeX.
2663         //
2664         // so this is for Images.
2665         if (!success && mathtype != BufferParams::LaTeX) {
2666                 graphics::PreviewImage const * pimage = 0;
2667                 if (!op.dryrun) {
2668                         loadPreview(docit_);
2669                         pimage = preview_->getPreviewImage(buffer());
2670                         // FIXME Do we always have png?
2671                 }
2672
2673                 if (pimage || op.dryrun) {
2674                         string const filename = pimage ? pimage->filename().onlyFileName()
2675                                                        : "previewimage.png";
2676                         if (pimage) {
2677                                 // if we are not in the master buffer, then we need to see that the
2678                                 // generated image is copied there; otherwise, preview fails.
2679                                 Buffer const * mbuf = buffer().masterBuffer();
2680                                 if (mbuf != &buffer()) {
2681                                         string mbtmp = mbuf->temppath();
2682                                         FileName const mbufimg(support::addName(mbtmp, filename));
2683                                         pimage->filename().copyTo(mbufimg);
2684                                 }
2685                                 // add the file to the list of files to be exported
2686                                 op.exportdata->addExternalFile("xhtml", pimage->filename());
2687                         }
2688
2689                         string const tag = (getType() == hullSimple) ? "span" : "div";
2690                         xs << xml::CR()
2691                            << xml::StartTag(tag, "style = \"text-align: center;\"")
2692                            << xml::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2693                            << xml::EndTag(tag)
2694                            << xml::CR();
2695                         success = true;
2696                 }
2697         }
2698
2699         // so we'll pass this test if we've failed everything else, or
2700         // if mathtype was LaTeX, since we won't have entered any of the
2701         // earlier branches
2702         if (!success /* || mathtype != BufferParams::LaTeX */) {
2703                 // Unfortunately, we cannot use latexString() because we do not want
2704                 // $...$ or whatever.
2705                 odocstringstream ls;
2706                 otexrowstream ots(ls);
2707                 TeXMathStream wi(ots, false, true, TeXMathStream::wsPreview);
2708                 ModeSpecifier specifier(wi, MATH_MODE);
2709                 mathAsLatex(wi);
2710                 docstring const latex = ls.str();
2711
2712                 // class='math' allows for use of jsMath
2713                 // http://www.math.union.edu/~dpvc/jsMath/
2714                 // FIXME XHTML
2715                 // probably should allow for some kind of customization here
2716                 string const tag = (getType() == hullSimple) ? "span" : "div";
2717                 xs << xml::StartTag(tag, "class='math'")
2718                    << latex
2719                    << xml::EndTag(tag)
2720                    << xml::CR();
2721         }
2722         return docstring();
2723 }
2724
2725
2726 void InsetMathHull::toString(odocstream & os) const
2727 {
2728         odocstringstream ods;
2729         plaintext(ods, OutputParams(0));
2730         os << ods.str();
2731 }
2732
2733
2734 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2735 {
2736         odocstringstream ods;
2737         OutputParams op(0);
2738         op.for_toc = true;
2739         // FIXME: this results in spilling TeX into the LyXHTML output since the
2740         // outliner is used to generate the LyXHTML list of figures/etc.
2741         plaintext(ods, op);
2742         os += ods.str();
2743 }
2744
2745
2746 string InsetMathHull::contextMenuName() const
2747 {
2748         return "context-math";
2749 }
2750
2751
2752 void InsetMathHull::recordLocation(DocIterator const & di)
2753 {
2754         docit_ = di;
2755 }
2756
2757
2758 bool InsetMathHull::canPaintChange(BufferView const &) const
2759 {
2760         // We let RowPainter do it seamlessly for inline insets
2761         return display();
2762 }
2763
2764
2765 } // namespace lyx