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