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