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