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