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