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