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