]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathHull.cpp
2413af3e86ca9d58a911aaf65d960d6ad4e0d5bf
[lyx.git] / src / mathed / InsetMathHull.cpp
1 /**
2  * \file InsetMathHull.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetMathHull.h"
14
15 #include "InsetMathChar.h"
16 #include "InsetMathColor.h"
17 #include "InsetMathFrac.h"
18 #include "InsetMathNest.h"
19 #include "InsetMathScript.h"
20 #include "MathExtern.h"
21 #include "MathFactory.h"
22 #include "MathStream.h"
23 #include "MathSupport.h"
24
25 #include "Buffer.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
28 #include "ColorSet.h"
29 #include "CutAndPaste.h"
30 #include "Encoding.h"
31 #include "Exporter.h"
32 #include "FuncRequest.h"
33 #include "FuncStatus.h"
34 #include "Language.h"
35 #include "LaTeXFeatures.h"
36 #include "LyXRC.h"
37 #include "MacroTable.h"
38 #include "InsetMathMacro.h"
39 #include "InsetMathMacroTemplate.h"
40 #include "MetricsInfo.h"
41 #include "output_xhtml.h"
42 #include "Paragraph.h"
43 #include "ParIterator.h"
44 #include "sgml.h"
45 #include "TexRow.h"
46 #include "TextClass.h"
47 #include "TextPainter.h"
48 #include "TocBackend.h"
49
50 #include "insets/InsetLabel.h"
51 #include "insets/InsetRef.h"
52 #include "insets/RenderPreview.h"
53
54 #include "graphics/GraphicsImage.h"
55 #include "graphics/PreviewImage.h"
56 #include "graphics/PreviewLoader.h"
57
58 #include "frontends/alert.h"
59 #include "frontends/Painter.h"
60
61 #include "support/convert.h"
62 #include "support/debug.h"
63 #include "support/gettext.h"
64 #include "support/filetools.h"
65 #include "support/lassert.h"
66 #include "support/lstrings.h"
67 #include "support/RefChanger.h"
68
69 #include <sstream>
70
71 using namespace std;
72 using namespace lyx::support;
73
74 namespace lyx {
75
76 using cap::grabAndEraseSelection;
77 using cap::reduceSelectionToOneCell;
78
79 namespace {
80
81         int getCols(HullType type)
82         {
83                 switch (type) {
84                 case hullEqnArray:
85                         return 3;
86                 case hullAlign:
87                 case hullFlAlign:
88                 case hullAlignAt:
89                 case hullXAlignAt:
90                 case hullXXAlignAt:
91                         return 2;
92                 case hullUnknown:
93                 case hullNone:
94                 case hullSimple:
95                 case hullEquation:
96                 case hullMultline:
97                 case hullGather:
98                 case hullRegexp:
99                         return 1;
100                 }
101                 // avoid warning
102                 return 0;
103         }
104
105
106         // returns position of first relation operator in the array
107         // used for "intelligent splitting"
108         size_t firstRelOp(MathData const & ar)
109         {
110                 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
111                         if ((*it)->mathClass() == MC_REL)
112                                 return it - ar.begin();
113                 return ar.size();
114         }
115
116
117         char const * star(bool numbered)
118         {
119                 return numbered ? "" : "*";
120         }
121
122
123         // writes a preamble for underlined or struck out math display
124         void writeMathdisplayPreamble(WriteStream & os)
125         {
126                 if (os.strikeoutMath())
127                         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.require("tikz");
1106                                 features.require("ct-tikz-object-sout");
1107                 }
1108
1109                 // Validation is necessary only if not using AMS math.
1110                 // To be safe, we will always run mathedvalidate.
1111                 //if (features.amsstyle)
1112                 //  return;
1113
1114                 //features.binom      = true;
1115         } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
1116                 // it would be better to do this elsewhere, but we can't validate in
1117                 // InsetMathMatrix and we have no way, outside MathExtern, to know if
1118                 // we even have any matrices.
1119                                 features.addCSSSnippet(
1120                                         "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
1121                                         "table.matrix td{padding: 0.25px;}\n"
1122                                         "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
1123                                         "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
1124         }
1125         InsetMathGrid::validate(features);
1126 }
1127
1128
1129 OutputParams::CtObject InsetMathHull::CtObject(OutputParams const & runparams) const
1130 {
1131         OutputParams::CtObject res = OutputParams::CT_NORMAL;
1132         switch(type_) {
1133         case hullNone:
1134         case hullSimple:
1135         case hullAlignAt:
1136         case hullXAlignAt:
1137         case hullXXAlignAt:
1138         case hullRegexp:
1139         case hullUnknown:
1140                 break;
1141
1142         case hullEquation:
1143         case hullEqnArray:
1144         case hullAlign:
1145         case hullFlAlign:
1146         case hullGather:
1147         case hullMultline: {
1148                 if (runparams.inulemcmd
1149                     && (!runparams.local_font || runparams.local_font->fontInfo().strikeout() != FONT_ON))
1150                         res = OutputParams::CT_UDISPLAYOBJECT;
1151                 else
1152                         res = OutputParams::CT_DISPLAYOBJECT;
1153                 break;
1154                 }
1155         }
1156         return res;
1157 }
1158
1159
1160 void InsetMathHull::header_write(WriteStream & os) const
1161 {
1162         bool n = numberedType();
1163
1164         switch(type_) {
1165         case hullNone:
1166                 break;
1167
1168         case hullSimple:
1169                 if (os.ulemCmd())
1170                         os << "\\mbox{";
1171                 os << '$';
1172                 os.startOuterRow();
1173                 if (cell(0).empty())
1174                         os << ' ';
1175                 break;
1176
1177         case hullEquation:
1178                 writeMathdisplayPreamble(os);
1179                 os << "\n";
1180                 os.startOuterRow();
1181                 if (n)
1182                         os << "\\begin{equation" << star(n) << "}\n";
1183                 else
1184                         os << "\\[\n";
1185                 break;
1186
1187         case hullEqnArray:
1188         case hullAlign:
1189         case hullFlAlign:
1190         case hullGather:
1191         case hullMultline:
1192                 writeMathdisplayPreamble(os);
1193                 os << "\n";
1194                 os.startOuterRow();
1195                 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1196                 break;
1197
1198         case hullAlignAt:
1199         case hullXAlignAt:
1200                 os << "\n";
1201                 os.startOuterRow();
1202                 os << "\\begin{" << hullName(type_) << star(n) << '}'
1203                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1204                 break;
1205
1206         case hullXXAlignAt:
1207                 os << "\n";
1208                 os.startOuterRow();
1209                 os << "\\begin{" << hullName(type_) << '}'
1210                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1211                 break;
1212
1213         case hullRegexp:
1214                 os << "\\regexp{";
1215                 break;
1216
1217         case hullUnknown:
1218                 os << "\n";
1219                 os.startOuterRow();
1220                 os << "\\begin{unknown" << star(n) << "}\n";
1221                 break;
1222         }
1223 }
1224
1225
1226 void InsetMathHull::footer_write(WriteStream & os) const
1227 {
1228         bool n = numberedType();
1229
1230         switch(type_) {
1231         case hullNone:
1232                 os << "\n";
1233                 break;
1234
1235         case hullSimple:
1236                 os << '$';
1237                 if (os.ulemCmd())
1238                         os << "}";
1239                 break;
1240
1241         case hullEquation:
1242                 os << "\n";
1243                 os.startOuterRow();
1244                 if (n)
1245                         os << "\\end{equation" << star(n) << "}\n";
1246                 else
1247                         os << "\\]\n";
1248                 writeMathdisplayPostamble(os);
1249                 break;
1250
1251         case hullEqnArray:
1252         case hullAlign:
1253         case hullFlAlign:
1254         case hullGather:
1255         case hullMultline:
1256                 os << "\n";
1257                 os.startOuterRow();
1258                 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1259                 writeMathdisplayPostamble(os);
1260                 break;
1261
1262         case hullAlignAt:
1263         case hullXAlignAt:
1264                 os << "\n";
1265                 os.startOuterRow();
1266                 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1267                 break;
1268
1269         case hullXXAlignAt:
1270                 os << "\n";
1271                 os.startOuterRow();
1272                 os << "\\end{" << hullName(type_) << "}\n";
1273                 break;
1274
1275         case hullRegexp:
1276                 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1277                 os << "\\endregexp{}}";
1278                 break;
1279
1280         case hullUnknown:
1281                 os << "\n";
1282                 os.startOuterRow();
1283                 os << "\\end{unknown" << star(n) << "}\n";
1284                 break;
1285         }
1286 }
1287
1288
1289 bool InsetMathHull::allowsTabularFeatures() const
1290 {
1291         switch (type_) {
1292         case hullEqnArray:
1293         case hullAlign:
1294         case hullAlignAt:
1295         case hullXAlignAt:
1296         case hullXXAlignAt:
1297         case hullFlAlign:
1298         case hullMultline:
1299         case hullGather:
1300                 return true;
1301         case hullNone:
1302         case hullSimple:
1303         case hullEquation:
1304         case hullRegexp:
1305         case hullUnknown:
1306                 break;
1307         }
1308         return false;
1309 }
1310
1311
1312 bool InsetMathHull::rowChangeOK() const
1313 {
1314         return
1315                 type_ == hullEqnArray || type_ == hullAlign ||
1316                 type_ == hullFlAlign || type_ == hullAlignAt ||
1317                 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1318                 type_ == hullGather || type_ == hullMultline;
1319 }
1320
1321
1322 bool InsetMathHull::colChangeOK() const
1323 {
1324         return
1325                 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1326                 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1327 }
1328
1329
1330 void InsetMathHull::addRow(row_type row)
1331 {
1332         if (!rowChangeOK())
1333                 return;
1334
1335         bool numbered = numberedType();
1336         // Move the number and raw pointer, do not call label() (bug 7511)
1337         InsetLabel * label = dummy_pointer;
1338         docstring number = empty_docstring();
1339         if (type_ == hullMultline) {
1340                 if (row + 1 == nrows())  {
1341                         numbered_[row] = NONUMBER;
1342                         swap(label, label_[row]);
1343                         swap(number, numbers_[row]);
1344                 } else
1345                         numbered = false;
1346         }
1347
1348         numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1349         numbers_.insert(numbers_.begin() + row + 1, number);
1350         label_.insert(label_.begin() + row + 1, label);
1351         InsetMathGrid::addRow(row);
1352 }
1353
1354
1355 void InsetMathHull::swapRow(row_type row)
1356 {
1357         if (nrows() <= 1)
1358                 return;
1359         if (row + 1 == nrows())
1360                 --row;
1361         swap(numbered_[row], numbered_[row + 1]);
1362         swap(numbers_[row], numbers_[row + 1]);
1363         swap(label_[row], label_[row + 1]);
1364         InsetMathGrid::swapRow(row);
1365 }
1366
1367
1368 void InsetMathHull::delRow(row_type row)
1369 {
1370         if (nrows() <= 1 || !rowChangeOK())
1371                 return;
1372         if (row + 1 == nrows() && type_ == hullMultline) {
1373                 swap(numbered_[row - 1], numbered_[row]);
1374                 swap(numbers_[row - 1], numbers_[row]);
1375                 swap(label_[row - 1], label_[row]);
1376                 InsetMathGrid::delRow(row);
1377                 return;
1378         }
1379         InsetMathGrid::delRow(row);
1380         // The last dummy row has no number info nor a label.
1381         // Test nrows() + 1 because we have already erased the row.
1382         if (row == nrows() + 1)
1383                 row--;
1384         numbered_.erase(numbered_.begin() + row);
1385         numbers_.erase(numbers_.begin() + row);
1386         delete label_[row];
1387         label_.erase(label_.begin() + row);
1388 }
1389
1390
1391 void InsetMathHull::addCol(col_type col)
1392 {
1393         if (!colChangeOK())
1394                 return;
1395         InsetMathGrid::addCol(col);
1396 }
1397
1398
1399 void InsetMathHull::delCol(col_type col)
1400 {
1401         if (ncols() <= 1 || !colChangeOK())
1402                 return;
1403         InsetMathGrid::delCol(col);
1404 }
1405
1406
1407 docstring InsetMathHull::nicelabel(row_type row) const
1408 {
1409         if (!numbered(row))
1410                 return docstring();
1411         docstring const & val = numbers_[row];
1412         if (!label_[row])
1413                 return '(' + val + ')';
1414         return '(' + val + ',' + label_[row]->screenLabel() + ')';
1415 }
1416
1417
1418 void InsetMathHull::glueall(HullType type)
1419 {
1420         MathData ar;
1421         for (idx_type i = 0; i < nargs(); ++i)
1422                 ar.append(cell(i));
1423         InsetLabel * label = 0;
1424         if (type == hullEquation) {
1425                 // preserve first non-empty label
1426                 for (row_type row = 0; row < nrows(); ++row) {
1427                         if (label_[row]) {
1428                                 label = label_[row];
1429                                 label_[row] = 0;
1430                                 break;
1431                         }
1432                 }
1433         }
1434         *this = InsetMathHull(buffer_, hullSimple);
1435         label_[0] = label;
1436         cell(0) = ar;
1437         setDefaults();
1438 }
1439
1440
1441 void InsetMathHull::splitTo2Cols()
1442 {
1443         LASSERT(ncols() == 1, return);
1444         InsetMathGrid::addCol(1);
1445         for (row_type row = 0; row < nrows(); ++row) {
1446                 idx_type const i = 2 * row;
1447                 pos_type pos = firstRelOp(cell(i));
1448                 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1449                 cell(i).erase(pos, cell(i).size());
1450         }
1451 }
1452
1453
1454 void InsetMathHull::splitTo3Cols()
1455 {
1456         LASSERT(ncols() < 3, return);
1457         if (ncols() < 2)
1458                 splitTo2Cols();
1459         InsetMathGrid::addCol(2);
1460         for (row_type row = 0; row < nrows(); ++row) {
1461                 idx_type const i = 3 * row + 1;
1462                 if (!cell(i).empty()) {
1463                         cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1464                         cell(i).erase(1, cell(i).size());
1465                 }
1466         }
1467 }
1468
1469
1470 void InsetMathHull::changeCols(col_type cols)
1471 {
1472         if (ncols() == cols)
1473                 return;
1474         else if (ncols() < cols) {
1475                 // split columns
1476                 if (cols < 3)
1477                         splitTo2Cols();
1478                 else {
1479                         splitTo3Cols();
1480                         while (ncols() < cols)
1481                                 InsetMathGrid::addCol(ncols());
1482                 }
1483                 return;
1484         }
1485
1486         // combine columns
1487         for (row_type row = 0; row < nrows(); ++row) {
1488                 idx_type const i = row * ncols();
1489                 for (col_type col = cols; col < ncols(); ++col) {
1490                         cell(i + cols - 1).append(cell(i + col));
1491                 }
1492         }
1493         // delete columns
1494         while (ncols() > cols) {
1495                 InsetMathGrid::delCol(ncols() - 1);
1496         }
1497 }
1498
1499
1500 HullType InsetMathHull::getType() const
1501 {
1502         return type_;
1503 }
1504
1505
1506 void InsetMathHull::setType(HullType type)
1507 {
1508         type_ = type;
1509         setDefaults();
1510 }
1511
1512
1513 bool InsetMathHull::isMutable(HullType type)
1514 {
1515         switch (type) {
1516         case hullNone:
1517         case hullSimple:
1518         case hullEquation:
1519         case hullEqnArray:
1520         case hullAlign:
1521         case hullFlAlign:
1522         case hullAlignAt:
1523         case hullXAlignAt:
1524         case hullXXAlignAt:
1525         case hullMultline:
1526         case hullGather:
1527                 return true;
1528         case hullUnknown:
1529         case hullRegexp:
1530                 return false;
1531         }
1532         // avoid warning
1533         return false;
1534 }
1535
1536
1537 void InsetMathHull::mutate(HullType newtype)
1538 {
1539         //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1540
1541         if (newtype == type_)
1542                 return;
1543
1544         // This guards the algorithm below it, which is designed with certain types
1545         // in mind.
1546         if (!isMutable(newtype) || !isMutable(type_)) {
1547                 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1548                        << "' to '" << to_utf8(hullName(newtype))
1549                        << "' not implemented" << endl;
1550                 return;
1551         }
1552
1553         // we try to move along the chain
1554         // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1555         //                                     ^                                     |
1556         //                                     +-------------------------------------+
1557         // we use eqnarray as intermediate type for mutations that are not
1558         // directly supported because it handles labels and numbering for
1559         // "down mutation".
1560
1561         switch (type_) {
1562         case hullNone:
1563                 setType(hullSimple);
1564                 numbered(0, false);
1565                 mutate(newtype);
1566                 break;
1567
1568         case hullSimple:
1569                 if (newtype == hullNone) {
1570                         setType(hullNone);
1571                         numbered(0, false);
1572                 } else {
1573                         setType(hullEquation);
1574                         numbered(0, label_[0] ? true : false);
1575                         mutate(newtype);
1576                 }
1577                 break;
1578
1579         case hullEquation:
1580                 switch (newtype) {
1581                 case hullNone:
1582                 case hullSimple:
1583                         setType(hullSimple);
1584                         numbered(0, false);
1585                         mutate(newtype);
1586                         break;
1587                 case hullEqnArray:
1588                         // split it "nicely" on the first relop
1589                         splitTo3Cols();
1590                         setType(hullEqnArray);
1591                         break;
1592                 case hullMultline:
1593                 case hullGather:
1594                         setType(newtype);
1595                         break;
1596                 default:
1597                         // *align*
1598                         // split it "nicely"
1599                         splitTo2Cols();
1600                         setType(hullAlign);
1601                         mutate(newtype);
1602                         break;
1603                 }
1604                 break;
1605
1606         case hullEqnArray:
1607                 switch (newtype) {
1608                 case hullNone:
1609                 case hullSimple:
1610                 case hullEquation:
1611                         glueall(newtype);
1612                         mutate(newtype);
1613                         break;
1614                 default:
1615                         // align & Co.
1616                         changeCols(2);
1617                         setType(hullAlign);
1618                         mutate(newtype);
1619                         break;
1620                 }
1621                 break;
1622
1623         case hullAlign:
1624         case hullAlignAt:
1625         case hullXAlignAt:
1626         case hullFlAlign:
1627                 switch (newtype) {
1628                 case hullNone:
1629                 case hullSimple:
1630                 case hullEquation:
1631                 case hullEqnArray:
1632                         changeCols(3);
1633                         setType(hullEqnArray);
1634                         mutate(newtype);
1635                         break;
1636                 case hullGather:
1637                 case hullMultline:
1638                         changeCols(1);
1639                         setType(newtype);
1640                         break;
1641                 case hullXXAlignAt:
1642                         for (row_type row = 0; row < nrows(); ++row)
1643                                 numbered(row, false);
1644                         setType(newtype);
1645                         break;
1646                 default:
1647                         setType(newtype);
1648                         break;
1649                 }
1650                 break;
1651
1652         case hullXXAlignAt:
1653                 for (row_type row = 0; row < nrows(); ++row)
1654                         numbered(row, false);
1655                 switch (newtype) {
1656                 case hullNone:
1657                 case hullSimple:
1658                 case hullEquation:
1659                 case hullEqnArray:
1660                         changeCols(3);
1661                         setType(hullEqnArray);
1662                         mutate(newtype);
1663                         break;
1664                 case hullGather:
1665                 case hullMultline:
1666                         changeCols(1);
1667                         setType(newtype);
1668                         break;
1669                 default:
1670                         setType(newtype);
1671                         break;
1672                 }
1673                 break;
1674
1675         case hullMultline:
1676         case hullGather:
1677                 switch (newtype) {
1678                 case hullGather:
1679                 case hullMultline:
1680                         setType(newtype);
1681                         break;
1682                 case hullAlign:
1683                 case hullFlAlign:
1684                 case hullAlignAt:
1685                 case hullXAlignAt:
1686                         splitTo2Cols();
1687                         setType(newtype);
1688                         break;
1689                 case hullXXAlignAt:
1690                         splitTo2Cols();
1691                         for (row_type row = 0; row < nrows(); ++row)
1692                                 numbered(row, false);
1693                         setType(newtype);
1694                         break;
1695                 default:
1696                         // first we mutate to EqnArray
1697                         splitTo3Cols();
1698                         setType(hullEqnArray);
1699                         mutate(newtype);
1700                         break;
1701                 }
1702                 break;
1703
1704         default:
1705                 // we passed the guard so we should not be here
1706                 LYXERR0("Mutation not implemented, but should have been.");
1707                 LASSERT(false, return);
1708                 break;
1709         }// switch
1710 }
1711
1712
1713 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1714                 bool last_eoln) const
1715 {
1716         docstring res;
1717         if (numberedType()) {
1718                 if (label_[row] && numbered(row)) {
1719                         docstring const name =
1720                                 latex ? escape(label_[row]->getParam("name"))
1721                                       : label_[row]->getParam("name");
1722                         res += "\\label{" + name + '}';
1723                 }
1724                 if (type_ != hullMultline) {
1725                         if (numbered_[row]  == NONUMBER)
1726                                 res += "\\nonumber ";
1727                         else if (numbered_[row]  == NOTAG)
1728                                 res += "\\notag ";
1729                 }
1730         }
1731         // Never add \\ on the last empty line of eqnarray and friends
1732         last_eoln = false;
1733         return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1734 }
1735
1736 void InsetMathHull::write(WriteStream & os) const
1737 {
1738         ModeSpecifier specifier(os, MATH_MODE);
1739         header_write(os);
1740         InsetMathGrid::write(os);
1741         footer_write(os);
1742 }
1743
1744
1745 void InsetMathHull::normalize(NormalStream & os) const
1746 {
1747         os << "[formula " << hullName(type_) << ' ';
1748         InsetMathGrid::normalize(os);
1749         os << "] ";
1750 }
1751
1752
1753 void InsetMathHull::infoize(odocstream & os) const
1754 {
1755         os << bformat(_("Type: %1$s"), hullName(type_));
1756 }
1757
1758
1759 void InsetMathHull::check() const
1760 {
1761         LATTEST(numbered_.size() == nrows());
1762         LATTEST(numbers_.size() == nrows());
1763         LATTEST(label_.size() == nrows());
1764 }
1765
1766
1767 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1768 {
1769         //FIXME: sort out whether we want std::string or docstring for those
1770         string const lang = func.getArg(0);
1771         docstring extra = from_utf8(func.getArg(1));
1772         if (extra.empty())
1773                 extra = from_ascii("noextra");
1774
1775         // replace selection with result of computation
1776         if (reduceSelectionToOneCell(cur)) {
1777                 MathData ar;
1778                 asArray(grabAndEraseSelection(cur), ar);
1779                 lyxerr << "use selection: " << ar << endl;
1780                 cur.insert(pipeThroughExtern(lang, extra, ar));
1781                 return;
1782         }
1783
1784         // only inline, display or eqnarray math is allowed
1785         switch (getType()) {
1786         case hullSimple:
1787         case hullEquation:
1788         case hullEqnArray:
1789                 break;
1790         default:
1791                 frontend::Alert::warning(_("Bad math environment"),
1792                                 _("Computation cannot be performed for AMS "
1793                                   "math environments.\nChange the math "
1794                                   "formula type and try again."));
1795                 return;
1796         }
1797
1798         MathData eq;
1799         eq.push_back(MathAtom(new InsetMathChar('=')));
1800
1801         // go to first item in line
1802         cur.idx() -= cur.idx() % ncols();
1803         cur.pos() = 0;
1804
1805         if (getType() == hullSimple) {
1806                 size_type pos = cur.cell().find_last(eq);
1807                 MathData ar;
1808                 if (pos == cur.cell().size()) {
1809                         ar = cur.cell();
1810                         lyxerr << "use whole cell: " << ar << endl;
1811                 } else {
1812                         ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1813                         lyxerr << "use partial cell form pos: " << pos << endl;
1814                 }
1815                 cur.cell().append(eq);
1816                 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1817                 cur.pos() = cur.lastpos();
1818                 return;
1819         }
1820
1821         if (getType() == hullEquation) {
1822                 lyxerr << "use equation inset" << endl;
1823                 mutate(hullEqnArray);
1824                 MathData & ar = cur.cell();
1825                 lyxerr << "use cell: " << ar << endl;
1826                 ++cur.idx();
1827                 cur.cell() = eq;
1828                 ++cur.idx();
1829                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1830                 // move to end of line
1831                 cur.pos() = cur.lastpos();
1832                 return;
1833         }
1834
1835         {
1836                 lyxerr << "use eqnarray" << endl;
1837                 cur.idx() += 2 - cur.idx() % ncols();
1838                 cur.pos() = 0;
1839                 MathData ar = cur.cell();
1840                 lyxerr << "use cell: " << ar << endl;
1841                 // FIXME: temporarily disabled
1842                 addRow(cur.row());
1843                 ++cur.idx();
1844                 ++cur.idx();
1845                 cur.cell() = eq;
1846                 ++cur.idx();
1847                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1848                 cur.pos() = cur.lastpos();
1849         }
1850 }
1851
1852
1853 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1854 {
1855         //lyxerr << "action: " << cmd.action() << endl;
1856         switch (cmd.action()) {
1857
1858         case LFUN_FINISHED_BACKWARD:
1859         case LFUN_FINISHED_FORWARD:
1860         case LFUN_FINISHED_RIGHT:
1861         case LFUN_FINISHED_LEFT:
1862                 //lyxerr << "action: " << cmd.action() << endl;
1863                 InsetMathGrid::doDispatch(cur, cmd);
1864                 break;
1865
1866         case LFUN_PARAGRAPH_BREAK:
1867                 // just swallow this
1868                 break;
1869
1870         case LFUN_NEWLINE_INSERT:
1871                 // some magic for the common case
1872                 if (type_ == hullSimple || type_ == hullEquation) {
1873                         cur.recordUndoInset();
1874                         bool const align =
1875                                 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1876                         mutate(align ? hullAlign : hullEqnArray);
1877                         // mutate() may change labels and such.
1878                         cur.forceBufferUpdate();
1879                         cur.idx() = nrows() * ncols() - 1;
1880                         cur.pos() = cur.lastpos();
1881                 }
1882                 InsetMathGrid::doDispatch(cur, cmd);
1883                 break;
1884
1885         case LFUN_MATH_NUMBER_TOGGLE: {
1886                 //lyxerr << "toggling all numbers" << endl;
1887                 cur.recordUndoInset();
1888                 bool old = numberedType();
1889                 if (type_ == hullMultline)
1890                         numbered(nrows() - 1, !old);
1891                 else
1892                         for (row_type row = 0; row < nrows(); ++row)
1893                                 numbered(row, !old);
1894
1895                 cur.message(old ? _("No number") : _("Number"));
1896                 cur.forceBufferUpdate();
1897                 break;
1898         }
1899
1900         case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1901                 cur.recordUndoInset();
1902                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1903                 bool old = numbered(r);
1904                 cur.message(old ? _("No number") : _("Number"));
1905                 numbered(r, !old);
1906                 cur.forceBufferUpdate();
1907                 break;
1908         }
1909
1910         case LFUN_LABEL_INSERT: {
1911                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1912                 docstring old_label = label(r);
1913                 docstring const default_label = from_ascii("eq:");
1914                 if (old_label.empty())
1915                         old_label = default_label;
1916
1917                 InsetCommandParams p(LABEL_CODE);
1918                 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1919                 string const data = InsetCommand::params2string(p);
1920
1921                 if (cmd.argument().empty())
1922                         cur.bv().showDialog("label", data);
1923                 else {
1924                         FuncRequest fr(LFUN_INSET_INSERT, data);
1925                         dispatch(cur, fr);
1926                 }
1927                 break;
1928         }
1929
1930         case LFUN_LABEL_COPY_AS_REFERENCE: {
1931                 row_type row;
1932                 if (cmd.argument().empty() && &cur.inset() == this)
1933                         // if there is no argument and we're inside math, we retrieve
1934                         // the row number from the cursor position.
1935                         row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1936                 else {
1937                         // if there is an argument, find the corresponding label, else
1938                         // check whether there is at least one label.
1939                         for (row = 0; row != nrows(); ++row)
1940                                 if (numbered(row) && label_[row]
1941                                           && (cmd.argument().empty() || label(row) == cmd.argument()))
1942                                         break;
1943                 }
1944
1945                 if (row == nrows())
1946                         break;
1947
1948                 InsetCommandParams p(REF_CODE, "ref");
1949                 p["reference"] = label(row);
1950                 cap::clearSelection();
1951                 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1952                 break;
1953         }
1954
1955         case LFUN_WORD_DELETE_FORWARD:
1956         case LFUN_CHAR_DELETE_FORWARD:
1957                 if (col(cur.idx()) + 1 == ncols()
1958                     && cur.pos() == cur.lastpos()
1959                     && !cur.selection()) {
1960                         if (!label(row(cur.idx())).empty()) {
1961                                 cur.recordUndoInset();
1962                                 label(row(cur.idx()), docstring());
1963                         } else if (numbered(row(cur.idx()))) {
1964                                 cur.recordUndoInset();
1965                                 numbered(row(cur.idx()), false);
1966                                 cur.forceBufferUpdate();
1967                         } else {
1968                                 InsetMathGrid::doDispatch(cur, cmd);
1969                                 return;
1970                         }
1971                 } else {
1972                         InsetMathGrid::doDispatch(cur, cmd);
1973                         return;
1974                 }
1975                 break;
1976
1977         case LFUN_INSET_INSERT: {
1978                 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1979                 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1980                 string const name = cmd.getArg(0);
1981                 if (name == "label") {
1982                         InsetCommandParams p(LABEL_CODE);
1983                         InsetCommand::string2params(to_utf8(cmd.argument()), p);
1984                         docstring str = p["name"];
1985                         cur.recordUndoInset();
1986                         row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1987                         str = trim(str);
1988                         if (!str.empty())
1989                                 numbered(r, true);
1990                         docstring old = label(r);
1991                         if (str != old) {
1992                                 if (label_[r])
1993                                         // The label will take care of the reference update.
1994                                         label(r, str);
1995                                 else {
1996                                         label(r, str);
1997                                         // Newly created inset so initialize it.
1998                                         label_[r]->initView();
1999                                 }
2000                         }
2001                         cur.forceBufferUpdate();
2002                         break;
2003                 }
2004                 InsetMathGrid::doDispatch(cur, cmd);
2005                 return;
2006         }
2007
2008         case LFUN_MATH_EXTERN:
2009                 cur.recordUndoInset();
2010                 doExtern(cur, cmd);
2011                 break;
2012
2013         case LFUN_MATH_MUTATE: {
2014                 cur.recordUndoInset();
2015                 row_type row = cur.row();
2016                 col_type col = cur.col();
2017                 mutate(hullType(cmd.argument()));
2018                 cur.idx() = row * ncols() + col;
2019                 if (cur.idx() > cur.lastidx()) {
2020                         cur.idx() = cur.lastidx();
2021                         cur.pos() = cur.lastpos();
2022                 }
2023                 if (cur.pos() > cur.lastpos())
2024                         cur.pos() = cur.lastpos();
2025
2026                 cur.forceBufferUpdate();
2027                 // FIXME: find some more clever handling of the selection,
2028                 // i.e. preserve it.
2029                 cur.clearSelection();
2030                 //cur.dispatched(FINISHED);
2031                 break;
2032         }
2033
2034         case LFUN_MATH_DISPLAY: {
2035                 cur.recordUndoInset();
2036                 mutate(type_ == hullSimple ? hullEquation : hullSimple);
2037                 // if the cursor is in a cell that got merged, move it to
2038                 // start of the hull inset.
2039                 if (cur.idx() > 0) {
2040                         cur.idx() = 0;
2041                         cur.pos() = 0;
2042                 }
2043                 if (cur.pos() > cur.lastpos())
2044                         cur.pos() = cur.lastpos();
2045
2046                 break;
2047         }
2048
2049         case LFUN_TABULAR_FEATURE:
2050                 if (!allowsTabularFeatures())
2051                         cur.undispatched();
2052                 else
2053                         InsetMathGrid::doDispatch(cur, cmd);
2054                 break;
2055
2056         default:
2057                 InsetMathGrid::doDispatch(cur, cmd);
2058                 break;
2059         }
2060 }
2061
2062
2063 namespace {
2064
2065 bool allowDisplayMath(Cursor const & cur)
2066 {
2067         LATTEST(cur.depth() > 1);
2068         Cursor tmpcur = cur;
2069         tmpcur.pop();
2070         FuncStatus status;
2071         FuncRequest cmd(LFUN_MATH_DISPLAY);
2072         return tmpcur.getStatus(cmd, status) && status.enabled();
2073 }
2074
2075 } // namespace
2076
2077
2078 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
2079                 FuncStatus & status) const
2080 {
2081         switch (cmd.action()) {
2082         case LFUN_FINISHED_BACKWARD:
2083         case LFUN_FINISHED_FORWARD:
2084         case LFUN_FINISHED_RIGHT:
2085         case LFUN_FINISHED_LEFT:
2086         case LFUN_UP:
2087         case LFUN_DOWN:
2088         case LFUN_NEWLINE_INSERT:
2089         case LFUN_MATH_EXTERN:
2090                 // we handle these
2091                 status.setEnabled(true);
2092                 return true;
2093
2094         // we never allow this in math, and we want to bind enter
2095         // to another actions in command-alternatives
2096         case LFUN_PARAGRAPH_BREAK:
2097                 status.setEnabled(false);
2098                 return true;
2099         case LFUN_MATH_MUTATE: {
2100                 HullType const ht = hullType(cmd.argument());
2101                 status.setOnOff(type_ == ht);
2102                 status.setEnabled(isMutable(ht) && isMutable(type_));
2103
2104                 if (ht != hullSimple && status.enabled())
2105                         status.setEnabled(allowDisplayMath(cur));
2106                 return true;
2107         }
2108         case LFUN_MATH_DISPLAY: {
2109                 status.setEnabled(display() != Inline || allowDisplayMath(cur));
2110                 status.setOnOff(display() != Inline);
2111                 return true;
2112         }
2113
2114         case LFUN_MATH_NUMBER_TOGGLE:
2115                 // FIXME: what is the right test, this or the one of
2116                 // LABEL_INSERT?
2117                 status.setEnabled(display() != Inline);
2118                 status.setOnOff(numberedType());
2119                 return true;
2120
2121         case LFUN_MATH_NUMBER_LINE_TOGGLE: {
2122                 // FIXME: what is the right test, this or the one of
2123                 // LABEL_INSERT?
2124                 bool const enable = (type_ == hullMultline)
2125                         ? (nrows() - 1 == cur.row())
2126                         : display() != Inline;
2127                 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2128                 status.setEnabled(enable);
2129                 status.setOnOff(enable && numbered(r));
2130                 return true;
2131         }
2132
2133         case LFUN_LABEL_INSERT:
2134                 status.setEnabled(type_ != hullSimple);
2135                 return true;
2136
2137         case LFUN_LABEL_COPY_AS_REFERENCE: {
2138                 bool enabled = false;
2139                 if (cmd.argument().empty() && &cur.inset() == this) {
2140                         // if there is no argument and we're inside math, we retrieve
2141                         // the row number from the cursor position.
2142                         row_type row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2143                         enabled = numberedType() && label_[row] && numbered(row);
2144                 } else {
2145                         // if there is an argument, find the corresponding label, else
2146                         // check whether there is at least one label.
2147                         for (row_type row = 0; row != nrows(); ++row) {
2148                                 if (numbered(row) && label_[row] &&
2149                                         (cmd.argument().empty() || label(row) == cmd.argument())) {
2150                                                 enabled = true;
2151                                                 break;
2152                                 }
2153                         }
2154                 }
2155                 status.setEnabled(enabled);
2156                 return true;
2157         }
2158
2159         case LFUN_INSET_INSERT:
2160                 if (cmd.getArg(0) == "label") {
2161                         status.setEnabled(type_ != hullSimple);
2162                         return true;
2163                 }
2164                 return InsetMathGrid::getStatus(cur, cmd, status);
2165
2166         case LFUN_TABULAR_FEATURE: {
2167                 if (!allowsTabularFeatures())
2168                         return false;
2169                 string s = cmd.getArg(0);
2170                 if (!rowChangeOK()
2171                     && (s == "append-row"
2172                         || s == "delete-row"
2173                         || s == "copy-row")) {
2174                         status.message(bformat(
2175                                 from_utf8(N_("Can't change number of rows in '%1$s'")),
2176                                 hullName(type_)));
2177                         status.setEnabled(false);
2178                         return true;
2179                 }
2180                 if (!colChangeOK()
2181                     && (s == "append-column"
2182                         || s == "delete-column"
2183                         || s == "copy-column")) {
2184                         status.message(bformat(
2185                                 from_utf8(N_("Can't change number of columns in '%1$s'")),
2186                                 hullName(type_)));
2187                         status.setEnabled(false);
2188                         return true;
2189                 }
2190                 if (s == "add-vline-left" || s == "add-vline-right") {
2191                         status.message(bformat(
2192                                 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2193                                 hullName(type_)));
2194                         status.setEnabled(false);
2195                         return true;
2196                 }
2197                 if (s == "valign-top" || s == "valign-middle"
2198                  || s == "valign-bottom" || s == "align-left"
2199                  || s == "align-center" || s == "align-right") {
2200                         status.setEnabled(false);
2201                         return true;
2202                 }
2203                 return InsetMathGrid::getStatus(cur, cmd, status);
2204         }
2205
2206         default:
2207                 return InsetMathGrid::getStatus(cur, cmd, status);
2208         }
2209 }
2210
2211
2212 int InsetMathHull::leftMargin() const
2213 {
2214         return (getType() == hullSimple) ? 0 : InsetMathGrid::leftMargin();
2215 }
2216
2217
2218 int InsetMathHull::rightMargin() const
2219 {
2220         return (getType() == hullSimple) ? 0 : InsetMathGrid::rightMargin();
2221 }
2222
2223
2224 int InsetMathHull::border() const
2225 {
2226         return (getType() == hullSimple) ? 0 : InsetMathGrid::border();
2227 }
2228
2229
2230 /////////////////////////////////////////////////////////////////////
2231
2232
2233
2234 // simply scrap this function if you want
2235 void InsetMathHull::mutateToText()
2236 {
2237 #if 0
2238         // translate to latex
2239         ostringstream os;
2240         latex(os, false, false);
2241         string str = os.str();
2242
2243         // insert this text
2244         Text * lt = view_->cursor().innerText();
2245         string::const_iterator cit = str.begin();
2246         string::const_iterator end = str.end();
2247         for (; cit != end; ++cit)
2248                 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2249
2250         // remove ourselves
2251         //dispatch(LFUN_ESCAPE);
2252 #endif
2253 }
2254
2255
2256 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2257         docstring const & font)
2258 {
2259         // this whole function is a hack and won't work for incremental font
2260         // changes...
2261         cur.recordUndo();
2262         if (cur.inset().asInsetMath()->name() == font)
2263                 cur.handleFont(to_utf8(font));
2264         else {
2265                 cur.handleNest(createInsetMath(font, cur.buffer()));
2266                 cur.insert(arg);
2267         }
2268 }
2269
2270
2271 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2272 {
2273         cur.recordUndo();
2274         Font font;
2275         bool b;
2276         font.fromString(to_utf8(arg), b);
2277         if (font.fontInfo().color() != Color_inherit) {
2278                 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2279                 cur.handleNest(at);
2280         }
2281 }
2282
2283
2284 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2285 {
2286         InsetMathNest::edit(cur, front, entry_from);
2287         // The inset formula dimension is not necessarily the same as the
2288         // one of the instant preview image, so we have to indicate to the
2289         // BufferView that a metrics update is needed.
2290         cur.screenUpdateFlags(Update::Force);
2291 }
2292
2293
2294 /////////////////////////////////////////////////////////////////////
2295
2296
2297 #if 0
2298 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
2299                                      bool, bool)
2300 {
2301         // FIXME: completely broken
2302         static InsetMathHull * lastformula = 0;
2303         static CursorBase current = DocIterator(ibegin(nucleus()));
2304         static MathData ar;
2305         static string laststr;
2306
2307         if (lastformula != this || laststr != str) {
2308                 //lyxerr << "reset lastformula to " << this << endl;
2309                 lastformula = this;
2310                 laststr = str;
2311                 current = ibegin(nucleus());
2312                 ar.clear();
2313                 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2314         } else {
2315                 increment(current);
2316         }
2317         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2318
2319         for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2320                 CursorSlice & top = it.back();
2321                 MathData const & a = top.asInsetMath()->cell(top.idx_);
2322                 if (a.matchpart(ar, top.pos_)) {
2323                         bv->cursor().setSelection(it, ar.size());
2324                         current = it;
2325                         top.pos_ += ar.size();
2326                         bv->update();
2327                         return true;
2328                 }
2329         }
2330
2331         //lyxerr << "not found!" << endl;
2332         lastformula = 0;
2333         return false;
2334 }
2335 #endif
2336
2337
2338 void InsetMathHull::write(ostream & os) const
2339 {
2340         odocstringstream oss;
2341         otexrowstream ots(oss);
2342         WriteStream wi(ots, false, false, WriteStream::wsDefault);
2343         oss << "Formula ";
2344         write(wi);
2345         os << to_utf8(oss.str());
2346 }
2347
2348
2349 void InsetMathHull::read(Lexer & lex)
2350 {
2351         MathAtom at;
2352         mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2353         operator=(*at->asHullInset());
2354 }
2355
2356
2357 bool InsetMathHull::readQuiet(Lexer & lex)
2358 {
2359         MathAtom at;
2360         bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2361         if (success)
2362                 operator=(*at->asHullInset());
2363         return success;
2364 }
2365
2366
2367 int InsetMathHull::plaintext(odocstringstream & os,
2368         OutputParams const & op, size_t max_length) const
2369 {
2370         // Try enabling this now that there is a flag as requested at #2275.
2371         if (buffer().isExporting() && display()) {
2372                 Dimension dim;
2373                 TextMetricsInfo mi;
2374                 metricsT(mi, dim);
2375                 TextPainter tpain(dim.width(), dim.height());
2376                 drawT(tpain, 0, dim.ascent());
2377                 tpain.show(os, 3);
2378                 // reset metrics cache to "real" values
2379                 //metrics();
2380                 return tpain.textheight();
2381         }
2382
2383         odocstringstream oss;
2384         otexrowstream ots(oss);
2385         Encoding const * const enc = encodings.fromLyXName("utf8");
2386         WriteStream wi(ots, false, true, WriteStream::wsDefault, enc);
2387
2388         // Fix Bug #6139
2389         if (type_ == hullRegexp)
2390                 write(wi);
2391         else {
2392                 for (row_type r = 0; r < nrows(); ++r) {
2393                         for (col_type c = 0; c < ncols(); ++c)
2394                                 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2395                         // if it's for the TOC, we write just the first line
2396                         // and do not include the newline.
2397                         if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2398                                 break;
2399                         if (r < nrows() - 1)
2400                                 wi << "\n";
2401                 }
2402         }
2403         docstring const str = oss.str();
2404         os << str;
2405         return str.size();
2406 }
2407
2408
2409 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
2410 {
2411         MathStream ms(os);
2412         int res = 0;
2413         docstring name;
2414         if (getType() == hullSimple)
2415                 name = from_ascii("inlineequation");
2416         else
2417                 name = from_ascii("informalequation");
2418
2419         docstring bname = name;
2420         if (!label(0).empty())
2421                 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
2422
2423         ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
2424
2425         odocstringstream ls;
2426         otexstream ols(ls);
2427         if (runparams.flavor == OutputParams::XML) {
2428                 ms << MTag("alt role='tex' ");
2429                 // Workaround for db2latex: db2latex always includes equations with
2430                 // \ensuremath{} or \begin{display}\end{display}
2431                 // so we strip LyX' math environment
2432                 WriteStream wi(ols, false, false, WriteStream::wsDefault, runparams.encoding);
2433                 InsetMathGrid::write(wi);
2434                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
2435                 ms << ETag("alt");
2436                 ms << MTag("math");
2437                 ms << ETag("alt");
2438                 ms << MTag("math");
2439                 InsetMathGrid::mathmlize(ms);
2440                 ms << ETag("math");
2441         } else {
2442                 ms << MTag("alt role='tex'");
2443                 latex(ols, runparams);
2444                 res = ols.texrow().rows();
2445                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
2446                 ms << ETag("alt");
2447         }
2448
2449         ms << from_ascii("<graphic fileref=\"eqn/");
2450         if (!label(0).empty())
2451                 ms << sgml::cleanID(buffer(), runparams, label(0));
2452         else
2453                 ms << sgml::uniqueID(from_ascii("anon"));
2454
2455         if (runparams.flavor == OutputParams::XML)
2456                 ms << from_ascii("\"/>");
2457         else
2458                 ms << from_ascii("\">");
2459
2460         ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2461
2462         return ms.line() + res;
2463 }
2464
2465
2466 bool InsetMathHull::haveNumbers() const
2467 {
2468         bool havenumbers = false;
2469         // inline formulas are never numbered (bug 7351 part 3)
2470         if (getType() == hullSimple)
2471                 return havenumbers;
2472         for (size_t i = 0; i != numbered_.size(); ++i) {
2473                 if (numbered(i)) {
2474                         havenumbers = true;
2475                         break;
2476                 }
2477         }
2478         return havenumbers;
2479 }
2480
2481
2482 // FIXME XHTML
2483 // We need to do something about alignment here.
2484 //
2485 // This duplicates code from InsetMathGrid, but
2486 // we need access here to number information,
2487 // and we simply do not have that in InsetMathGrid.
2488 void InsetMathHull::htmlize(HtmlStream & os) const
2489 {
2490         bool const havenumbers = haveNumbers();
2491         bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2492
2493         if (!havetable) {
2494                 os << cell(index(0, 0));
2495                 return;
2496         }
2497
2498         os << MTag("table", "class='mathtable'");
2499         for (row_type row = 0; row < nrows(); ++row) {
2500                 os << MTag("tr");
2501                 for (col_type col = 0; col < ncols(); ++col) {
2502                         os << MTag("td");
2503                         os << cell(index(row, col));
2504                         os << ETag("td");
2505                 }
2506                 if (havenumbers) {
2507                         os << MTag("td");
2508                         docstring const & num = numbers_[row];
2509                         if (!num.empty())
2510                                 os << '(' << num << ')';
2511                   os << ETag("td");
2512                 }
2513                 os << ETag("tr");
2514         }
2515         os << ETag("table");
2516 }
2517
2518
2519 // this duplicates code from InsetMathGrid, but
2520 // we need access here to number information,
2521 // and we simply do not have that in InsetMathGrid.
2522 void InsetMathHull::mathmlize(MathStream & os) const
2523 {
2524         bool const havenumbers = haveNumbers();
2525         bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2526
2527         if (havetable)
2528                 os << MTag("mtable");
2529         char const * const celltag = havetable ? "mtd" : "mrow";
2530         // FIXME There does not seem to be wide support at the moment
2531         // for mlabeledtr, so we have to use just mtr for now.
2532         // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2533         char const * const rowtag = "mtr";
2534         for (row_type row = 0; row < nrows(); ++row) {
2535                 if (havetable)
2536                         os << MTag(rowtag);
2537                 for (col_type col = 0; col < ncols(); ++col) {
2538                         os << MTag(celltag)
2539                            << cell(index(row, col))
2540                            << ETag(celltag);
2541                 }
2542                 // fleqn?
2543                 if (havenumbers) {
2544                         os << MTag("mtd");
2545                         docstring const & num = numbers_[row];
2546                         if (!num.empty())
2547                                 os << '(' << num << ')';
2548                   os << ETag("mtd");
2549                 }
2550                 if (havetable)
2551                         os << ETag(rowtag);
2552         }
2553         if (havetable)
2554                 os << ETag("mtable");
2555 }
2556
2557
2558 void InsetMathHull::mathAsLatex(WriteStream & os) const
2559 {
2560         MathEnsurer ensurer(os, false);
2561         bool havenumbers = haveNumbers();
2562         bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2563
2564         if (!havetable) {
2565                 os << cell(index(0, 0));
2566                 return;
2567         }
2568
2569         os << "<table class='mathtable'>";
2570         for (row_type row = 0; row < nrows(); ++row) {
2571                 os << "<tr>";
2572                 for (col_type col = 0; col < ncols(); ++col) {
2573                         os << "<td class='math'>";
2574                         os << cell(index(row, col));
2575                         os << "</td>";
2576                 }
2577                 if (havenumbers) {
2578                         os << "<td>";
2579                         docstring const & num = numbers_[row];
2580                         if (!num.empty())
2581                                 os << '(' << num << ')';
2582                   os << "</td>";
2583                 }
2584                 os << "</tr>";
2585         }
2586         os << "</table>";
2587 }
2588
2589
2590 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2591 {
2592         BufferParams::MathOutput const mathtype =
2593                 buffer().masterBuffer()->params().html_math_output;
2594
2595         bool success = false;
2596
2597         // we output all the labels just at the beginning of the equation.
2598         // this should be fine.
2599         for (size_t i = 0; i != label_.size(); ++i) {
2600                 InsetLabel const * const il = label_[i];
2601                 if (!il)
2602                         continue;
2603                 il->xhtml(xs, op);
2604         }
2605
2606         // FIXME Eventually we would like to do this inset by inset.
2607         if (mathtype == BufferParams::MathML) {
2608                 odocstringstream os;
2609                 MathStream ms(os);
2610                 try {
2611                         mathmlize(ms);
2612                         success = true;
2613                 } catch (MathExportException const &) {}
2614                 if (success) {
2615                         if (getType() == hullSimple)
2616                                 xs << html::StartTag("math",
2617                                                         "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2618                         else
2619                                 xs << html::StartTag("math",
2620                                       "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2621                         xs << XHTMLStream::ESCAPE_NONE
2622                                  << os.str()
2623                                  << html::EndTag("math");
2624                 }
2625         } else if (mathtype == BufferParams::HTML) {
2626                 odocstringstream os;
2627                 HtmlStream ms(os);
2628                 try {
2629                         htmlize(ms);
2630                         success = true;
2631                 } catch (MathExportException const &) {}
2632                 if (success) {
2633                         string const tag = (getType() == hullSimple) ? "span" : "div";
2634                         xs << html::StartTag(tag, "class='formula'", true)
2635                            << XHTMLStream::ESCAPE_NONE
2636                            << os.str()
2637                            << html::EndTag(tag);
2638                 }
2639         }
2640
2641         // what we actually want is this:
2642         // if (
2643         //     ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2644         //       && !success)
2645         //     || mathtype == BufferParams::Images
2646         //    )
2647         // but what follows is equivalent, since we'll enter only if either (a) we
2648         // tried and failed with MathML or HTML or (b) didn't try yet at all but
2649         // aren't doing LaTeX.
2650         //
2651         // so this is for Images.
2652         if (!success && mathtype != BufferParams::LaTeX) {
2653                 graphics::PreviewImage const * pimage = 0;
2654                 if (!op.dryrun) {
2655                         loadPreview(docit_);
2656                         pimage = preview_->getPreviewImage(buffer());
2657                         // FIXME Do we always have png?
2658                 }
2659
2660                 if (pimage || op.dryrun) {
2661                         string const filename = pimage ? pimage->filename().onlyFileName()
2662                                                        : "previewimage.png";
2663                         if (pimage) {
2664                                 // if we are not in the master buffer, then we need to see that the
2665                                 // generated image is copied there; otherwise, preview fails.
2666                                 Buffer const * mbuf = buffer().masterBuffer();
2667                                 if (mbuf != &buffer()) {
2668                                         string mbtmp = mbuf->temppath();
2669                                         FileName const mbufimg(support::addName(mbtmp, filename));
2670                                         pimage->filename().copyTo(mbufimg);
2671                                 }
2672                                 // add the file to the list of files to be exported
2673                                 op.exportdata->addExternalFile("xhtml", pimage->filename());
2674                         }
2675
2676                         string const tag = (getType() == hullSimple) ? "span" : "div";
2677                         xs << html::CR()
2678                            << html::StartTag(tag, "style = \"text-align: center;\"")
2679                                  << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2680                                  << html::EndTag(tag)
2681                                  << html::CR();
2682                         success = true;
2683                 }
2684         }
2685
2686         // so we'll pass this test if we've failed everything else, or
2687         // if mathtype was LaTeX, since we won't have entered any of the
2688         // earlier branches
2689         if (!success /* || mathtype != BufferParams::LaTeX */) {
2690                 // Unfortunately, we cannot use latexString() because we do not want
2691                 // $...$ or whatever.
2692                 odocstringstream ls;
2693                 otexrowstream ots(ls);
2694                 WriteStream wi(ots, false, true, WriteStream::wsPreview);
2695                 ModeSpecifier specifier(wi, MATH_MODE);
2696                 mathAsLatex(wi);
2697                 docstring const latex = ls.str();
2698
2699                 // class='math' allows for use of jsMath
2700                 // http://www.math.union.edu/~dpvc/jsMath/
2701                 // FIXME XHTML
2702                 // probably should allow for some kind of customization here
2703                 string const tag = (getType() == hullSimple) ? "span" : "div";
2704                 xs << html::StartTag(tag, "class='math'")
2705                    << latex
2706                    << html::EndTag(tag)
2707                    << html::CR();
2708         }
2709         return docstring();
2710 }
2711
2712
2713 void InsetMathHull::toString(odocstream & os) const
2714 {
2715         odocstringstream ods;
2716         plaintext(ods, OutputParams(0));
2717         os << ods.str();
2718 }
2719
2720
2721 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2722 {
2723         odocstringstream ods;
2724         OutputParams op(0);
2725         op.for_toc = true;
2726         // FIXME: this results in spilling TeX into the LyXHTML output since the
2727         // outliner is used to generate the LyXHTML list of figures/etc.
2728         plaintext(ods, op);
2729         os += ods.str();
2730 }
2731
2732
2733 string InsetMathHull::contextMenuName() const
2734 {
2735         return "context-math";
2736 }
2737
2738
2739 void InsetMathHull::recordLocation(DocIterator const & di)
2740 {
2741         docit_ = di;
2742 }
2743
2744
2745 bool InsetMathHull::canPaintChange(BufferView const &) const
2746 {
2747         // We let RowPainter do it seamlessly for inline insets
2748         return display() != Inline;
2749 }
2750
2751
2752 } // namespace lyx