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