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