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