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