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