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