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