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