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