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