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