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