]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathHull.cpp
Better mechanism for setting cell height
[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                         if (os.ulemCmd() == WriteStream::UNDERLINE)
128                                 os << "\\raisebox{-\\belowdisplayshortskip}{"
129                                       "\\lyxmathsout{\\parbox[b]{\\linewidth}{";
130                         else
131                                 os << "\\lyxmathsout{\\parbox{\\linewidth}{";
132                 } else if (os.ulemCmd() == WriteStream::UNDERLINE)
133                         os << "\\raisebox{-\\belowdisplayshortskip}{"
134                               "\\parbox[b]{\\linewidth}{";
135                 else if (os.ulemCmd() == WriteStream::STRIKEOUT)
136                         os << "\\parbox{\\linewidth}{";
137         }
138
139
140         // writes a postamble for underlined or struck out math display
141         void writeMathdisplayPostamble(WriteStream & os)
142         {
143                 if (os.strikeoutMath()) {
144                         if (os.ulemCmd() == WriteStream::UNDERLINE)
145                                 os << "}";
146                         os << "}}\\\\\n";
147                 } else if (os.ulemCmd() == WriteStream::UNDERLINE)
148                         os << "}}\\\\\n";
149                 else if (os.ulemCmd() == WriteStream::STRIKEOUT)
150                         os << "}\\\\\n";
151         }
152
153
154 } // namespace
155
156
157 HullType hullType(docstring const & s)
158 {
159         if (s == "none")      return hullNone;
160         if (s == "simple")    return hullSimple;
161         if (s == "equation")  return hullEquation;
162         if (s == "eqnarray")  return hullEqnArray;
163         if (s == "align")     return hullAlign;
164         if (s == "alignat")   return hullAlignAt;
165         if (s == "xalignat")  return hullXAlignAt;
166         if (s == "xxalignat") return hullXXAlignAt;
167         if (s == "multline")  return hullMultline;
168         if (s == "gather")    return hullGather;
169         if (s == "flalign")   return hullFlAlign;
170         if (s == "regexp")    return hullRegexp;
171         lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
172         return hullUnknown;
173 }
174
175
176 docstring hullName(HullType type)
177 {
178         switch (type) {
179         case hullNone:       return from_ascii("none");
180         case hullSimple:     return from_ascii("simple");
181         case hullEquation:   return from_ascii("equation");
182         case hullEqnArray:   return from_ascii("eqnarray");
183         case hullAlign:      return from_ascii("align");
184         case hullAlignAt:    return from_ascii("alignat");
185         case hullXAlignAt:   return from_ascii("xalignat");
186         case hullXXAlignAt:  return from_ascii("xxalignat");
187         case hullMultline:   return from_ascii("multline");
188         case hullGather:     return from_ascii("gather");
189         case hullFlAlign:    return from_ascii("flalign");
190         case hullRegexp:     return from_ascii("regexp");
191         case hullUnknown:
192                 lyxerr << "unknown hull type" << endl;
193                 break;
194         }
195         return from_ascii("none");
196 }
197
198 static InsetLabel * dummy_pointer = 0;
199
200 InsetMathHull::InsetMathHull(Buffer * buf)
201         : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, NUMBER),
202           numbers_(1, empty_docstring()), label_(1, dummy_pointer),
203           preview_(new RenderPreview(this))
204 {
205         //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
206         //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
207         //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
208         //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
209         buffer_ = buf;
210         initMath();
211         setDefaults();
212 }
213
214
215 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
216         : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, NUMBER),
217           numbers_(1, empty_docstring()), label_(1, dummy_pointer),
218           preview_(new RenderPreview(this))
219 {
220         buffer_ = buf;
221         initMath();
222         setDefaults();
223 }
224
225
226 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
227 {
228         operator=(other);
229 }
230
231
232 InsetMathHull::~InsetMathHull()
233 {
234         for (size_t i = 0; i < label_.size(); ++i)
235                 delete label_[i];
236 }
237
238
239 Inset * InsetMathHull::clone() const
240 {
241         return new InsetMathHull(*this);
242 }
243
244
245 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
246 {
247         if (this == &other)
248                 return *this;
249         InsetMathGrid::operator=(other);
250         type_  = other.type_;
251         numbered_ = other.numbered_;
252         numbers_ = other.numbers_;
253         buffer_ = other.buffer_;
254         for (size_t i = 0; i < label_.size(); ++i)
255                 delete label_[i];
256         label_ = other.label_;
257         for (size_t i = 0; i != label_.size(); ++i) {
258                 if (label_[i])
259                         label_[i] = new InsetLabel(*label_[i]);
260         }
261         preview_.reset(new RenderPreview(*other.preview_, this));
262
263         return *this;
264 }
265
266
267 void InsetMathHull::setBuffer(Buffer & buffer)
268 {
269         InsetMathGrid::setBuffer(buffer);
270
271         for (size_t i = 0; i != label_.size(); ++i) {
272                 if (label_[i])
273                         label_[i]->setBuffer(buffer);
274         }
275 }
276
277
278 // FIXME This should really be controlled by the TOC level, or
279 // something of the sort.
280 namespace {
281         const char * counters_to_save[] = {"section", "chapter"};
282         unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
283 } // namespace
284
285
286 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
287 {
288         if (!buffer_) {
289                 //FIXME: buffer_ should be set at creation for this inset! Problem is
290                 // This inset is created at too many places (see Parser::parse1() in
291                 // MathParser.cpp).
292                 return;
293         }
294
295         // if any of the equations are numbered, then we want to save the values
296         // of some of the counters.
297         if (haveNumbers()) {
298                 BufferParams const & bp = buffer_->params();
299                 string const & lang = it->getParLanguage(bp)->code();
300                 Counters & cnts =
301                         buffer_->masterBuffer()->params().documentClass().counters();
302
303                 // right now, we only need to do this at export time
304                 if (utype == OutputUpdate) {
305                         for (size_t i = 0; i < numcnts; ++i) {
306                                 docstring const cnt = from_ascii(counters_to_save[i]);
307                                 if (cnts.hasCounter(cnt))
308                                         counter_map[cnt] = cnts.value(cnt);
309                         }
310                 }
311
312                 // this has to be done separately
313                 docstring const eqstr = from_ascii("equation");
314                 if (cnts.hasCounter(eqstr)) {
315                         if (utype == OutputUpdate)
316                                 counter_map[eqstr] = cnts.value(eqstr);
317                         for (size_t i = 0; i != label_.size(); ++i) {
318                                 if (numbered(i)) {
319                                         cnts.step(eqstr, utype);
320                                         numbers_[i] = cnts.theCounter(eqstr, lang);
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 bool InsetMathHull::idxFirst(Cursor & cur) const
423 {
424         cur.idx() = 0;
425         cur.pos() = 0;
426         return true;
427 }
428
429
430 bool InsetMathHull::idxLast(Cursor & cur) const
431 {
432         cur.idx() = nargs() - 1;
433         cur.pos() = cur.lastpos();
434         return true;
435 }
436
437
438 // FIXME: InsetMathGrid should be changed to let the real column alignment be
439 // given by a virtual method like displayColAlign, because the values produced
440 // by defaultColAlign can be invalidated by lfuns such as add-column. For the
441 // moment the values produced by defaultColAlign are not used, notably because
442 // alignment is not implemented in the LyXHTML output.
443 char InsetMathHull::defaultColAlign(col_type col)
444 {
445         return colAlign(type_, col);
446 }
447
448
449 char InsetMathHull::displayColAlign(idx_type idx) const
450 {
451         switch (type_) {
452         case hullMultline: {
453                 row_type const r = row(idx);
454                 if (r == 0)
455                         return 'l';
456                 if (r == nrows() - 1)
457                         return 'r';
458                 return 'c';
459         }
460         case hullEqnArray:
461         case hullGather:
462         case hullAlign:
463         case hullAlignAt:
464         case hullXAlignAt:
465         case hullXXAlignAt:
466         case hullFlAlign:
467                 return colAlign(type_, col(idx));
468         default:
469                 break;
470         }
471         return InsetMathGrid::displayColAlign(idx);
472 }
473
474
475 int InsetMathHull::displayColSpace(col_type col) const
476 {
477         return colSpace(type_, col);
478 }
479
480
481 // FIXME: same comment as for defaultColAlign applies.
482 int InsetMathHull::defaultColSpace(col_type col)
483 {
484         return colSpace(type_, col);
485 }
486
487
488 string InsetMathHull::standardFont() const
489 {
490         switch (type_) {
491         case hullRegexp:
492                 return "texttt";
493         case hullNone:
494                 return "lyxnochange";
495         default:
496                 return "mathnormal";
497         }
498 }
499
500
501 ColorCode InsetMathHull::standardColor() const
502 {
503         switch (type_) {
504         case hullRegexp:
505         case hullNone:
506                 return Color_foreground;
507
508         default:
509                 return Color_math;
510         }
511 }
512
513
514 bool InsetMathHull::previewState(const BufferView *const bv) const
515 {
516         if (!editing(bv) && RenderPreview::previewMath()
517             && type_ != hullRegexp)
518         {
519                 graphics::PreviewImage const * pimage =
520                         preview_->getPreviewImage(bv->buffer());
521                 return pimage && pimage->image();
522         }
523         return false;
524 }
525
526
527 namespace {
528 static const int ERROR_FRAME_WIDTH = 2;
529 }
530
531 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
532 {
533         if (previewState(mi.base.bv)) {
534                 preview_->metrics(mi, dim);
535                 if (previewTooSmall(dim)) {
536                         // preview image is too small
537                         dim.wid += 2 * ERROR_FRAME_WIDTH;
538                         dim.asc += 2 * ERROR_FRAME_WIDTH;
539                 } else {
540                         // insert a one pixel gap in front of the formula
541                         dim.wid += 1;
542                         if (display())
543                                 dim.des += displayMargin();
544                 }
545                 return;
546         }
547
548         Changer dummy1 = mi.base.changeFontSet(standardFont());
549         Changer dummy2 = mi.base.font.changeStyle(display() ? LM_ST_DISPLAY
550                                                             : LM_ST_TEXT);
551
552         // let the cells adjust themselves
553         InsetMathGrid::metrics(mi, dim);
554
555         if (display()) {
556                 dim.asc += displayMargin();
557                 dim.des += displayMargin();
558         }
559
560         if (numberedType()) {
561                 Changer dummy = mi.base.changeFontSet("mathrm");
562                 int l = 0;
563                 for (row_type row = 0; row < nrows(); ++row)
564                         l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
565
566                 if (l)
567                         // Value was hardcoded to 30 pixels
568                         dim.wid += Length(0.3, Length::IN).inPixels(mi.base) + l;
569         }
570
571         // reserve some space for marker.
572         dim.wid += 2;
573 }
574
575
576 bool InsetMathHull::previewTooSmall(Dimension const & dim) const
577 {
578         return dim.width() <= 10 && dim.height() <= 10;
579 }
580
581
582 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
583 {
584         BufferView const * const bv = pi.base.bv;
585         if (previewState(bv)) {
586                 Dimension const dim = dimension(*pi.base.bv);
587                 if (previewTooSmall(dim))
588                         return Color_error;
589                 return graphics::PreviewLoader::backgroundColor();
590         }
591         return Color_mathbg;
592 }
593
594
595 void InsetMathHull::drawMarkers(PainterInfo & pi, int x, int y) const
596 {
597         ColorCode pen_color = mouseHovered(pi.base.bv) || editing(pi.base.bv)?
598                 Color_mathframe : Color_mathcorners;
599         // If the corners have the same color as the background, do not paint them.
600         if (lcolor.getX11Name(Color_mathbg) == lcolor.getX11Name(pen_color))
601                 return;
602
603         Inset::drawMarkers(pi, x, y);
604         Dimension const dim = dimension(*pi.base.bv);
605         int const t = x + dim.width() - 1;
606         int const a = y - dim.ascent();
607         pi.pain.line(x, a + 3, x, a, pen_color);
608         pi.pain.line(t, a + 3, t, a, pen_color);
609         pi.pain.line(x, a, x + 3, a, pen_color);
610         pi.pain.line(t - 3, a, t, a, pen_color);
611 }
612
613
614 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
615 {
616         Dimension const dim = dimension(*pi.base.bv);
617         if (previewTooSmall(dim)) {
618                 pi.pain.fillRectangle(x, y - 2 * ERROR_FRAME_WIDTH,
619                     dim.wid, dim.asc + dim.des, backgroundColor(pi));
620                 return;
621         }
622         pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
623                         dim.asc + dim.des - 1, pi.backgroundColor(this));
624 }
625
626
627 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
628 {
629         BufferView const * const bv = pi.base.bv;
630         Dimension const dim = dimension(*bv);
631
632         if (type_ == hullRegexp)
633                 pi.pain.rectangle(x + 2, y - dim.ascent() + 1,
634                                   dim.width() - 3, dim.height() - 2, Color_regexpframe);
635
636         if (previewState(bv)) {
637                 // Do not draw change tracking cue if taken care of by RowPainter
638                 // already.
639                 Changer dummy = !canPaintChange(*bv) ? make_change(pi.change_, Change())
640                         : Changer();
641                 if (previewTooSmall(dim)) {
642                         // we have an extra frame
643                         preview_->draw(pi, x + ERROR_FRAME_WIDTH, y);
644                 } else {
645                         // one pixel gap in front
646                         preview_->draw(pi, x + 1, y);
647                 }
648                 return;
649         }
650
651         ColorCode color = pi.selected && lyxrc.use_system_colors
652                                 ? Color_selectiontext : standardColor();
653         bool const really_change_color = pi.base.font.color() == Color_none;
654         Changer dummy0 = really_change_color ? pi.base.font.changeColor(color)
655                 : Changer();
656         Changer dummy1 = pi.base.changeFontSet(standardFont());
657         Changer dummy2 = pi.base.font.changeStyle(display() ? LM_ST_DISPLAY
658                                                             : LM_ST_TEXT);
659
660         int xmath = x;
661         BufferParams::MathNumber const math_number = buffer().params().getMathNumber();
662         if (numberedType() && math_number == BufferParams::LEFT) {
663                 Changer dummy = pi.base.changeFontSet("mathrm");
664                 int l = 0;
665                 for (row_type row = 0; row < nrows(); ++row)
666                         l = max(l, mathed_string_width(pi.base.font, nicelabel(row)));
667
668                 if (l)
669                         // Value was hardcoded to 30 pixels
670                         xmath += Length(0.3, Length::IN).inPixels(pi.base) + l;
671         }
672
673         InsetMathGrid::draw(pi, xmath + 1, y);
674         drawMarkers(pi, x, y);
675
676         if (numberedType()) {
677                 Changer dummy = pi.base.changeFontSet("mathrm");
678                 for (row_type row = 0; row < nrows(); ++row) {
679                         int const yy = y + rowinfo_[row].offset_;
680                         docstring const nl = nicelabel(row);
681                         if (math_number == BufferParams::LEFT)
682                                 pi.draw(x, yy, nl);
683                         else {
684                                 int l = mathed_string_width(pi.base.font, nl);
685                                 pi.draw(x + dim.wid - l, yy, nl);
686                         }
687                 }
688         }
689
690         // drawing change line
691         if (canPaintChange(*bv))
692                 pi.change_.paintCue(pi, x + 1, y + 1 - dim.asc,
693                                     x + dim.wid, y + dim.des);
694 }
695
696
697 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
698 {
699         if (display()) {
700                 InsetMathGrid::metricsT(mi, dim);
701         } else {
702                 odocstringstream os;
703                 otexrowstream ots(os);
704                 WriteStream wi(ots, false, true, WriteStream::wsDefault);
705                 write(wi);
706                 dim.wid = os.str().size();
707                 dim.asc = 1;
708                 dim.des = 0;
709         }
710 }
711
712
713 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
714 {
715         if (display()) {
716                 InsetMathGrid::drawT(pain, x, y);
717         } else {
718                 odocstringstream os;
719                 otexrowstream ots(os);
720                 WriteStream wi(ots, false, true, WriteStream::wsDefault);
721                 write(wi);
722                 pain.draw(x, y, os.str().c_str());
723         }
724 }
725
726
727 static docstring latexString(InsetMathHull const & inset)
728 {
729         odocstringstream ls;
730         // This has to be static, because a preview snippet or a math
731         // macro containing math in text mode (such as $\text{$\phi$}$ or
732         // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
733         // first time as a whole, and the second time only the inner math.
734         // In this last case inset.buffer() would be invalid.
735         static Encoding const * encoding = 0;
736         if (inset.isBufferValid())
737                 encoding = &(inset.buffer().params().encoding());
738         otexrowstream ots(ls);
739         WriteStream wi(ots, false, true, WriteStream::wsPreview, encoding);
740         inset.write(wi);
741         return ls.str();
742 }
743
744
745 void InsetMathHull::initUnicodeMath() const
746 {
747         // Trigger classification of the unicode symbols in this inset
748         docstring const dummy = latexString(*this);
749 }
750
751
752 void InsetMathHull::addPreview(DocIterator const & inset_pos,
753         graphics::PreviewLoader & /*ploader*/) const
754 {
755         if (RenderPreview::previewMath()) {
756                 preparePreview(inset_pos);
757         }
758 }
759
760
761 void InsetMathHull::usedMacros(MathData const & md, DocIterator const & pos,
762                                MacroNameSet & macros, MacroNameSet & defs) const
763 {
764         MacroNameSet::iterator const end = macros.end();
765
766         for (size_t i = 0; i < md.size(); ++i) {
767                 InsetMathMacro const * mi = md[i].nucleus()->asMacro();
768                 InsetMathMacroTemplate const * mt = md[i].nucleus()->asMacroTemplate();
769                 InsetMathScript const * si = md[i].nucleus()->asScriptInset();
770                 InsetMathFracBase const * fi = md[i].nucleus()->asFracBaseInset();
771                 InsetMathGrid const * gi = md[i].nucleus()->asGridInset();
772                 InsetMathNest const * ni = md[i].nucleus()->asNestInset();
773                 if (mi) {
774                         // Look for macros in the arguments of this macro.
775                         for (idx_type idx = 0; idx < mi->nargs(); ++idx)
776                                 usedMacros(mi->cell(idx), pos, macros, defs);
777                         // Make sure this is a macro defined in the document
778                         // (as we also spot the macros in the symbols file)
779                         // or that we have not already accounted for it.
780                         docstring const name = mi->name();
781                         if (macros.find(name) == end)
782                                 continue;
783                         macros.erase(name);
784                         // Look for macros in the definition of this macro.
785                         MathData ar(pos.buffer());
786                         MacroData const * data =
787                                 pos.buffer()->getMacro(name, pos, true);
788                         if (data) {
789                                 odocstringstream macro_def;
790                                 data->write(macro_def, true);
791                                 macro_def << endl;
792                                 defs.insert(macro_def.str());
793                                 asArray(data->definition(), ar);
794                         }
795                         usedMacros(ar, pos, macros, defs);
796                 } else if (mt) {
797                         MathData ar(pos.buffer());
798                         asArray(mt->definition(), ar);
799                         usedMacros(ar, pos, macros, defs);
800                 } else if (si) {
801                         if (!si->nuc().empty())
802                                 usedMacros(si->nuc(), pos, macros, defs);
803                         if (si->hasDown())
804                                 usedMacros(si->down(), pos, macros, defs);
805                         if (si->hasUp())
806                                 usedMacros(si->up(), pos, macros, defs);
807                 } else if (fi || gi) {
808                         idx_type nidx = fi ? fi->nargs() : gi->nargs();
809                         for (idx_type idx = 0; idx < nidx; ++idx)
810                                 usedMacros(fi ? fi->cell(idx) : gi->cell(idx),
811                                            pos, macros, defs);
812                 } else if (ni) {
813                         usedMacros(ni->cell(0), pos, macros, defs);
814                 }
815         }
816 }
817
818
819 void InsetMathHull::preparePreview(DocIterator const & pos,
820                                    bool forexport) const
821 {
822         // there is no need to do all the macro stuff if we're not
823         // actually going to generate the preview.
824         if (!RenderPreview::previewMath() && !forexport)
825                 return;
826
827         Buffer const * buffer = pos.buffer();
828
829         // collect macros at this position
830         MacroNameSet macros;
831         buffer->listMacroNames(macros);
832
833         // collect definitions only for the macros used in this inset
834         MacroNameSet defs;
835         for (idx_type idx = 0; idx < nargs(); ++idx)
836                 usedMacros(cell(idx), pos, macros, defs);
837
838         MacroNameSet::iterator it = defs.begin();
839         MacroNameSet::iterator end = defs.end();
840         docstring macro_preamble;
841         for (; it != end; ++it)
842                 macro_preamble.append(*it);
843
844         // set the font series and size for this snippet
845         DocIterator dit = pos.getInnerText();
846         Paragraph const & par = dit.paragraph();
847         Font font = par.getFontSettings(buffer->params(), dit.pos());
848         font.fontInfo().realize(par.layout().font);
849         string const lsize = font.latexSize();
850         docstring setfont;
851         docstring endfont;
852         if (font.fontInfo().series() == BOLD_SERIES) {
853                 setfont += from_ascii("\\textbf{");
854                 endfont += '}';
855         }
856         if (lsize != "normalsize" && !prefixIs(lsize, "error"))
857                 setfont += from_ascii("\\" + lsize + '\n');
858
859         docstring setcnt;
860         if (forexport && haveNumbers()) {
861                 docstring eqstr = from_ascii("equation");
862                 CounterMap::const_iterator it = counter_map.find(eqstr);
863                 if (it != counter_map.end()) {
864                         int num = it->second;
865                         if (num >= 0)
866                                 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
867                                           '{' + convert<docstring>(num) + '}' + '\n';
868                 }
869                 for (size_t i = 0; i != numcnts; ++i) {
870                         docstring cnt = from_ascii(counters_to_save[i]);
871                         it = counter_map.find(cnt);
872                         if (it == counter_map.end())
873                                         continue;
874                         int num = it->second;
875                         if (num > 0)
876                                 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
877                                           '{' + convert<docstring>(num) + '}';
878                 }
879         }
880         docstring const snippet = macro_preamble + setfont + setcnt
881                                   + latexString(*this) + endfont;
882         LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
883         preview_->addPreview(snippet, *buffer, forexport);
884 }
885
886
887 void InsetMathHull::reloadPreview(DocIterator const & pos) const
888 {
889         preparePreview(pos);
890         preview_->startLoading(*pos.buffer());
891 }
892
893
894 void InsetMathHull::loadPreview(DocIterator const & pos) const
895 {
896         bool const forexport = true;
897         preparePreview(pos, forexport);
898         preview_->startLoading(*pos.buffer(), forexport);
899 }
900
901
902 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
903 {
904         if (RenderPreview::previewMath()) {
905                 reloadPreview(old);
906                 cur.screenUpdateFlags(Update::Force);
907         }
908         return false;
909 }
910
911
912 docstring InsetMathHull::label(row_type row) const
913 {
914         LASSERT(row < nrows(), return docstring());
915         if (InsetLabel * il = label_[row])
916                 return il->screenLabel();
917         return docstring();
918 }
919
920
921 void InsetMathHull::label(row_type row, docstring const & label)
922 {
923         //lyxerr << "setting label '" << label << "' for row " << row << endl;
924         if (label_[row]) {
925                 if (label.empty()) {
926                         delete label_[row];
927                         label_[row] = dummy_pointer;
928                 } else {
929                         if (buffer_)
930                                 label_[row]->updateLabelAndRefs(label);
931                         else
932                                 label_[row]->setParam("name", label);
933                 }
934                 return;
935         }
936         InsetCommandParams p(LABEL_CODE);
937         p["name"] = label;
938         label_[row] = new InsetLabel(buffer_, p);
939         if (buffer_)
940                 label_[row]->setBuffer(buffer());
941 }
942
943
944 void InsetMathHull::numbered(row_type row, Numbered num)
945 {
946         numbered_[row] = num;
947         if (!numbered(row) && label_[row]) {
948                 delete label_[row];
949                 label_[row] = 0;
950         }
951 }
952
953
954 bool InsetMathHull::numbered(row_type row) const
955 {
956         return numbered_[row] == NUMBER;
957 }
958
959
960 bool InsetMathHull::ams() const
961 {
962         switch (type_) {
963         case hullAlign:
964         case hullFlAlign:
965         case hullMultline:
966         case hullGather:
967         case hullAlignAt:
968         case hullXAlignAt:
969         case hullXXAlignAt:
970                 return true;
971         case hullUnknown:
972         case hullRegexp:
973                 return false;
974         case hullNone:
975         case hullSimple:
976         case hullEquation:
977         case hullEqnArray:
978                 break;
979         }
980         for (size_t row = 0; row < numbered_.size(); ++row)
981                 if (numbered_[row] == NOTAG)
982                         return true;
983         return false;
984 }
985
986
987 bool InsetMathHull::outerDisplay() const
988 {
989         switch (type_) {
990         case hullEquation:
991         case hullEqnArray:
992         case hullAlign:
993         case hullFlAlign:
994         case hullGather:
995         case hullMultline:
996                 return true;
997         case hullNone:
998         case hullSimple:
999         case hullAlignAt:
1000         case hullXAlignAt:
1001         case hullXXAlignAt:
1002         case hullUnknown:
1003         case hullRegexp:
1004                 break;
1005         }
1006         return false;
1007 }
1008
1009
1010 Inset::DisplayType InsetMathHull::display() const
1011 {
1012         switch (type_) {
1013         case hullUnknown:
1014         case hullSimple:
1015         case hullNone:
1016         case hullRegexp:
1017                 return Inline;
1018         case hullEqnArray:
1019         case hullAlign:
1020         case hullFlAlign:
1021         case hullAlignAt:
1022         case hullXAlignAt:
1023         case hullXXAlignAt:
1024         case hullEquation:
1025         case hullMultline:
1026         case hullGather:
1027                 if (buffer().params().is_math_indent)
1028                         return AlignLeft;
1029                 else
1030                         return AlignCenter;
1031         }
1032         // avoid warning
1033         return AlignCenter;
1034 }
1035
1036
1037 int InsetMathHull::indent(BufferView const & bv) const
1038 {
1039         // FIXME: set this in the textclass. This value is what the article class uses.
1040         static Length default_indent(2.5, Length::EM);
1041         if (display() != Inline && buffer().params().is_math_indent) {
1042                 Length const & len = buffer().params().getMathIndent();
1043                 if (len.empty())
1044                         return bv.inPixels(default_indent);
1045                 else
1046                         return bv.inPixels(len);
1047         } else
1048                 return Inset::indent(bv);
1049 }
1050
1051
1052 bool InsetMathHull::numberedType() const
1053 {
1054         switch (type_) {
1055         case hullUnknown:
1056         case hullNone:
1057         case hullSimple:
1058         case hullXXAlignAt:
1059         case hullRegexp:
1060                 return false;
1061         case hullEqnArray:
1062         case hullAlign:
1063         case hullFlAlign:
1064         case hullAlignAt:
1065         case hullXAlignAt:
1066         case hullEquation:
1067         case hullMultline:
1068         case hullGather:
1069                 break;
1070         }
1071         for (row_type row = 0; row < nrows(); ++row)
1072                 if (numbered(row))
1073                         return true;
1074         return false;
1075 }
1076
1077
1078 void InsetMathHull::validate(LaTeXFeatures & features) const
1079 {
1080         if (features.runparams().isLaTeX()) {
1081                 if (ams())
1082                         features.require("amsmath");
1083
1084                 if (type_ == hullRegexp) {
1085                         features.require("color");
1086                         docstring frcol = from_utf8(lcolor.getLaTeXName(Color_regexpframe));
1087                         docstring bgcol = from_ascii("white");
1088                         features.addPreambleSnippet(
1089                                 "\\newcommand{\\regexp}[1]{\\fcolorbox{"
1090                                 + frcol + "}{"
1091                                 + bgcol + "}{\\ensuremath{\\mathtt{#1}}}}");
1092                         features.addPreambleSnippet(
1093                                 from_ascii("\\newcommand{\\endregexp}{}"));
1094                 } else if (outerDisplay() && features.inDeletedInset()
1095                            && !features.mustProvide("ct-dvipost")) {
1096                                 features.require("ct-tikz-math-sout");
1097                 }
1098
1099                 // Validation is necessary only if not using AMS math.
1100                 // To be safe, we will always run mathedvalidate.
1101                 //if (features.amsstyle)
1102                 //  return;
1103
1104                 //features.binom      = true;
1105         } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
1106                 // it would be better to do this elsewhere, but we can't validate in
1107                 // InsetMathMatrix and we have no way, outside MathExtern, to know if
1108                 // we even have any matrices.
1109                                 features.addCSSSnippet(
1110                                         "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
1111                                         "table.matrix td{padding: 0.25px;}\n"
1112                                         "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
1113                                         "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
1114         }
1115         InsetMathGrid::validate(features);
1116 }
1117
1118
1119 void InsetMathHull::header_write(WriteStream & os) const
1120 {
1121         bool n = numberedType();
1122
1123         switch(type_) {
1124         case hullNone:
1125                 break;
1126
1127         case hullSimple:
1128                 if (os.ulemCmd())
1129                         os << "\\mbox{";
1130                 os << '$';
1131                 os.startOuterRow();
1132                 if (cell(0).empty())
1133                         os << ' ';
1134                 break;
1135
1136         case hullEquation:
1137                 writeMathdisplayPreamble(os);
1138                 os << "\n";
1139                 os.startOuterRow();
1140                 if (n)
1141                         os << "\\begin{equation" << star(n) << "}\n";
1142                 else
1143                         os << "\\[\n";
1144                 break;
1145
1146         case hullEqnArray:
1147         case hullAlign:
1148         case hullFlAlign:
1149         case hullGather:
1150         case hullMultline:
1151                 writeMathdisplayPreamble(os);
1152                 os << "\n";
1153                 os.startOuterRow();
1154                 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
1155                 break;
1156
1157         case hullAlignAt:
1158         case hullXAlignAt:
1159                 os << "\n";
1160                 os.startOuterRow();
1161                 os << "\\begin{" << hullName(type_) << star(n) << '}'
1162                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1163                 break;
1164
1165         case hullXXAlignAt:
1166                 os << "\n";
1167                 os.startOuterRow();
1168                 os << "\\begin{" << hullName(type_) << '}'
1169                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
1170                 break;
1171
1172         case hullRegexp:
1173                 os << "\\regexp{";
1174                 break;
1175
1176         case hullUnknown:
1177                 os << "\n";
1178                 os.startOuterRow();
1179                 os << "\\begin{unknown" << star(n) << "}\n";
1180                 break;
1181         }
1182 }
1183
1184
1185 void InsetMathHull::footer_write(WriteStream & os) const
1186 {
1187         bool n = numberedType();
1188
1189         switch(type_) {
1190         case hullNone:
1191                 os << "\n";
1192                 break;
1193
1194         case hullSimple:
1195                 os << '$';
1196                 if (os.ulemCmd())
1197                         os << "}";
1198                 break;
1199
1200         case hullEquation:
1201                 os << "\n";
1202                 os.startOuterRow();
1203                 if (n)
1204                         os << "\\end{equation" << star(n) << "}\n";
1205                 else
1206                         os << "\\]\n";
1207                 writeMathdisplayPostamble(os);
1208                 break;
1209
1210         case hullEqnArray:
1211         case hullAlign:
1212         case hullFlAlign:
1213         case hullGather:
1214         case hullMultline:
1215                 os << "\n";
1216                 os.startOuterRow();
1217                 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1218                 writeMathdisplayPostamble(os);
1219                 break;
1220
1221         case hullAlignAt:
1222         case hullXAlignAt:
1223                 os << "\n";
1224                 os.startOuterRow();
1225                 os << "\\end{" << hullName(type_) << star(n) << "}\n";
1226                 break;
1227
1228         case hullXXAlignAt:
1229                 os << "\n";
1230                 os.startOuterRow();
1231                 os << "\\end{" << hullName(type_) << "}\n";
1232                 break;
1233
1234         case hullRegexp:
1235                 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1236                 os << "\\endregexp{}}";
1237                 break;
1238
1239         case hullUnknown:
1240                 os << "\n";
1241                 os.startOuterRow();
1242                 os << "\\end{unknown" << star(n) << "}\n";
1243                 break;
1244         }
1245 }
1246
1247
1248 bool InsetMathHull::allowsTabularFeatures() const
1249 {
1250         switch (type_) {
1251         case hullEqnArray:
1252         case hullAlign:
1253         case hullAlignAt:
1254         case hullXAlignAt:
1255         case hullXXAlignAt:
1256         case hullFlAlign:
1257         case hullMultline:
1258         case hullGather:
1259                 return true;
1260         case hullNone:
1261         case hullSimple:
1262         case hullEquation:
1263         case hullRegexp:
1264         case hullUnknown:
1265                 break;
1266         }
1267         return false;
1268 }
1269
1270
1271 bool InsetMathHull::rowChangeOK() const
1272 {
1273         return
1274                 type_ == hullEqnArray || type_ == hullAlign ||
1275                 type_ == hullFlAlign || type_ == hullAlignAt ||
1276                 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1277                 type_ == hullGather || type_ == hullMultline;
1278 }
1279
1280
1281 bool InsetMathHull::colChangeOK() const
1282 {
1283         return
1284                 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1285                 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1286 }
1287
1288
1289 void InsetMathHull::addRow(row_type row)
1290 {
1291         if (!rowChangeOK())
1292                 return;
1293
1294         bool numbered = numberedType();
1295         // Move the number and raw pointer, do not call label() (bug 7511)
1296         InsetLabel * label = dummy_pointer;
1297         docstring number = empty_docstring();
1298         if (type_ == hullMultline) {
1299                 if (row + 1 == nrows())  {
1300                         numbered_[row] = NONUMBER;
1301                         swap(label, label_[row]);
1302                         swap(number, numbers_[row]);
1303                 } else
1304                         numbered = false;
1305         }
1306
1307         numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1308         numbers_.insert(numbers_.begin() + row + 1, number);
1309         label_.insert(label_.begin() + row + 1, label);
1310         InsetMathGrid::addRow(row);
1311 }
1312
1313
1314 void InsetMathHull::swapRow(row_type row)
1315 {
1316         if (nrows() <= 1)
1317                 return;
1318         if (row + 1 == nrows())
1319                 --row;
1320         swap(numbered_[row], numbered_[row + 1]);
1321         swap(numbers_[row], numbers_[row + 1]);
1322         swap(label_[row], label_[row + 1]);
1323         InsetMathGrid::swapRow(row);
1324 }
1325
1326
1327 void InsetMathHull::delRow(row_type row)
1328 {
1329         if (nrows() <= 1 || !rowChangeOK())
1330                 return;
1331         if (row + 1 == nrows() && type_ == hullMultline) {
1332                 swap(numbered_[row - 1], numbered_[row]);
1333                 swap(numbers_[row - 1], numbers_[row]);
1334                 swap(label_[row - 1], label_[row]);
1335                 InsetMathGrid::delRow(row);
1336                 return;
1337         }
1338         InsetMathGrid::delRow(row);
1339         // The last dummy row has no number info nor a label.
1340         // Test nrows() + 1 because we have already erased the row.
1341         if (row == nrows() + 1)
1342                 row--;
1343         numbered_.erase(numbered_.begin() + row);
1344         numbers_.erase(numbers_.begin() + row);
1345         delete label_[row];
1346         label_.erase(label_.begin() + row);
1347 }
1348
1349
1350 void InsetMathHull::addCol(col_type col)
1351 {
1352         if (!colChangeOK())
1353                 return;
1354         InsetMathGrid::addCol(col);
1355 }
1356
1357
1358 void InsetMathHull::delCol(col_type col)
1359 {
1360         if (ncols() <= 1 || !colChangeOK())
1361                 return;
1362         InsetMathGrid::delCol(col);
1363 }
1364
1365
1366 docstring InsetMathHull::nicelabel(row_type row) const
1367 {
1368         if (!numbered(row))
1369                 return docstring();
1370         docstring const & val = numbers_[row];
1371         if (!label_[row])
1372                 return '(' + val + ')';
1373         return '(' + val + ',' + label_[row]->screenLabel() + ')';
1374 }
1375
1376
1377 void InsetMathHull::glueall(HullType type)
1378 {
1379         MathData ar;
1380         for (idx_type i = 0; i < nargs(); ++i)
1381                 ar.append(cell(i));
1382         InsetLabel * label = 0;
1383         if (type == hullEquation) {
1384                 // preserve first non-empty label
1385                 for (row_type row = 0; row < nrows(); ++row) {
1386                         if (label_[row]) {
1387                                 label = label_[row];
1388                                 label_[row] = 0;
1389                                 break;
1390                         }
1391                 }
1392         }
1393         *this = InsetMathHull(buffer_, hullSimple);
1394         label_[0] = label;
1395         cell(0) = ar;
1396         setDefaults();
1397 }
1398
1399
1400 void InsetMathHull::splitTo2Cols()
1401 {
1402         LASSERT(ncols() == 1, return);
1403         InsetMathGrid::addCol(1);
1404         for (row_type row = 0; row < nrows(); ++row) {
1405                 idx_type const i = 2 * row;
1406                 pos_type pos = firstRelOp(cell(i));
1407                 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1408                 cell(i).erase(pos, cell(i).size());
1409         }
1410 }
1411
1412
1413 void InsetMathHull::splitTo3Cols()
1414 {
1415         LASSERT(ncols() < 3, return);
1416         if (ncols() < 2)
1417                 splitTo2Cols();
1418         InsetMathGrid::addCol(2);
1419         for (row_type row = 0; row < nrows(); ++row) {
1420                 idx_type const i = 3 * row + 1;
1421                 if (!cell(i).empty()) {
1422                         cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1423                         cell(i).erase(1, cell(i).size());
1424                 }
1425         }
1426 }
1427
1428
1429 void InsetMathHull::changeCols(col_type cols)
1430 {
1431         if (ncols() == cols)
1432                 return;
1433         else if (ncols() < cols) {
1434                 // split columns
1435                 if (cols < 3)
1436                         splitTo2Cols();
1437                 else {
1438                         splitTo3Cols();
1439                         while (ncols() < cols)
1440                                 InsetMathGrid::addCol(ncols());
1441                 }
1442                 return;
1443         }
1444
1445         // combine columns
1446         for (row_type row = 0; row < nrows(); ++row) {
1447                 idx_type const i = row * ncols();
1448                 for (col_type col = cols; col < ncols(); ++col) {
1449                         cell(i + cols - 1).append(cell(i + col));
1450                 }
1451         }
1452         // delete columns
1453         while (ncols() > cols) {
1454                 InsetMathGrid::delCol(ncols() - 1);
1455         }
1456 }
1457
1458
1459 HullType InsetMathHull::getType() const
1460 {
1461         return type_;
1462 }
1463
1464
1465 void InsetMathHull::setType(HullType type)
1466 {
1467         type_ = type;
1468         setDefaults();
1469 }
1470
1471
1472 bool InsetMathHull::isMutable(HullType type)
1473 {
1474         switch (type) {
1475         case hullNone:
1476         case hullSimple:
1477         case hullEquation:
1478         case hullEqnArray:
1479         case hullAlign:
1480         case hullFlAlign:
1481         case hullAlignAt:
1482         case hullXAlignAt:
1483         case hullXXAlignAt:
1484         case hullMultline:
1485         case hullGather:
1486                 return true;
1487         case hullUnknown:
1488         case hullRegexp:
1489                 return false;
1490         }
1491         // avoid warning
1492         return false;
1493 }
1494
1495
1496 void InsetMathHull::mutate(HullType newtype)
1497 {
1498         //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1499
1500         if (newtype == type_)
1501                 return;
1502
1503         // This guards the algorithm below it, which is designed with certain types
1504         // in mind.
1505         if (!isMutable(newtype) || !isMutable(type_)) {
1506                 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1507                        << "' to '" << to_utf8(hullName(newtype))
1508                        << "' not implemented" << endl;
1509                 return;
1510         }
1511
1512         // we try to move along the chain
1513         // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1514         //                                     ^                                     |
1515         //                                     +-------------------------------------+
1516         // we use eqnarray as intermediate type for mutations that are not
1517         // directly supported because it handles labels and numbering for
1518         // "down mutation".
1519
1520         switch (type_) {
1521         case hullNone:
1522                 setType(hullSimple);
1523                 numbered(0, false);
1524                 mutate(newtype);
1525                 break;
1526
1527         case hullSimple:
1528                 if (newtype == hullNone) {
1529                         setType(hullNone);
1530                         numbered(0, false);
1531                 } else {
1532                         setType(hullEquation);
1533                         numbered(0, label_[0] ? true : false);
1534                         mutate(newtype);
1535                 }
1536                 break;
1537
1538         case hullEquation:
1539                 switch (newtype) {
1540                 case hullNone:
1541                 case hullSimple:
1542                         setType(hullSimple);
1543                         numbered(0, false);
1544                         mutate(newtype);
1545                         break;
1546                 case hullEqnArray:
1547                         // split it "nicely" on the first relop
1548                         splitTo3Cols();
1549                         setType(hullEqnArray);
1550                         break;
1551                 case hullMultline:
1552                 case hullGather:
1553                         setType(newtype);
1554                         break;
1555                 default:
1556                         // *align*
1557                         // split it "nicely"
1558                         splitTo2Cols();
1559                         setType(hullAlign);
1560                         mutate(newtype);
1561                         break;
1562                 }
1563                 break;
1564
1565         case hullEqnArray:
1566                 switch (newtype) {
1567                 case hullNone:
1568                 case hullSimple:
1569                 case hullEquation:
1570                         glueall(newtype);
1571                         mutate(newtype);
1572                         break;
1573                 default:
1574                         // align & Co.
1575                         changeCols(2);
1576                         setType(hullAlign);
1577                         mutate(newtype);
1578                         break;
1579                 }
1580                 break;
1581
1582         case hullAlign:
1583         case hullAlignAt:
1584         case hullXAlignAt:
1585         case hullFlAlign:
1586                 switch (newtype) {
1587                 case hullNone:
1588                 case hullSimple:
1589                 case hullEquation:
1590                 case hullEqnArray:
1591                         changeCols(3);
1592                         setType(hullEqnArray);
1593                         mutate(newtype);
1594                         break;
1595                 case hullGather:
1596                 case hullMultline:
1597                         changeCols(1);
1598                         setType(newtype);
1599                         break;
1600                 case hullXXAlignAt:
1601                         for (row_type row = 0; row < nrows(); ++row)
1602                                 numbered(row, false);
1603                         setType(newtype);
1604                         break;
1605                 default:
1606                         setType(newtype);
1607                         break;
1608                 }
1609                 break;
1610
1611         case hullXXAlignAt:
1612                 for (row_type row = 0; row < nrows(); ++row)
1613                         numbered(row, false);
1614                 switch (newtype) {
1615                 case hullNone:
1616                 case hullSimple:
1617                 case hullEquation:
1618                 case hullEqnArray:
1619                         changeCols(3);
1620                         setType(hullEqnArray);
1621                         mutate(newtype);
1622                         break;
1623                 case hullGather:
1624                 case hullMultline:
1625                         changeCols(1);
1626                         setType(newtype);
1627                         break;
1628                 default:
1629                         setType(newtype);
1630                         break;
1631                 }
1632                 break;
1633
1634         case hullMultline:
1635         case hullGather:
1636                 switch (newtype) {
1637                 case hullGather:
1638                 case hullMultline:
1639                         setType(newtype);
1640                         break;
1641                 case hullAlign:
1642                 case hullFlAlign:
1643                 case hullAlignAt:
1644                 case hullXAlignAt:
1645                         splitTo2Cols();
1646                         setType(newtype);
1647                         break;
1648                 case hullXXAlignAt:
1649                         splitTo2Cols();
1650                         for (row_type row = 0; row < nrows(); ++row)
1651                                 numbered(row, false);
1652                         setType(newtype);
1653                         break;
1654                 default:
1655                         // first we mutate to EqnArray
1656                         splitTo3Cols();
1657                         setType(hullEqnArray);
1658                         mutate(newtype);
1659                         break;
1660                 }
1661                 break;
1662
1663         default:
1664                 // we passed the guard so we should not be here
1665                 LASSERT("Mutation not implemented, but should have been.", return);
1666                 break;
1667         }// switch
1668 }
1669
1670
1671 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1672                 bool last_eoln) const
1673 {
1674         docstring res;
1675         if (numberedType()) {
1676                 if (label_[row] && numbered(row)) {
1677                         docstring const name =
1678                                 latex ? escape(label_[row]->getParam("name"))
1679                                       : label_[row]->getParam("name");
1680                         res += "\\label{" + name + '}';
1681                 }
1682                 if (type_ != hullMultline) {
1683                         if (numbered_[row]  == NONUMBER)
1684                                 res += "\\nonumber ";
1685                         else if (numbered_[row]  == NOTAG)
1686                                 res += "\\notag ";
1687                 }
1688         }
1689         // Never add \\ on the last empty line of eqnarray and friends
1690         last_eoln = false;
1691         return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1692 }
1693
1694 void InsetMathHull::write(WriteStream & os) const
1695 {
1696         ModeSpecifier specifier(os, MATH_MODE);
1697         header_write(os);
1698         InsetMathGrid::write(os);
1699         footer_write(os);
1700 }
1701
1702
1703 void InsetMathHull::normalize(NormalStream & os) const
1704 {
1705         os << "[formula " << hullName(type_) << ' ';
1706         InsetMathGrid::normalize(os);
1707         os << "] ";
1708 }
1709
1710
1711 void InsetMathHull::infoize(odocstream & os) const
1712 {
1713         os << bformat(_("Type: %1$s"), hullName(type_));
1714 }
1715
1716
1717 void InsetMathHull::check() const
1718 {
1719         LATTEST(numbered_.size() == nrows());
1720         LATTEST(numbers_.size() == nrows());
1721         LATTEST(label_.size() == nrows());
1722 }
1723
1724
1725 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1726 {
1727         docstring dlang;
1728         docstring extra;
1729         idocstringstream iss(func.argument());
1730         iss >> dlang >> extra;
1731         if (extra.empty())
1732                 extra = from_ascii("noextra");
1733         string const lang = to_ascii(dlang);
1734
1735         // replace selection with result of computation
1736         if (reduceSelectionToOneCell(cur)) {
1737                 MathData ar;
1738                 asArray(grabAndEraseSelection(cur), ar);
1739                 lyxerr << "use selection: " << ar << endl;
1740                 cur.insert(pipeThroughExtern(lang, extra, ar));
1741                 return;
1742         }
1743
1744         // only inline, display or eqnarray math is allowed
1745         switch (getType()) {
1746         case hullSimple:
1747         case hullEquation:
1748         case hullEqnArray:
1749                 break;
1750         default:
1751                 frontend::Alert::warning(_("Bad math environment"),
1752                                 _("Computation cannot be performed for AMS "
1753                                   "math environments.\nChange the math "
1754                                   "formula type and try again."));
1755                 return;
1756         }
1757
1758         MathData eq;
1759         eq.push_back(MathAtom(new InsetMathChar('=')));
1760
1761         // go to first item in line
1762         cur.idx() -= cur.idx() % ncols();
1763         cur.pos() = 0;
1764
1765         if (getType() == hullSimple) {
1766                 size_type pos = cur.cell().find_last(eq);
1767                 MathData ar;
1768                 if (pos == cur.cell().size()) {
1769                         ar = cur.cell();
1770                         lyxerr << "use whole cell: " << ar << endl;
1771                 } else {
1772                         ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1773                         lyxerr << "use partial cell form pos: " << pos << endl;
1774                 }
1775                 cur.cell().append(eq);
1776                 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1777                 cur.pos() = cur.lastpos();
1778                 return;
1779         }
1780
1781         if (getType() == hullEquation) {
1782                 lyxerr << "use equation inset" << endl;
1783                 mutate(hullEqnArray);
1784                 MathData & ar = cur.cell();
1785                 lyxerr << "use cell: " << ar << endl;
1786                 ++cur.idx();
1787                 cur.cell() = eq;
1788                 ++cur.idx();
1789                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1790                 // move to end of line
1791                 cur.pos() = cur.lastpos();
1792                 return;
1793         }
1794
1795         {
1796                 lyxerr << "use eqnarray" << endl;
1797                 cur.idx() += 2 - cur.idx() % ncols();
1798                 cur.pos() = 0;
1799                 MathData ar = cur.cell();
1800                 lyxerr << "use cell: " << ar << endl;
1801                 // FIXME: temporarily disabled
1802                 addRow(cur.row());
1803                 ++cur.idx();
1804                 ++cur.idx();
1805                 cur.cell() = eq;
1806                 ++cur.idx();
1807                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1808                 cur.pos() = cur.lastpos();
1809         }
1810 }
1811
1812
1813 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1814 {
1815         //lyxerr << "action: " << cmd.action() << endl;
1816         switch (cmd.action()) {
1817
1818         case LFUN_FINISHED_BACKWARD:
1819         case LFUN_FINISHED_FORWARD:
1820         case LFUN_FINISHED_RIGHT:
1821         case LFUN_FINISHED_LEFT:
1822                 //lyxerr << "action: " << cmd.action() << endl;
1823                 InsetMathGrid::doDispatch(cur, cmd);
1824                 break;
1825
1826         case LFUN_PARAGRAPH_BREAK:
1827                 // just swallow this
1828                 break;
1829
1830         case LFUN_NEWLINE_INSERT:
1831                 // some magic for the common case
1832                 if (type_ == hullSimple || type_ == hullEquation) {
1833                         cur.recordUndoInset();
1834                         bool const align =
1835                                 cur.bv().buffer().params().use_package("amsmath") != BufferParams::package_off;
1836                         mutate(align ? hullAlign : hullEqnArray);
1837                         // mutate() may change labels and such.
1838                         cur.forceBufferUpdate();
1839                         cur.idx() = nrows() * ncols() - 1;
1840                         cur.pos() = cur.lastpos();
1841                 }
1842                 InsetMathGrid::doDispatch(cur, cmd);
1843                 break;
1844
1845         case LFUN_MATH_NUMBER_TOGGLE: {
1846                 //lyxerr << "toggling all numbers" << endl;
1847                 cur.recordUndoInset();
1848                 bool old = numberedType();
1849                 if (type_ == hullMultline)
1850                         numbered(nrows() - 1, !old);
1851                 else
1852                         for (row_type row = 0; row < nrows(); ++row)
1853                                 numbered(row, !old);
1854
1855                 cur.message(old ? _("No number") : _("Number"));
1856                 cur.forceBufferUpdate();
1857                 break;
1858         }
1859
1860         case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1861                 cur.recordUndoInset();
1862                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1863                 bool old = numbered(r);
1864                 cur.message(old ? _("No number") : _("Number"));
1865                 numbered(r, !old);
1866                 cur.forceBufferUpdate();
1867                 break;
1868         }
1869
1870         case LFUN_LABEL_INSERT: {
1871                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1872                 docstring old_label = label(r);
1873                 docstring const default_label = from_ascii("eq:");
1874                 if (old_label.empty())
1875                         old_label = default_label;
1876
1877                 InsetCommandParams p(LABEL_CODE);
1878                 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1879                 string const data = InsetCommand::params2string(p);
1880
1881                 if (cmd.argument().empty())
1882                         cur.bv().showDialog("label", data);
1883                 else {
1884                         FuncRequest fr(LFUN_INSET_INSERT, data);
1885                         dispatch(cur, fr);
1886                 }
1887                 break;
1888         }
1889
1890         case LFUN_LABEL_COPY_AS_REFERENCE: {
1891                 row_type row;
1892                 if (cmd.argument().empty() && &cur.inset() == this)
1893                         // if there is no argument and we're inside math, we retrieve
1894                         // the row number from the cursor position.
1895                         row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1896                 else {
1897                         // if there is an argument, find the corresponding label, else
1898                         // check whether there is at least one label.
1899                         for (row = 0; row != nrows(); ++row)
1900                                 if (numbered(row) && label_[row]
1901                                           && (cmd.argument().empty() || label(row) == cmd.argument()))
1902                                         break;
1903                 }
1904
1905                 if (row == nrows())
1906                         break;
1907
1908                 InsetCommandParams p(REF_CODE, "ref");
1909                 p["reference"] = label(row);
1910                 cap::clearSelection();
1911                 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1912                 break;
1913         }
1914
1915         case LFUN_WORD_DELETE_FORWARD:
1916         case LFUN_CHAR_DELETE_FORWARD:
1917                 if (col(cur.idx()) + 1 == ncols()
1918                     && cur.pos() == cur.lastpos()
1919                     && !cur.selection()) {
1920                         if (!label(row(cur.idx())).empty()) {
1921                                 cur.recordUndoInset();
1922                                 label(row(cur.idx()), docstring());
1923                         } else if (numbered(row(cur.idx()))) {
1924                                 cur.recordUndoInset();
1925                                 numbered(row(cur.idx()), false);
1926                                 cur.forceBufferUpdate();
1927                         } else {
1928                                 InsetMathGrid::doDispatch(cur, cmd);
1929                                 return;
1930                         }
1931                 } else {
1932                         InsetMathGrid::doDispatch(cur, cmd);
1933                         return;
1934                 }
1935                 break;
1936
1937         case LFUN_INSET_INSERT: {
1938                 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1939                 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1940                 string const name = cmd.getArg(0);
1941                 if (name == "label") {
1942                         InsetCommandParams p(LABEL_CODE);
1943                         InsetCommand::string2params(to_utf8(cmd.argument()), p);
1944                         docstring str = p["name"];
1945                         cur.recordUndoInset();
1946                         row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1947                         str = trim(str);
1948                         if (!str.empty())
1949                                 numbered(r, true);
1950                         docstring old = label(r);
1951                         if (str != old) {
1952                                 if (label_[r])
1953                                         // The label will take care of the reference update.
1954                                         label(r, str);
1955                                 else {
1956                                         label(r, str);
1957                                         // Newly created inset so initialize it.
1958                                         label_[r]->initView();
1959                                 }
1960                         }
1961                         cur.forceBufferUpdate();
1962                         break;
1963                 }
1964                 InsetMathGrid::doDispatch(cur, cmd);
1965                 return;
1966         }
1967
1968         case LFUN_MATH_EXTERN:
1969                 cur.recordUndoInset();
1970                 doExtern(cur, cmd);
1971                 break;
1972
1973         case LFUN_MATH_MUTATE: {
1974                 cur.recordUndoInset();
1975                 row_type row = cur.row();
1976                 col_type col = cur.col();
1977                 mutate(hullType(cmd.argument()));
1978                 cur.idx() = row * ncols() + col;
1979                 if (cur.idx() > cur.lastidx()) {
1980                         cur.idx() = cur.lastidx();
1981                         cur.pos() = cur.lastpos();
1982                 }
1983                 if (cur.pos() > cur.lastpos())
1984                         cur.pos() = cur.lastpos();
1985
1986                 cur.forceBufferUpdate();
1987                 // FIXME: find some more clever handling of the selection,
1988                 // i.e. preserve it.
1989                 cur.clearSelection();
1990                 //cur.dispatched(FINISHED);
1991                 break;
1992         }
1993
1994         case LFUN_MATH_DISPLAY: {
1995                 cur.recordUndoInset();
1996                 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1997                 // if the cursor is in a cell that got merged, move it to
1998                 // start of the hull inset.
1999                 if (cur.idx() > 0) {
2000                         cur.idx() = 0;
2001                         cur.pos() = 0;
2002                 }
2003                 if (cur.pos() > cur.lastpos())
2004                         cur.pos() = cur.lastpos();
2005
2006                 break;
2007         }
2008
2009         case LFUN_TABULAR_FEATURE:
2010                 if (!allowsTabularFeatures())
2011                         cur.undispatched();
2012                 else
2013                         InsetMathGrid::doDispatch(cur, cmd);
2014                 break;
2015
2016         default:
2017                 InsetMathGrid::doDispatch(cur, cmd);
2018                 break;
2019         }
2020 }
2021
2022
2023 namespace {
2024
2025 bool allowDisplayMath(Cursor const & cur)
2026 {
2027         LATTEST(cur.depth() > 1);
2028         Cursor tmpcur = cur;
2029         tmpcur.pop();
2030         FuncStatus status;
2031         FuncRequest cmd(LFUN_MATH_DISPLAY);
2032         return tmpcur.getStatus(cmd, status) && status.enabled();
2033 }
2034
2035 } // namespace
2036
2037
2038 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
2039                 FuncStatus & status) const
2040 {
2041         switch (cmd.action()) {
2042         case LFUN_FINISHED_BACKWARD:
2043         case LFUN_FINISHED_FORWARD:
2044         case LFUN_FINISHED_RIGHT:
2045         case LFUN_FINISHED_LEFT:
2046         case LFUN_UP:
2047         case LFUN_DOWN:
2048         case LFUN_NEWLINE_INSERT:
2049         case LFUN_MATH_EXTERN:
2050                 // we handle these
2051                 status.setEnabled(true);
2052                 return true;
2053
2054         // we never allow this in math, and we want to bind enter
2055         // to another actions in command-alternatives
2056         case LFUN_PARAGRAPH_BREAK:
2057                 status.setEnabled(false);
2058                 return true;
2059         case LFUN_MATH_MUTATE: {
2060                 HullType const ht = hullType(cmd.argument());
2061                 status.setOnOff(type_ == ht);
2062                 status.setEnabled(isMutable(ht) && isMutable(type_));
2063
2064                 if (ht != hullSimple && status.enabled())
2065                         status.setEnabled(allowDisplayMath(cur));
2066                 return true;
2067         }
2068         case LFUN_MATH_DISPLAY: {
2069                 status.setEnabled(display() != Inline || allowDisplayMath(cur));
2070                 status.setOnOff(display() != Inline);
2071                 return true;
2072         }
2073
2074         case LFUN_MATH_NUMBER_TOGGLE:
2075                 // FIXME: what is the right test, this or the one of
2076                 // LABEL_INSERT?
2077                 status.setEnabled(display() != Inline);
2078                 status.setOnOff(numberedType());
2079                 return true;
2080
2081         case LFUN_MATH_NUMBER_LINE_TOGGLE: {
2082                 // FIXME: what is the right test, this or the one of
2083                 // LABEL_INSERT?
2084                 bool const enable = (type_ == hullMultline)
2085                         ? (nrows() - 1 == cur.row())
2086                         : display() != Inline;
2087                 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2088                 status.setEnabled(enable);
2089                 status.setOnOff(enable && numbered(r));
2090                 return true;
2091         }
2092
2093         case LFUN_LABEL_INSERT:
2094                 status.setEnabled(type_ != hullSimple);
2095                 return true;
2096
2097         case LFUN_LABEL_COPY_AS_REFERENCE: {
2098                 bool enabled = false;
2099                 row_type row;
2100                 if (cmd.argument().empty() && &cur.inset() == this) {
2101                         // if there is no argument and we're inside math, we retrieve
2102                         // the row number from the cursor position.
2103                         row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
2104                         enabled = numberedType() && label_[row] && numbered(row);
2105                 } else {
2106                         // if there is an argument, find the corresponding label, else
2107                         // check whether there is at least one label.
2108                         for (row_type row = 0; row != nrows(); ++row) {
2109                                 if (numbered(row) && label_[row] &&
2110                                         (cmd.argument().empty() || label(row) == cmd.argument())) {
2111                                                 enabled = true;
2112                                                 break;
2113                                 }
2114                         }
2115                 }
2116                 status.setEnabled(enabled);
2117                 return true;
2118         }
2119
2120         case LFUN_INSET_INSERT:
2121                 if (cmd.getArg(0) == "label") {
2122                         status.setEnabled(type_ != hullSimple);
2123                         return true;
2124                 }
2125                 return InsetMathGrid::getStatus(cur, cmd, status);
2126
2127         case LFUN_TABULAR_FEATURE: {
2128                 if (!allowsTabularFeatures())
2129                         return false;
2130                 string s = cmd.getArg(0);
2131                 if (!rowChangeOK()
2132                     && (s == "append-row"
2133                         || s == "delete-row"
2134                         || s == "copy-row")) {
2135                         status.message(bformat(
2136                                 from_utf8(N_("Can't change number of rows in '%1$s'")),
2137                                 hullName(type_)));
2138                         status.setEnabled(false);
2139                         return true;
2140                 }
2141                 if (!colChangeOK()
2142                     && (s == "append-column"
2143                         || s == "delete-column"
2144                         || s == "copy-column")) {
2145                         status.message(bformat(
2146                                 from_utf8(N_("Can't change number of columns in '%1$s'")),
2147                                 hullName(type_)));
2148                         status.setEnabled(false);
2149                         return true;
2150                 }
2151                 if (s == "add-vline-left" || s == "add-vline-right") {
2152                         status.message(bformat(
2153                                 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
2154                                 hullName(type_)));
2155                         status.setEnabled(false);
2156                         return true;
2157                 }
2158                 if (s == "valign-top" || s == "valign-middle"
2159                  || s == "valign-bottom" || s == "align-left"
2160                  || s == "align-center" || s == "align-right") {
2161                         status.setEnabled(false);
2162                         return true;
2163                 }
2164                 return InsetMathGrid::getStatus(cur, cmd, status);
2165         }
2166
2167         default:
2168                 return InsetMathGrid::getStatus(cur, cmd, status);
2169         }
2170 }
2171
2172
2173 int InsetMathHull::leftMargin() const
2174 {
2175         return (getType() == hullSimple) ? 0 : InsetMathGrid::leftMargin();
2176 }
2177
2178
2179 int InsetMathHull::rightMargin() const
2180 {
2181         return (getType() == hullSimple) ? 0 : InsetMathGrid::rightMargin();
2182 }
2183
2184
2185 int InsetMathHull::border() const
2186 {
2187         return (getType() == hullSimple) ? 0 : InsetMathGrid::border();
2188 }
2189
2190
2191 /////////////////////////////////////////////////////////////////////
2192
2193
2194
2195 // simply scrap this function if you want
2196 void InsetMathHull::mutateToText()
2197 {
2198 #if 0
2199         // translate to latex
2200         ostringstream os;
2201         latex(os, false, false);
2202         string str = os.str();
2203
2204         // insert this text
2205         Text * lt = view_->cursor().innerText();
2206         string::const_iterator cit = str.begin();
2207         string::const_iterator end = str.end();
2208         for (; cit != end; ++cit)
2209                 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
2210
2211         // remove ourselves
2212         //dispatch(LFUN_ESCAPE);
2213 #endif
2214 }
2215
2216
2217 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
2218         docstring const & font)
2219 {
2220         // this whole function is a hack and won't work for incremental font
2221         // changes...
2222         cur.recordUndo();
2223         if (cur.inset().asInsetMath()->name() == font)
2224                 cur.handleFont(to_utf8(font));
2225         else {
2226                 cur.handleNest(createInsetMath(font, cur.buffer()));
2227                 cur.insert(arg);
2228         }
2229 }
2230
2231
2232 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
2233 {
2234         cur.recordUndo();
2235         Font font;
2236         bool b;
2237         font.fromString(to_utf8(arg), b);
2238         if (font.fontInfo().color() != Color_inherit) {
2239                 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
2240                 cur.handleNest(at, 0);
2241         }
2242 }
2243
2244
2245 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
2246 {
2247         cur.push(*this);
2248         bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
2249                 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
2250         enter_front ? idxFirst(cur) : idxLast(cur);
2251         // The inset formula dimension is not necessarily the same as the
2252         // one of the instant preview image, so we have to indicate to the
2253         // BufferView that a metrics update is needed.
2254         cur.screenUpdateFlags(Update::Force);
2255 }
2256
2257
2258 void InsetMathHull::revealCodes(Cursor & cur) const
2259 {
2260         if (!cur.inMathed())
2261                 return;
2262         odocstringstream os;
2263         cur.info(os, false);
2264         cur.message(os.str());
2265 /*
2266         // write something to the minibuffer
2267         // translate to latex
2268         cur.markInsert(bv);
2269         ostringstream os;
2270         write(os);
2271         string str = os.str();
2272         cur.markErase(bv);
2273         string::size_type pos = 0;
2274         string res;
2275         for (string::iterator it = str.begin(); it != str.end(); ++it) {
2276                 if (*it == '\n')
2277                         res += ' ';
2278                 else if (*it == '\0') {
2279                         res += "  -X-  ";
2280                         pos = it - str.begin();
2281                 }
2282                 else
2283                         res += *it;
2284         }
2285         if (pos > 30)
2286                 res = res.substr(pos - 30);
2287         if (res.size() > 60)
2288                 res = res.substr(0, 60);
2289         cur.message(res);
2290 */
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         // disables ASCII-art for export of equations. See #2275.
2371         if (0 && 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