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