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