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