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