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