]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathHull.cpp
560c9991c88a39c1a3fbfc8b2c7e59901a231433
[lyx.git] / src / mathed / InsetMathHull.cpp
1 /**
2  * \file InsetMathHull.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetMathHull.h"
14
15 #include "InsetMathChar.h"
16 #include "InsetMathColor.h"
17 #include "InsetMathFrac.h"
18 #include "InsetMathGrid.h"
19 #include "InsetMathNest.h"
20 #include "InsetMathScript.h"
21 #include "MathExtern.h"
22 #include "MathFactory.h"
23 #include "MathStream.h"
24 #include "MathSupport.h"
25
26 #include "Buffer.h"
27 #include "BufferParams.h"
28 #include "BufferView.h"
29 #include "ColorSet.h"
30 #include "CutAndPaste.h"
31 #include "Encoding.h"
32 #include "Exporter.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "Language.h"
36 #include "LaTeXFeatures.h"
37 #include "LyXRC.h"
38 #include "MacroTable.h"
39 #include "MathMacro.h"
40 #include "MathMacroTemplate.h"
41 #include "output_xhtml.h"
42 #include "Paragraph.h"
43 #include "ParIterator.h"
44 #include "sgml.h"
45 #include "TextClass.h"
46 #include "TextPainter.h"
47 #include "TocBackend.h"
48
49 #include "insets/InsetLabel.h"
50 #include "insets/InsetRef.h"
51 #include "insets/RenderPreview.h"
52
53 #include "graphics/GraphicsImage.h"
54 #include "graphics/PreviewImage.h"
55 #include "graphics/PreviewLoader.h"
56
57 #include "frontends/alert.h"
58 #include "frontends/Painter.h"
59
60 #include "support/convert.h"
61 #include "support/lassert.h"
62 #include "support/debug.h"
63 #include "support/filetools.h"
64 #include "support/gettext.h"
65 #include "support/lstrings.h"
66
67 #include <sstream>
68
69 using namespace std;
70 using namespace lyx::support;
71
72 namespace lyx {
73
74 using cap::grabAndEraseSelection;
75 using cap::reduceSelectionToOneCell;
76
77 namespace {
78
79         int getCols(HullType type)
80         {
81                 switch (type) {
82                         case hullEqnArray:
83                                 return 3;
84                         case hullAlign:
85                         case hullFlAlign:
86                         case hullAlignAt:
87                         case hullXAlignAt:
88                         case hullXXAlignAt:
89                                 return 2;
90                         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         // set the font series and size for this snippet
717         DocIterator dit = pos;
718         while (dit.inMathed())
719                 dit.pop_back();
720         Paragraph const & par = dit.paragraph();
721         Font font = par.getFontSettings(buffer->params(), dit.pos());
722         font.fontInfo().realize(par.layout().font);
723         string const lsize = font.latexSize();
724         docstring setfont;
725         docstring endfont;
726         if (font.fontInfo().series() == BOLD_SERIES) {
727                 setfont += from_ascii("\\textbf{");
728                 endfont += '}';
729         }
730         if (lsize != "normalsize" && !prefixIs(lsize, "error"))
731                 setfont += from_ascii("\\" + lsize + '\n'); 
732
733         docstring setcnt;
734         if (forexport && haveNumbers()) {
735                 docstring eqstr = from_ascii("equation");
736                 CounterMap::const_iterator it = counter_map.find(eqstr);
737                 if (it != counter_map.end()) {
738                         int num = it->second;
739                         if (num >= 0)
740                                 setcnt += from_ascii("\\setcounter{") + eqstr + '}' +
741                                           '{' + convert<docstring>(num) + '}' + '\n';
742                 }
743                 for (size_t i = 0; i != numcnts; ++i) {
744                         docstring cnt = from_ascii(counters_to_save[i]);
745                         it = counter_map.find(cnt);
746                         if (it == counter_map.end())
747                                         continue;
748                         int num = it->second;
749                         if (num > 0)
750                                 setcnt += from_ascii("\\setcounter{") + cnt + '}' +
751                                           '{' + convert<docstring>(num) + '}';
752                 }
753         }
754         docstring const snippet = macro_preamble + setfont + setcnt
755                                   + latexString(*this) + endfont;
756         LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
757         preview_->addPreview(snippet, *buffer, forexport);
758 }
759
760
761 void InsetMathHull::reloadPreview(DocIterator const & pos) const
762 {
763         preparePreview(pos);
764         preview_->startLoading(*pos.buffer());
765 }
766
767
768 void InsetMathHull::loadPreview(DocIterator const & pos) const
769 {
770         bool const forexport = true;
771         preparePreview(pos, forexport);
772         preview_->startLoading(*pos.buffer(), forexport);
773 }
774
775
776 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
777 {
778         if (RenderPreview::previewMath()) {
779                 reloadPreview(old);
780                 cur.screenUpdateFlags(Update::Force);
781         }
782         return false;
783 }
784
785
786 docstring InsetMathHull::label(row_type row) const
787 {
788         LASSERT(row < nrows(), return docstring());
789         if (InsetLabel * il = label_[row])
790                 return il->screenLabel();
791         return docstring();
792 }
793
794
795 void InsetMathHull::label(row_type row, docstring const & label)
796 {
797         //lyxerr << "setting label '" << label << "' for row " << row << endl;
798         if (label_[row]) {
799                 if (label.empty()) {
800                         delete label_[row];
801                         label_[row] = dummy_pointer;
802                 } else {
803                         if (buffer_)
804                                 label_[row]->updateLabelAndRefs(label);
805                         else
806                                 label_[row]->setParam("name", label);
807                 }
808                 return;
809         }
810         InsetCommandParams p(LABEL_CODE);
811         p["name"] = label;
812         label_[row] = new InsetLabel(buffer_, p);
813         if (buffer_)
814                 label_[row]->setBuffer(buffer());
815 }
816
817
818 void InsetMathHull::numbered(row_type row, Numbered num)
819 {
820         numbered_[row] = num;
821         if (!numbered(row) && label_[row]) {
822                 delete label_[row];
823                 label_[row] = 0;
824         }
825 }
826
827
828 bool InsetMathHull::numbered(row_type row) const
829 {
830         return numbered_[row] == NUMBER;
831 }
832
833
834 bool InsetMathHull::ams() const
835 {
836         switch (type_) {
837                 case hullAlign:
838                 case hullFlAlign:
839                 case hullMultline:
840                 case hullGather:
841                 case hullAlignAt:
842                 case hullXAlignAt:
843                 case hullXXAlignAt:
844                         return true;
845                 case hullNone:
846                 case hullSimple:
847                 case hullEquation:
848                 case hullEqnArray:
849                 case hullRegexp:
850                         break;
851         }
852         for (size_t row = 0; row < numbered_.size(); ++row)
853                 if (numbered_[row] == NOTAG)
854                         return true;
855         return false;
856 }
857
858
859 Inset::DisplayType InsetMathHull::display() const
860 {
861         if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
862                 return Inline;
863         return AlignCenter;
864 }
865
866 bool InsetMathHull::numberedType() const
867 {
868         if (type_ == hullNone)
869                 return false;
870         if (type_ == hullSimple)
871                 return false;
872         if (type_ == hullXXAlignAt)
873                 return false;
874         if (type_ == hullRegexp)
875                 return false;
876         for (row_type row = 0; row < nrows(); ++row)
877                 if (numbered(row))
878                         return true;
879         return false;
880 }
881
882
883 void InsetMathHull::validate(LaTeXFeatures & features) const
884 {
885         if (features.runparams().isLaTeX()) {
886                 if (ams())
887                         features.require("amsmath");
888
889                 if (type_ == hullRegexp) {
890                         features.require("color");
891                         string frcol = lcolor.getLaTeXName(Color_regexpframe);
892                         string bgcol = "white";
893                         features.addPreambleSnippet(
894                                 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
895                                 + frcol + string("}{")
896                                 + bgcol + string("}{\\ensuremath{\\mathtt{#1}}}}"));
897                         features.addPreambleSnippet(
898                                 string("\\newcommand{\\endregexp}{}"));
899                 }
900
901                 // Validation is necessary only if not using AMS math.
902                 // To be safe, we will always run mathedvalidate.
903                 //if (features.amsstyle)
904                 //  return;
905
906                 //features.binom      = true;
907         } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
908                 // it would be better to do this elsewhere, but we can't validate in
909                 // InsetMathMatrix and we have no way, outside MathExtern, to know if
910                 // we even have any matrices.
911                                 features.addCSSSnippet(
912                                         "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
913                                         "table.matrix td{padding: 0.25px;}\n"
914                                         "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
915                                         "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}");
916         }
917         InsetMathGrid::validate(features);
918 }
919
920
921 void InsetMathHull::header_write(WriteStream & os) const
922 {
923         bool n = numberedType();
924
925         switch(type_) {
926         case hullNone:
927                 break;
928
929         case hullSimple:
930                 os << '$';
931                 if (cell(0).empty())
932                         os << ' ';
933                 break;
934
935         case hullEquation:
936                 if (n)
937                         os << "\n\\begin{equation" << star(n) << "}\n";
938                 else
939                         os << "\n\\[\n";
940                 break;
941
942         case hullEqnArray:
943         case hullAlign:
944         case hullFlAlign:
945         case hullGather:
946         case hullMultline:
947                 os << "\n\\begin{" << hullName(type_) << star(n) << "}\n";
948                 break;
949
950         case hullAlignAt:
951         case hullXAlignAt:
952                 os << "\n\\begin{" << hullName(type_) << star(n) << '}'
953                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
954                 break;
955
956         case hullXXAlignAt:
957                 os << "\n\\begin{" << hullName(type_) << '}'
958                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
959                 break;
960
961         case hullRegexp:
962                 os << "\\regexp{";
963                 break;
964
965         default:
966                 os << "\n\\begin{unknown" << star(n) << "}\n";
967                 break;
968         }
969 }
970
971
972 void InsetMathHull::footer_write(WriteStream & os) const
973 {
974         bool n = numberedType();
975
976         switch(type_) {
977         case hullNone:
978                 os << "\n";
979                 break;
980
981         case hullSimple:
982                 os << '$';
983                 break;
984
985         case hullEquation:
986                 if (n)
987                         os << "\n\\end{equation" << star(n) << "}\n";
988                 else
989                         os << "\n\\]\n";
990                 break;
991
992         case hullEqnArray:
993         case hullAlign:
994         case hullFlAlign:
995         case hullAlignAt:
996         case hullXAlignAt:
997         case hullGather:
998         case hullMultline:
999                 os << "\n\\end{" << hullName(type_) << star(n) << "}\n";
1000                 break;
1001
1002         case hullXXAlignAt:
1003                 os << "\n\\end{" << hullName(type_) << "}\n";
1004                 break;
1005
1006         case hullRegexp:
1007                 // Only used as a heuristic to find the regexp termination, when searching in ignore-format mode
1008                 os << "\\endregexp{}}";
1009                 break;
1010
1011         default:
1012                 os << "\n\\end{unknown" << star(n) << "}\n";
1013                 break;
1014         }
1015 }
1016
1017
1018 bool InsetMathHull::rowChangeOK() const
1019 {
1020         return
1021                 type_ == hullEqnArray || type_ == hullAlign ||
1022                 type_ == hullFlAlign || type_ == hullAlignAt ||
1023                 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1024                 type_ == hullGather || type_ == hullMultline;
1025 }
1026
1027
1028 bool InsetMathHull::colChangeOK() const
1029 {
1030         return
1031                 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1032                 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1033 }
1034
1035
1036 void InsetMathHull::addRow(row_type row)
1037 {
1038         if (!rowChangeOK())
1039                 return;
1040
1041         bool numbered = numberedType();
1042         // Move the number and raw pointer, do not call label() (bug 7511)
1043         InsetLabel * label = dummy_pointer;
1044         docstring number = empty_docstring();
1045         if (type_ == hullMultline) {
1046                 if (row + 1 == nrows())  {
1047                         numbered_[row] = NONUMBER;
1048                         swap(label, label_[row]);
1049                         swap(number, numbers_[row]);
1050                 } else
1051                         numbered = false;
1052         }
1053
1054         numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1055         numbers_.insert(numbers_.begin() + row + 1, number);
1056         label_.insert(label_.begin() + row + 1, label);
1057         InsetMathGrid::addRow(row);
1058 }
1059
1060
1061 void InsetMathHull::swapRow(row_type row)
1062 {
1063         if (nrows() <= 1)
1064                 return;
1065         if (row + 1 == nrows())
1066                 --row;
1067         swap(numbered_[row], numbered_[row + 1]);
1068         swap(numbers_[row], numbers_[row + 1]);
1069         swap(label_[row], label_[row + 1]);
1070         InsetMathGrid::swapRow(row);
1071 }
1072
1073
1074 void InsetMathHull::delRow(row_type row)
1075 {
1076         if (nrows() <= 1 || !rowChangeOK())
1077                 return;
1078         if (row + 1 == nrows() && type_ == hullMultline) {
1079                 swap(numbered_[row - 1], numbered_[row]);
1080                 swap(numbers_[row - 1], numbers_[row]);
1081                 swap(label_[row - 1], label_[row]);
1082                 InsetMathGrid::delRow(row);
1083                 return;
1084         }
1085         InsetMathGrid::delRow(row);
1086         // The last dummy row has no number info nor a label.
1087         // Test nrows() + 1 because we have already erased the row.
1088         if (row == nrows() + 1)
1089                 row--;
1090         numbered_.erase(numbered_.begin() + row);
1091         numbers_.erase(numbers_.begin() + row);
1092         delete label_[row];
1093         label_.erase(label_.begin() + row);
1094 }
1095
1096
1097 void InsetMathHull::addCol(col_type col)
1098 {
1099         if (!colChangeOK())
1100                 return;
1101         InsetMathGrid::addCol(col);
1102 }
1103
1104
1105 void InsetMathHull::delCol(col_type col)
1106 {
1107         if (ncols() <= 1 || !colChangeOK())
1108                 return;
1109         InsetMathGrid::delCol(col);
1110 }
1111
1112
1113 docstring InsetMathHull::nicelabel(row_type row) const
1114 {
1115         if (!numbered(row))
1116                 return docstring();
1117         docstring const & val = numbers_[row];
1118         if (!label_[row])
1119                 return '(' + val + ')';
1120         return '(' + val + ',' + label_[row]->screenLabel() + ')';
1121 }
1122
1123
1124 void InsetMathHull::glueall(HullType type)
1125 {
1126         MathData ar;
1127         for (idx_type i = 0; i < nargs(); ++i)
1128                 ar.append(cell(i));
1129         InsetLabel * label = 0;
1130         if (type == hullEquation) {
1131                 // preserve first non-empty label
1132                 for (row_type row = 0; row < nrows(); ++row) {
1133                         if (label_[row]) {
1134                                 label = label_[row];
1135                                 label_[row] = 0;
1136                                 break;
1137                         }
1138                 }
1139         }
1140         *this = InsetMathHull(buffer_, hullSimple);
1141         label_[0] = label;
1142         cell(0) = ar;
1143         setDefaults();
1144 }
1145
1146
1147 void InsetMathHull::splitTo2Cols()
1148 {
1149         LASSERT(ncols() == 1, return);
1150         InsetMathGrid::addCol(1);
1151         for (row_type row = 0; row < nrows(); ++row) {
1152                 idx_type const i = 2 * row;
1153                 pos_type pos = firstRelOp(cell(i));
1154                 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1155                 cell(i).erase(pos, cell(i).size());
1156         }
1157 }
1158
1159
1160 void InsetMathHull::splitTo3Cols()
1161 {
1162         LASSERT(ncols() < 3, return);
1163         if (ncols() < 2)
1164                 splitTo2Cols();
1165         InsetMathGrid::addCol(2);
1166         for (row_type row = 0; row < nrows(); ++row) {
1167                 idx_type const i = 3 * row + 1;
1168                 if (!cell(i).empty()) {
1169                         cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1170                         cell(i).erase(1, cell(i).size());
1171                 }
1172         }
1173 }
1174
1175
1176 void InsetMathHull::changeCols(col_type cols)
1177 {
1178         if (ncols() == cols)
1179                 return;
1180         else if (ncols() < cols) {
1181                 // split columns
1182                 if (cols < 3)
1183                         splitTo2Cols();
1184                 else {
1185                         splitTo3Cols();
1186                         while (ncols() < cols)
1187                                 InsetMathGrid::addCol(ncols());
1188                 }
1189                 return;
1190         }
1191
1192         // combine columns
1193         for (row_type row = 0; row < nrows(); ++row) {
1194                 idx_type const i = row * ncols();
1195                 for (col_type col = cols; col < ncols(); ++col) {
1196                         cell(i + cols - 1).append(cell(i + col));
1197                 }
1198         }
1199         // delete columns
1200         while (ncols() > cols) {
1201                 InsetMathGrid::delCol(ncols() - 1);
1202         }
1203 }
1204
1205
1206 HullType InsetMathHull::getType() const
1207 {
1208         return type_;
1209 }
1210
1211
1212 void InsetMathHull::setType(HullType type)
1213 {
1214         type_ = type;
1215         setDefaults();
1216 }
1217
1218
1219 void InsetMathHull::mutate(HullType newtype)
1220 {
1221         //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1222
1223         // we try to move along the chain
1224         // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1225         //                                     ^                                     |
1226         //                                     +-------------------------------------+
1227         // we use eqnarray as intermediate type for mutations that are not
1228         // directly supported because it handles labels and numbering for
1229         // "down mutation".
1230
1231         if (newtype == type_) {
1232                 // done
1233         }
1234
1235         else if (newtype < hullNone) {
1236                 // unknown type
1237                 dump();
1238         }
1239
1240         else if (type_ == hullNone) {
1241                 setType(hullSimple);
1242                 numbered(0, false);
1243                 mutate(newtype);
1244         }
1245
1246         else if (type_ == hullSimple) {
1247                 if (newtype == hullNone) {
1248                         setType(hullNone);
1249                         numbered(0, false);
1250                 } else {
1251                         setType(hullEquation);
1252                         numbered(0, label_[0] ? true : false);
1253                         mutate(newtype);
1254                 }
1255         }
1256
1257         else if (type_ == hullEquation) {
1258                 if (newtype < type_) {
1259                         setType(hullSimple);
1260                         numbered(0, false);
1261                         mutate(newtype);
1262                 } else if (newtype == hullEqnArray) {
1263                         // split it "nicely" on the first relop
1264                         splitTo3Cols();
1265                         setType(hullEqnArray);
1266                 } else if (newtype == hullMultline || newtype == hullGather) {
1267                         setType(newtype);
1268                 } else {
1269                         // split it "nicely"
1270                         splitTo2Cols();
1271                         setType(hullAlign);
1272                         mutate(newtype);
1273                 }
1274         }
1275
1276         else if (type_ == hullEqnArray) {
1277                 if (newtype < type_) {
1278                         glueall(newtype);
1279                         mutate(newtype);
1280                 } else { // align & Co.
1281                         changeCols(2);
1282                         setType(hullAlign);
1283                         mutate(newtype);
1284                 }
1285         }
1286
1287         else if (type_ ==  hullAlign || type_ == hullAlignAt ||
1288                  type_ == hullXAlignAt || type_ == hullFlAlign) {
1289                 if (newtype < hullAlign) {
1290                         changeCols(3);
1291                         setType(hullEqnArray);
1292                         mutate(newtype);
1293                 } else if (newtype == hullGather || newtype == hullMultline) {
1294                         changeCols(1);
1295                         setType(newtype);
1296                 } else if (newtype ==   hullXXAlignAt) {
1297                         for (row_type row = 0; row < nrows(); ++row)
1298                                 numbered(row, false);
1299                         setType(newtype);
1300                 } else {
1301                         setType(newtype);
1302                 }
1303         }
1304
1305         else if (type_ == hullXXAlignAt) {
1306                 for (row_type row = 0; row < nrows(); ++row)
1307                         numbered(row, false);
1308                 if (newtype < hullAlign) {
1309                         changeCols(3);
1310                         setType(hullEqnArray);
1311                         mutate(newtype);
1312                 } else if (newtype == hullGather || newtype == hullMultline) {
1313                         changeCols(1);
1314                         setType(newtype);
1315                 } else {
1316                         setType(newtype);
1317                 }
1318         }
1319
1320         else if (type_ == hullMultline || type_ == hullGather) {
1321                 if (newtype == hullGather || newtype == hullMultline)
1322                         setType(newtype);
1323                 else if (newtype == hullAlign || newtype == hullFlAlign  ||
1324                          newtype == hullAlignAt || newtype == hullXAlignAt) {
1325                         splitTo2Cols();
1326                         setType(newtype);
1327                 } else if (newtype ==   hullXXAlignAt) {
1328                         splitTo2Cols();
1329                         for (row_type row = 0; row < nrows(); ++row)
1330                                 numbered(row, false);
1331                         setType(newtype);
1332                 } else {
1333                         splitTo3Cols();
1334                         setType(hullEqnArray);
1335                         mutate(newtype);
1336                 }
1337         }
1338
1339         else {
1340                 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1341                        << "' to '" << to_utf8(hullName(newtype))
1342                        << "' not implemented" << endl;
1343         }
1344 }
1345
1346
1347 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1348                 bool last_eoln) const
1349 {
1350         docstring res;
1351         if (numberedType()) {
1352                 if (label_[row] && numbered(row)) {
1353                         docstring const name =
1354                                 latex ? escape(label_[row]->getParam("name"))
1355                                       : label_[row]->getParam("name");
1356                         res += "\\label{" + name + '}';
1357                 }
1358                 if (type_ != hullMultline) {
1359                         if (numbered_[row]  == NONUMBER)
1360                                 res += "\\nonumber ";
1361                         else if (numbered_[row]  == NOTAG)
1362                                 res += "\\notag ";
1363                 }
1364         }
1365         // Never add \\ on the last empty line of eqnarray and friends
1366         last_eoln = false;
1367         return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1368 }
1369
1370
1371 void InsetMathHull::write(WriteStream & os) const
1372 {
1373         ModeSpecifier specifier(os, MATH_MODE);
1374         header_write(os);
1375         InsetMathGrid::write(os);
1376         footer_write(os);
1377 }
1378
1379
1380 void InsetMathHull::normalize(NormalStream & os) const
1381 {
1382         os << "[formula " << hullName(type_) << ' ';
1383         InsetMathGrid::normalize(os);
1384         os << "] ";
1385 }
1386
1387
1388 void InsetMathHull::infoize(odocstream & os) const
1389 {
1390         os << bformat(_("Type: %1$s"), hullName(type_));
1391 }
1392
1393
1394 void InsetMathHull::check() const
1395 {
1396         LATTEST(numbered_.size() == nrows());
1397         LATTEST(numbers_.size() == nrows());
1398         LATTEST(label_.size() == nrows());
1399 }
1400
1401
1402 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1403 {
1404         docstring dlang;
1405         docstring extra;
1406         idocstringstream iss(func.argument());
1407         iss >> dlang >> extra;
1408         if (extra.empty())
1409                 extra = from_ascii("noextra");
1410         string const lang = to_ascii(dlang);
1411
1412         // replace selection with result of computation
1413         if (reduceSelectionToOneCell(cur)) {
1414                 MathData ar;
1415                 asArray(grabAndEraseSelection(cur), ar);
1416                 lyxerr << "use selection: " << ar << endl;
1417                 cur.insert(pipeThroughExtern(lang, extra, ar));
1418                 return;
1419         }
1420
1421         // only inline, display or eqnarray math is allowed
1422         if (getType() > hullEqnArray) {
1423                 frontend::Alert::warning(_("Bad math environment"),
1424                                 _("Computation cannot be performed for AMS "
1425                                   "math environments.\nChange the math "
1426                                   "formula type and try again."));
1427                 return;
1428         }
1429
1430         MathData eq;
1431         eq.push_back(MathAtom(new InsetMathChar('=')));
1432
1433         // go to first item in line
1434         cur.idx() -= cur.idx() % ncols();
1435         cur.pos() = 0;
1436
1437         if (getType() == hullSimple) {
1438                 size_type pos = cur.cell().find_last(eq);
1439                 MathData ar;
1440                 if (pos == cur.cell().size()) {
1441                         ar = cur.cell();
1442                         lyxerr << "use whole cell: " << ar << endl;
1443                 } else {
1444                         ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1445                         lyxerr << "use partial cell form pos: " << pos << endl;
1446                 }
1447                 cur.cell().append(eq);
1448                 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1449                 cur.pos() = cur.lastpos();
1450                 return;
1451         }
1452
1453         if (getType() == hullEquation) {
1454                 lyxerr << "use equation inset" << endl;
1455                 mutate(hullEqnArray);
1456                 MathData & ar = cur.cell();
1457                 lyxerr << "use cell: " << ar << endl;
1458                 ++cur.idx();
1459                 cur.cell() = eq;
1460                 ++cur.idx();
1461                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1462                 // move to end of line
1463                 cur.pos() = cur.lastpos();
1464                 return;
1465         }
1466
1467         {
1468                 lyxerr << "use eqnarray" << endl;
1469                 cur.idx() += 2 - cur.idx() % ncols();
1470                 cur.pos() = 0;
1471                 MathData ar = cur.cell();
1472                 lyxerr << "use cell: " << ar << endl;
1473                 // FIXME: temporarily disabled
1474                 addRow(cur.row());
1475                 ++cur.idx();
1476                 ++cur.idx();
1477                 cur.cell() = eq;
1478                 ++cur.idx();
1479                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1480                 cur.pos() = cur.lastpos();
1481         }
1482 }
1483
1484
1485 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1486 {
1487         //lyxerr << "action: " << cmd.action() << endl;
1488         switch (cmd.action()) {
1489
1490         case LFUN_FINISHED_BACKWARD:
1491         case LFUN_FINISHED_FORWARD:
1492         case LFUN_FINISHED_RIGHT:
1493         case LFUN_FINISHED_LEFT:
1494                 //lyxerr << "action: " << cmd.action() << endl;
1495                 InsetMathGrid::doDispatch(cur, cmd);
1496                 break;
1497
1498         case LFUN_PARAGRAPH_BREAK:
1499                 // just swallow this
1500                 break;
1501
1502         case LFUN_NEWLINE_INSERT:
1503                 // some magic for the common case
1504                 if (type_ == hullSimple || type_ == hullEquation) {
1505                         cur.recordUndoInset();
1506                         bool const align =
1507                                 cur.bv().buffer().params().use_package("amsmath") == BufferParams::package_on;
1508                         mutate(align ? hullAlign : hullEqnArray);
1509                         // mutate() may change labels and such.
1510                         cur.forceBufferUpdate();
1511                         cur.idx() = nrows() * ncols() - 1;
1512                         cur.pos() = cur.lastpos();
1513                 }
1514                 InsetMathGrid::doDispatch(cur, cmd);
1515                 break;
1516
1517         case LFUN_MATH_NUMBER_TOGGLE: {
1518                 //lyxerr << "toggling all numbers" << endl;
1519                 cur.recordUndoInset();
1520                 bool old = numberedType();
1521                 if (type_ == hullMultline)
1522                         numbered(nrows() - 1, !old);
1523                 else
1524                         for (row_type row = 0; row < nrows(); ++row)
1525                                 numbered(row, !old);
1526
1527                 cur.message(old ? _("No number") : _("Number"));
1528                 cur.forceBufferUpdate();
1529                 break;
1530         }
1531
1532         case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1533                 cur.recordUndoInset();
1534                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1535                 bool old = numbered(r);
1536                 cur.message(old ? _("No number") : _("Number"));
1537                 numbered(r, !old);
1538                 cur.forceBufferUpdate();
1539                 break;
1540         }
1541
1542         case LFUN_LABEL_INSERT: {
1543                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1544                 docstring old_label = label(r);
1545                 docstring const default_label = from_ascii("eq:");
1546                 if (old_label.empty())
1547                         old_label = default_label;
1548
1549                 InsetCommandParams p(LABEL_CODE);
1550                 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1551                 string const data = InsetCommand::params2string(p);
1552
1553                 if (cmd.argument().empty())
1554                         cur.bv().showDialog("label", data);
1555                 else {
1556                         FuncRequest fr(LFUN_INSET_INSERT, data);
1557                         dispatch(cur, fr);
1558                 }
1559                 break;
1560         }
1561
1562         case LFUN_LABEL_COPY_AS_REFERENCE: {
1563                 row_type row;
1564                 if (cmd.argument().empty() && &cur.inset() == this)
1565                         // if there is no argument and we're inside math, we retrieve
1566                         // the row number from the cursor position.
1567                         row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1568                 else {
1569                         // if there is an argument, find the corresponding label, else
1570                         // check whether there is at least one label.
1571                         for (row = 0; row != nrows(); ++row)
1572                                 if (numbered(row) && label_[row]
1573                                           && (cmd.argument().empty() || label(row) == cmd.argument()))
1574                                         break;
1575                 }
1576
1577                 if (row == nrows())
1578                         break;
1579
1580                 InsetCommandParams p(REF_CODE, "ref");
1581                 p["reference"] = label(row);
1582                 cap::clearSelection();
1583                 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1584                 break;
1585         }
1586
1587         case LFUN_WORD_DELETE_FORWARD:
1588         case LFUN_CHAR_DELETE_FORWARD:
1589                 if (col(cur.idx()) + 1 == ncols()
1590                     && cur.pos() == cur.lastpos()
1591                     && !cur.selection()) {
1592                         if (!label(row(cur.idx())).empty()) {
1593                                 cur.recordUndoInset();
1594                                 label(row(cur.idx()), docstring());
1595                         } else if (numbered(row(cur.idx()))) {
1596                                 cur.recordUndoInset();
1597                                 numbered(row(cur.idx()), false);
1598                                 cur.forceBufferUpdate();
1599                         } else {
1600                                 InsetMathGrid::doDispatch(cur, cmd);
1601                                 return;
1602                         }
1603                 } else {
1604                         InsetMathGrid::doDispatch(cur, cmd);
1605                         return;
1606                 }
1607                 break;
1608
1609         case LFUN_INSET_INSERT: {
1610                 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1611                 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1612                 string const name = cmd.getArg(0);
1613                 if (name == "label") {
1614                         InsetCommandParams p(LABEL_CODE);
1615                         InsetCommand::string2params(to_utf8(cmd.argument()), p);
1616                         docstring str = p["name"];
1617                         cur.recordUndoInset();
1618                         row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1619                         str = trim(str);
1620                         if (!str.empty())
1621                                 numbered(r, true);
1622                         docstring old = label(r);
1623                         if (str != old) {
1624                                 if (label_[r])
1625                                         // The label will take care of the reference update.
1626                                         label(r, str);
1627                                 else {
1628                                         label(r, str);
1629                                         // Newly created inset so initialize it.
1630                                         label_[r]->initView();
1631                                 }
1632                         }
1633                         cur.forceBufferUpdate();
1634                         break;
1635                 }
1636                 InsetMathGrid::doDispatch(cur, cmd);
1637                 return;
1638         }
1639
1640         case LFUN_MATH_EXTERN:
1641                 cur.recordUndoInset();
1642                 doExtern(cur, cmd);
1643                 break;
1644
1645         case LFUN_MATH_MUTATE: {
1646                 cur.recordUndoInset();
1647                 row_type row = cur.row();
1648                 col_type col = cur.col();
1649                 mutate(hullType(cmd.argument()));
1650                 cur.idx() = row * ncols() + col;
1651                 if (cur.idx() > cur.lastidx()) {
1652                         cur.idx() = cur.lastidx();
1653                         cur.pos() = cur.lastpos();
1654                 }
1655                 if (cur.pos() > cur.lastpos())
1656                         cur.pos() = cur.lastpos();
1657
1658                 cur.forceBufferUpdate();
1659                 // FIXME: find some more clever handling of the selection,
1660                 // i.e. preserve it.
1661                 cur.clearSelection();
1662                 //cur.dispatched(FINISHED);
1663                 break;
1664         }
1665
1666         case LFUN_MATH_DISPLAY: {
1667                 cur.recordUndoInset();
1668                 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1669                 // if the cursor is in a cell that got merged, move it to
1670                 // start of the hull inset.
1671                 if (cur.idx() > 0) {
1672                         cur.idx() = 0;
1673                         cur.pos() = 0;
1674                 }
1675                 if (cur.pos() > cur.lastpos())
1676                         cur.pos() = cur.lastpos();
1677
1678                 break;
1679         }
1680
1681         default:
1682                 InsetMathGrid::doDispatch(cur, cmd);
1683                 break;
1684         }
1685 }
1686
1687
1688 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1689                 FuncStatus & status) const
1690 {
1691         switch (cmd.action()) {
1692         case LFUN_FINISHED_BACKWARD:
1693         case LFUN_FINISHED_FORWARD:
1694         case LFUN_FINISHED_RIGHT:
1695         case LFUN_FINISHED_LEFT:
1696         case LFUN_UP:
1697         case LFUN_DOWN:
1698         case LFUN_NEWLINE_INSERT:
1699         case LFUN_MATH_EXTERN:
1700                 // we handle these
1701                 status.setEnabled(true);
1702                 return true;
1703
1704         // we never allow this in math, and we want to bind enter
1705         // to another actions in command-alternatives
1706         case LFUN_PARAGRAPH_BREAK:
1707                 status.setEnabled(false);
1708                 return true;
1709         case LFUN_MATH_MUTATE: {
1710                 HullType const ht = hullType(cmd.argument());
1711                 status.setOnOff(type_ == ht);
1712                 status.setEnabled(true);
1713
1714                 if (ht != hullSimple) {
1715                         Cursor tmpcur = cur;
1716                         while (!tmpcur.empty()) {
1717                                 InsetCode code = tmpcur.inset().lyxCode();
1718                                 if (code == BOX_CODE) {
1719                                         return true;
1720                                 } else if (code == TABULAR_CODE) {
1721                                         FuncRequest tmpcmd(LFUN_MATH_DISPLAY);
1722                                         if (tmpcur.getStatus(tmpcmd, status) && !status.enabled())
1723                                                 return true;
1724                                 }
1725                                 tmpcur.pop_back();
1726                         }
1727                 }
1728                 return true;
1729         }
1730         case LFUN_MATH_DISPLAY: {
1731                 bool enable = true;
1732                 if (cur.depth() > 1) {
1733                         Inset const & in = cur[cur.depth()-2].inset();
1734                         if (in.lyxCode() == SCRIPT_CODE)
1735                                 enable = display() != Inline;
1736                 }
1737                 status.setEnabled(enable);
1738                 status.setOnOff(display() != Inline);
1739                 return true;
1740         }
1741
1742         case LFUN_MATH_NUMBER_TOGGLE:
1743                 // FIXME: what is the right test, this or the one of
1744                 // LABEL_INSERT?
1745                 status.setEnabled(display() != Inline);
1746                 status.setOnOff(numberedType());
1747                 return true;
1748
1749         case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1750                 // FIXME: what is the right test, this or the one of
1751                 // LABEL_INSERT?
1752                 bool const enable = (type_ == hullMultline)
1753                         ? (nrows() - 1 == cur.row())
1754                         : display() != Inline;
1755                 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1756                 status.setEnabled(enable);
1757                 status.setOnOff(enable && numbered(r));
1758                 return true;
1759         }
1760
1761         case LFUN_LABEL_INSERT:
1762                 status.setEnabled(type_ != hullSimple);
1763                 return true;
1764
1765         case LFUN_LABEL_COPY_AS_REFERENCE: {
1766                 bool enabled = false;
1767                 row_type row;
1768                 if (cmd.argument().empty() && &cur.inset() == this) {
1769                         // if there is no argument and we're inside math, we retrieve
1770                         // the row number from the cursor position.
1771                         row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1772                         enabled = numberedType() && label_[row] && numbered(row);
1773                 } else {
1774                         // if there is an argument, find the corresponding label, else
1775                         // check whether there is at least one label.
1776                         for (row_type row = 0; row != nrows(); ++row) {
1777                                 if (numbered(row) && label_[row] &&
1778                                         (cmd.argument().empty() || label(row) == cmd.argument())) {
1779                                                 enabled = true;
1780                                                 break;
1781                                 }
1782                         }
1783                 }
1784                 status.setEnabled(enabled);
1785                 return true;
1786         }
1787
1788         case LFUN_INSET_INSERT:
1789                 if (cmd.getArg(0) == "label") {
1790                         status.setEnabled(type_ != hullSimple);
1791                         return true;
1792                 }
1793                 return InsetMathGrid::getStatus(cur, cmd, status);
1794
1795         case LFUN_INSET_MODIFY: {
1796                 istringstream is(to_utf8(cmd.argument()));
1797                 string s;
1798                 is >> s;
1799                 if (s != "tabular")
1800                         return InsetMathGrid::getStatus(cur, cmd, status);
1801                 is >> s;
1802                 if (!rowChangeOK()
1803                     && (s == "append-row"
1804                         || s == "delete-row"
1805                         || s == "copy-row")) {
1806                         status.message(bformat(
1807                                 from_utf8(N_("Can't change number of rows in '%1$s'")),
1808                                 hullName(type_)));
1809                         status.setEnabled(false);
1810                         return true;
1811                 }
1812                 if (!colChangeOK()
1813                     && (s == "append-column"
1814                         || s == "delete-column"
1815                         || s == "copy-column")) {
1816                         status.message(bformat(
1817                                 from_utf8(N_("Can't change number of columns in '%1$s'")),
1818                                 hullName(type_)));
1819                         status.setEnabled(false);
1820                         return true;
1821                 }
1822                 if ((type_ == hullSimple
1823                   || type_ == hullEquation
1824                   || type_ == hullNone) &&
1825                     (s == "add-hline-above" || s == "add-hline-below")) {
1826                         status.message(bformat(
1827                                 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1828                                 hullName(type_)));
1829                         status.setEnabled(false);
1830                         return true;
1831                 }
1832                 if (s == "add-vline-left" || s == "add-vline-right") {
1833                         status.message(bformat(
1834                                 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1835                                 hullName(type_)));
1836                         status.setEnabled(false);
1837                         return true;
1838                 }
1839                 if (s == "valign-top" || s == "valign-middle"
1840                  || s == "valign-bottom" || s == "align-left"
1841                  || s == "align-center" || s == "align-right") {
1842                         status.setEnabled(false);
1843                         return true;
1844                 }
1845                 return InsetMathGrid::getStatus(cur, cmd, status);
1846         }
1847
1848         default:
1849                 return InsetMathGrid::getStatus(cur, cmd, status);
1850         }
1851
1852         // This cannot really happen, but inserted to shut-up gcc
1853         return InsetMathGrid::getStatus(cur, cmd, status);
1854 }
1855
1856
1857 /////////////////////////////////////////////////////////////////////
1858
1859
1860
1861 // simply scrap this function if you want
1862 void InsetMathHull::mutateToText()
1863 {
1864 #if 0
1865         // translate to latex
1866         ostringstream os;
1867         latex(os, false, false);
1868         string str = os.str();
1869
1870         // insert this text
1871         Text * lt = view_->cursor().innerText();
1872         string::const_iterator cit = str.begin();
1873         string::const_iterator end = str.end();
1874         for (; cit != end; ++cit)
1875                 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1876
1877         // remove ourselves
1878         //dispatch(LFUN_ESCAPE);
1879 #endif
1880 }
1881
1882
1883 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1884         docstring const & font)
1885 {
1886         // this whole function is a hack and won't work for incremental font
1887         // changes...
1888         cur.recordUndo();
1889         if (cur.inset().asInsetMath()->name() == font)
1890                 cur.handleFont(to_utf8(font));
1891         else {
1892                 cur.handleNest(createInsetMath(font, cur.buffer()));
1893                 cur.insert(arg);
1894         }
1895 }
1896
1897
1898 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1899 {
1900         cur.recordUndo();
1901         Font font;
1902         bool b;
1903         font.fromString(to_utf8(arg), b);
1904         if (font.fontInfo().color() != Color_inherit) {
1905                 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1906                 cur.handleNest(at, 0);
1907         }
1908 }
1909
1910
1911 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1912 {
1913         cur.push(*this);
1914         bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1915                 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1916         enter_front ? idxFirst(cur) : idxLast(cur);
1917         // The inset formula dimension is not necessarily the same as the
1918         // one of the instant preview image, so we have to indicate to the
1919         // BufferView that a metrics update is needed.
1920         cur.screenUpdateFlags(Update::Force);
1921 }
1922
1923
1924 void InsetMathHull::revealCodes(Cursor & cur) const
1925 {
1926         if (!cur.inMathed())
1927                 return;
1928         odocstringstream os;
1929         cur.info(os);
1930         cur.message(os.str());
1931 /*
1932         // write something to the minibuffer
1933         // translate to latex
1934         cur.markInsert(bv);
1935         ostringstream os;
1936         write(os);
1937         string str = os.str();
1938         cur.markErase(bv);
1939         string::size_type pos = 0;
1940         string res;
1941         for (string::iterator it = str.begin(); it != str.end(); ++it) {
1942                 if (*it == '\n')
1943                         res += ' ';
1944                 else if (*it == '\0') {
1945                         res += "  -X-  ";
1946                         pos = it - str.begin();
1947                 }
1948                 else
1949                         res += *it;
1950         }
1951         if (pos > 30)
1952                 res = res.substr(pos - 30);
1953         if (res.size() > 60)
1954                 res = res.substr(0, 60);
1955         cur.message(res);
1956 */
1957 }
1958
1959
1960 /////////////////////////////////////////////////////////////////////
1961
1962
1963 #if 0
1964 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1965                                      bool, bool)
1966 {
1967         // FIXME: completely broken
1968         static InsetMathHull * lastformula = 0;
1969         static CursorBase current = DocIterator(ibegin(nucleus()));
1970         static MathData ar;
1971         static string laststr;
1972
1973         if (lastformula != this || laststr != str) {
1974                 //lyxerr << "reset lastformula to " << this << endl;
1975                 lastformula = this;
1976                 laststr = str;
1977                 current = ibegin(nucleus());
1978                 ar.clear();
1979                 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1980         } else {
1981                 increment(current);
1982         }
1983         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1984
1985         for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1986                 CursorSlice & top = it.back();
1987                 MathData const & a = top.asInsetMath()->cell(top.idx_);
1988                 if (a.matchpart(ar, top.pos_)) {
1989                         bv->cursor().setSelection(it, ar.size());
1990                         current = it;
1991                         top.pos_ += ar.size();
1992                         bv->update();
1993                         return true;
1994                 }
1995         }
1996
1997         //lyxerr << "not found!" << endl;
1998         lastformula = 0;
1999         return false;
2000 }
2001 #endif
2002
2003
2004 void InsetMathHull::write(ostream & os) const
2005 {
2006         odocstringstream oss;
2007         WriteStream wi(oss, false, false, WriteStream::wsDefault);
2008         oss << "Formula ";
2009         write(wi);
2010         os << to_utf8(oss.str());
2011 }
2012
2013
2014 void InsetMathHull::read(Lexer & lex)
2015 {
2016         MathAtom at;
2017         mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2018         operator=(*at->asHullInset());
2019 }
2020
2021
2022 bool InsetMathHull::readQuiet(Lexer & lex)
2023 {
2024         MathAtom at;
2025         bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2026         if (success)
2027                 operator=(*at->asHullInset());
2028         return success;
2029 }
2030
2031
2032 int InsetMathHull::plaintext(odocstringstream & os,
2033         OutputParams const & op, size_t max_length) const
2034 {
2035         // disables ASCII-art for export of equations. See #2275.
2036         if (0 && display()) {
2037                 Dimension dim;
2038                 TextMetricsInfo mi;
2039                 metricsT(mi, dim);
2040                 TextPainter tpain(dim.width(), dim.height());
2041                 drawT(tpain, 0, dim.ascent());
2042                 tpain.show(os, 3);
2043                 // reset metrics cache to "real" values
2044                 //metrics();
2045                 return tpain.textheight();
2046         }
2047
2048         odocstringstream oss;
2049         Encoding const * const enc = encodings.fromLyXName("utf8");
2050         WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
2051
2052         // Fix Bug #6139
2053         if (type_ == hullRegexp)
2054                 write(wi);
2055         else {
2056                 for (row_type r = 0; r < nrows(); ++r) {
2057                         for (col_type c = 0; c < ncols(); ++c)
2058                                 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2059                         // if it's for the TOC, we write just the first line
2060                         // and do not include the newline.
2061                         if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2062                                 break;
2063                         if (r < nrows() - 1)
2064                                 wi << "\n";
2065                 }
2066         }
2067         docstring const str = oss.str();
2068         os << str;
2069         return str.size();
2070 }
2071
2072
2073 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
2074 {
2075         MathStream ms(os);
2076         int res = 0;
2077         docstring name;
2078         if (getType() == hullSimple)
2079                 name = from_ascii("inlineequation");
2080         else
2081                 name = from_ascii("informalequation");
2082
2083         docstring bname = name;
2084         if (!label(0).empty())
2085                 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
2086
2087         ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
2088
2089         odocstringstream ls;
2090         if (runparams.flavor == OutputParams::XML) {
2091                 ms << MTag("alt role='tex' ");
2092                 // Workaround for db2latex: db2latex always includes equations with
2093                 // \ensuremath{} or \begin{display}\end{display}
2094                 // so we strip LyX' math environment
2095                 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
2096                 InsetMathGrid::write(wi);
2097                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
2098                 ms << ETag("alt");
2099                 ms << MTag("math");
2100                 ms << ETag("alt");
2101                 ms << MTag("math");
2102                 InsetMathGrid::mathmlize(ms);
2103                 ms << ETag("math");
2104         } else {
2105                 TexRow texrow;
2106                 texrow.reset();
2107                 otexstream ols(ls, texrow);
2108                 ms << MTag("alt role='tex'");
2109                 latex(ols, runparams);
2110                 res = texrow.rows();
2111                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
2112                 ms << ETag("alt");
2113         }
2114
2115         ms << from_ascii("<graphic fileref=\"eqn/");
2116         if (!label(0).empty())
2117                 ms << sgml::cleanID(buffer(), runparams, label(0));
2118         else
2119                 ms << sgml::uniqueID(from_ascii("anon"));
2120
2121         if (runparams.flavor == OutputParams::XML)
2122                 ms << from_ascii("\"/>");
2123         else
2124                 ms << from_ascii("\">");
2125
2126         ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2127
2128         return ms.line() + res;
2129 }
2130
2131
2132 bool InsetMathHull::haveNumbers() const
2133 {
2134         bool havenumbers = false;
2135         // inline formulas are never numbered (bug 7351 part 3)
2136         if (getType() == hullSimple)
2137                 return havenumbers;
2138         for (size_t i = 0; i != numbered_.size(); ++i) {
2139                 if (numbered(i)) {
2140                         havenumbers = true;
2141                         break;
2142                 }
2143         }
2144         return havenumbers;
2145 }
2146
2147
2148 // FIXME XHTML
2149 // We need to do something about alignment here.
2150 //
2151 // This duplicates code from InsetMathGrid, but
2152 // we need access here to number information,
2153 // and we simply do not have that in InsetMathGrid.
2154 void InsetMathHull::htmlize(HtmlStream & os) const
2155 {
2156         bool const havenumbers = haveNumbers();
2157         bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2158
2159         if (!havetable) {
2160                 os << cell(index(0, 0));
2161                 return;
2162         }
2163
2164         os << MTag("table", "class='mathtable'");
2165         for (row_type row = 0; row < nrows(); ++row) {
2166                 os << MTag("tr");
2167                 for (col_type col = 0; col < ncols(); ++col) {
2168                         os << MTag("td");
2169                         os << cell(index(row, col));
2170                         os << ETag("td");
2171                 }
2172                 if (havenumbers) {
2173                         os << MTag("td");
2174                         docstring const & num = numbers_[row];
2175                         if (!num.empty())
2176                                 os << '(' << num << ')';
2177                   os << ETag("td");
2178                 }
2179                 os << ETag("tr");
2180         }
2181         os << ETag("table");
2182 }
2183
2184
2185 // this duplicates code from InsetMathGrid, but
2186 // we need access here to number information,
2187 // and we simply do not have that in InsetMathGrid.
2188 void InsetMathHull::mathmlize(MathStream & os) const
2189 {
2190         bool const havenumbers = haveNumbers();
2191         bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2192
2193         if (havetable)
2194                 os << MTag("mtable");
2195         char const * const celltag = havetable ? "mtd" : "mrow";
2196         // FIXME There does not seem to be wide support at the moment
2197         // for mlabeledtr, so we have to use just mtr for now.
2198         // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2199         char const * const rowtag = "mtr";
2200         for (row_type row = 0; row < nrows(); ++row) {
2201                 if (havetable)
2202                         os << MTag(rowtag);
2203                 for (col_type col = 0; col < ncols(); ++col) {
2204                         os << MTag(celltag)
2205                            << cell(index(row, col))
2206                            << ETag(celltag);
2207                 }
2208                 // fleqn?
2209                 if (havenumbers) {
2210                         os << MTag("mtd");
2211                         docstring const & num = numbers_[row];
2212                         if (!num.empty())
2213                                 os << '(' << num << ')';
2214                   os << ETag("mtd");
2215                 }
2216                 if (havetable)
2217                         os << ETag(rowtag);
2218         }
2219         if (havetable)
2220                 os << ETag("mtable");
2221 }
2222
2223
2224 void InsetMathHull::mathAsLatex(WriteStream & os) const
2225 {
2226         MathEnsurer ensurer(os, false);
2227         bool havenumbers = haveNumbers();
2228         bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2229
2230         if (!havetable) {
2231                 os << cell(index(0, 0));
2232                 return;
2233         }
2234
2235         os << "<table class='mathtable'>";
2236         for (row_type row = 0; row < nrows(); ++row) {
2237                 os << "<tr>";
2238                 for (col_type col = 0; col < ncols(); ++col) {
2239                         os << "<td class='math'>";
2240                         os << cell(index(row, col));
2241                         os << "</td>";
2242                 }
2243                 if (havenumbers) {
2244                         os << "<td>";
2245                         docstring const & num = numbers_[row];
2246                         if (!num.empty())
2247                                 os << '(' << num << ')';
2248                   os << "</td>";
2249                 }
2250                 os << "</tr>";
2251         }
2252         os << "</table>";
2253 }
2254
2255
2256 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2257 {
2258         BufferParams::MathOutput const mathtype =
2259                 buffer().masterBuffer()->params().html_math_output;
2260
2261         bool success = false;
2262
2263         // we output all the labels just at the beginning of the equation.
2264         // this should be fine.
2265         for (size_t i = 0; i != label_.size(); ++i) {
2266                 InsetLabel const * const il = label_[i];
2267                 if (!il)
2268                         continue;
2269                 il->xhtml(xs, op);
2270         }
2271
2272         // FIXME Eventually we would like to do this inset by inset.
2273         if (mathtype == BufferParams::MathML) {
2274                 odocstringstream os;
2275                 MathStream ms(os);
2276                 try {
2277                         mathmlize(ms);
2278                         success = true;
2279                 } catch (MathExportException const &) {}
2280                 if (success) {
2281                         if (getType() == hullSimple)
2282                                 xs << html::StartTag("math",
2283                                                         "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2284                         else
2285                                 xs << html::StartTag("math",
2286                                       "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2287                         xs << XHTMLStream::ESCAPE_NONE
2288                                  << os.str()
2289                                  << html::EndTag("math");
2290                 }
2291         } else if (mathtype == BufferParams::HTML) {
2292                 odocstringstream os;
2293                 HtmlStream ms(os);
2294                 try {
2295                         htmlize(ms);
2296                         success = true;
2297                 } catch (MathExportException const &) {}
2298                 if (success) {
2299                         string const tag = (getType() == hullSimple) ? "span" : "div";
2300                         xs << html::StartTag(tag, "class='formula'", true)
2301                            << XHTMLStream::ESCAPE_NONE
2302                            << os.str()
2303                            << html::EndTag(tag);
2304                 }
2305         }
2306
2307         // what we actually want is this:
2308         // if (
2309         //     ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2310         //       && !success)
2311         //     || mathtype == BufferParams::Images
2312         //    )
2313         // but what follows is equivalent, since we'll enter only if either (a) we
2314         // tried and failed with MathML or HTML or (b) didn't try yet at all but
2315         // aren't doing LaTeX, in which case we are doing Images.
2316         if (!success && mathtype != BufferParams::LaTeX) {
2317                 graphics::PreviewImage const * pimage = 0;
2318                 if (!op.dryrun) {
2319                         loadPreview(docit_);
2320                         pimage = preview_->getPreviewImage(buffer());
2321                         // FIXME Do we always have png?
2322                 }
2323
2324                 if (pimage || op.dryrun) {
2325                         string const filename = pimage ? pimage->filename().onlyFileName()
2326                                                        : "previewimage.png";
2327                         if (pimage) {
2328                                 // if we are not in the master buffer, then we need to see that the
2329                                 // generated image is copied there; otherwise, preview fails.
2330                                 Buffer const * mbuf = buffer().masterBuffer();
2331                                 if (mbuf != &buffer()) {
2332                                         string mbtmp = mbuf->temppath();
2333                                         FileName const mbufimg(support::addName(mbtmp, filename));
2334                                         pimage->filename().copyTo(mbufimg);
2335                                 }
2336                                 // add the file to the list of files to be exported
2337                                 op.exportdata->addExternalFile("xhtml", pimage->filename());
2338                         }
2339
2340                         string const tag = (getType() == hullSimple) ? "span" : "div";
2341                         xs << html::CR()
2342                            << html::StartTag(tag)
2343                                  << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2344                                  << html::EndTag(tag)
2345                                  << html::CR();
2346                         success = true;
2347                 }
2348         }
2349
2350         // so we'll pass this test if we've failed everything else, or
2351         // if mathtype was LaTeX, since we won't have entered any of the
2352         // earlier branches
2353         if (!success /* || mathtype != BufferParams::LaTeX */) {
2354                 // Unfortunately, we cannot use latexString() because we do not want
2355                 // $...$ or whatever.
2356                 odocstringstream ls;
2357                 WriteStream wi(ls, false, true, WriteStream::wsPreview);
2358                 ModeSpecifier specifier(wi, MATH_MODE);
2359                 mathAsLatex(wi);
2360                 docstring const latex = ls.str();
2361
2362                 // class='math' allows for use of jsMath
2363                 // http://www.math.union.edu/~dpvc/jsMath/
2364                 // FIXME XHTML
2365                 // probably should allow for some kind of customization here
2366                 string const tag = (getType() == hullSimple) ? "span" : "div";
2367                 xs << html::StartTag(tag, "class='math'")
2368                    << latex
2369                    << html::EndTag(tag)
2370                    << html::CR();
2371         }
2372         return docstring();
2373 }
2374
2375
2376 void InsetMathHull::toString(odocstream & os) const
2377 {
2378         odocstringstream ods;
2379         plaintext(ods, OutputParams(0));
2380         os << ods.str();
2381 }
2382
2383
2384 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2385 {
2386         odocstringstream ods;
2387         OutputParams op(0);
2388         op.for_toc = true;
2389         // FIXME: this results in spilling TeX into the LyXHTML output since the
2390         // outliner is used to generate the LyXHTML list of figures/etc.
2391         plaintext(ods, op);
2392         os += ods.str();
2393 }
2394
2395
2396 string InsetMathHull::contextMenuName() const
2397 {
2398         return "context-math";
2399 }
2400
2401
2402 void InsetMathHull::recordLocation(DocIterator const & di)
2403 {
2404         docit_ = di;
2405 }
2406
2407 } // namespace lyx