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