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