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