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