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