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