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