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