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