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