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