]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathHull.cpp
Small improvement for bug #7509 as suggested by JMarc
[lyx.git] / src / mathed / InsetMathHull.cpp
1 /**
2  * \file InsetMathHull.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetMathHull.h"
14
15 #include "InsetMathChar.h"
16 #include "InsetMathColor.h"
17 #include "MathExtern.h"
18 #include "MathFactory.h"
19 #include "MathStream.h"
20 #include "MathSupport.h"
21
22 #include "Buffer.h"
23 #include "BufferParams.h"
24 #include "BufferView.h"
25 #include "ColorSet.h"
26 #include "CutAndPaste.h"
27 #include "Encoding.h"
28 #include "Exporter.h"
29 #include "FuncRequest.h"
30 #include "FuncStatus.h"
31 #include "Language.h"
32 #include "LaTeXFeatures.h"
33 #include "LyXRC.h"
34 #include "MacroTable.h"
35 #include "output_xhtml.h"
36 #include "Paragraph.h"
37 #include "ParIterator.h"
38 #include "sgml.h"
39 #include "TextClass.h"
40 #include "TextPainter.h"
41 #include "TocBackend.h"
42
43 #include "insets/InsetLabel.h"
44 #include "insets/InsetRef.h"
45 #include "insets/RenderPreview.h"
46
47 #include "graphics/PreviewImage.h"
48 #include "graphics/PreviewLoader.h"
49
50 #include "frontends/alert.h"
51 #include "frontends/Painter.h"
52
53 #include "support/convert.h"
54 #include "support/lassert.h"
55 #include "support/debug.h"
56 #include "support/filetools.h"
57 #include "support/gettext.h"
58 #include "support/lstrings.h"
59
60 #include <sstream>
61
62 using namespace std;
63 using namespace lyx::support;
64
65 namespace lyx {
66
67 using cap::grabAndEraseSelection;
68
69 namespace {
70
71         int getCols(HullType type)
72         {
73                 switch (type) {
74                         case hullEqnArray:
75                                 return 3;
76                         case hullAlign:
77                         case hullFlAlign:
78                         case hullAlignAt:
79                         case hullXAlignAt:
80                         case hullXXAlignAt:
81                                 return 2;
82                         default:
83                                 return 1;
84                 }
85         }
86
87
88         // returns position of first relation operator in the array
89         // used for "intelligent splitting"
90         size_t firstRelOp(MathData const & ar)
91         {
92                 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
93                         if ((*it)->isRelOp())
94                                 return it - ar.begin();
95                 return ar.size();
96         }
97
98
99         char const * star(bool numbered)
100         {
101                 return numbered ? "" : "*";
102         }
103
104
105 } // end anon namespace
106
107
108 HullType hullType(docstring const & s)
109 {
110         if (s == "none")      return hullNone;
111         if (s == "simple")    return hullSimple;
112         if (s == "equation")  return hullEquation;
113         if (s == "eqnarray")  return hullEqnArray;
114         if (s == "align")     return hullAlign;
115         if (s == "alignat")   return hullAlignAt;
116         if (s == "xalignat")  return hullXAlignAt;
117         if (s == "xxalignat") return hullXXAlignAt;
118         if (s == "multline")  return hullMultline;
119         if (s == "gather")    return hullGather;
120         if (s == "flalign")   return hullFlAlign;
121         if (s == "regexp")    return hullRegexp;
122         lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
123         return HullType(-1);
124 }
125
126
127 docstring hullName(HullType type)
128 {
129         switch (type) {
130                 case hullNone:       return from_ascii("none");
131                 case hullSimple:     return from_ascii("simple");
132                 case hullEquation:   return from_ascii("equation");
133                 case hullEqnArray:   return from_ascii("eqnarray");
134                 case hullAlign:      return from_ascii("align");
135                 case hullAlignAt:    return from_ascii("alignat");
136                 case hullXAlignAt:   return from_ascii("xalignat");
137                 case hullXXAlignAt:  return from_ascii("xxalignat");
138                 case hullMultline:   return from_ascii("multline");
139                 case hullGather:     return from_ascii("gather");
140                 case hullFlAlign:    return from_ascii("flalign");
141                 case hullRegexp:     return from_ascii("regexp");
142                 default:
143                         lyxerr << "unknown hull type '" << type << "'" << endl;
144                         return from_ascii("none");
145         }
146 }
147
148 static InsetLabel * dummy_pointer = 0;
149
150 InsetMathHull::InsetMathHull(Buffer * buf)
151         : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, true),
152     numbers_(1, empty_docstring()), label_(1, dummy_pointer),
153     preview_(new RenderPreview(this))
154 {
155         //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
156         //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
157         //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
158         //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
159         buffer_ = buf;
160         initMath();
161         setDefaults();
162 }
163
164
165 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
166         : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, true),
167     numbers_(1, empty_docstring()), label_(1, dummy_pointer),
168     preview_(new RenderPreview(this))
169 {
170         buffer_ = buf;
171         initMath();
172         setDefaults();
173 }
174
175
176 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
177 {
178         operator=(other);
179 }
180
181
182 InsetMathHull::~InsetMathHull()
183 {
184         for (size_t i = 0; i < label_.size(); ++i)
185                 delete label_[i];
186 }
187
188
189 Inset * InsetMathHull::clone() const
190 {
191         return new InsetMathHull(*this);
192 }
193
194
195 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
196 {
197         if (this == &other)
198                 return *this;
199         InsetMathGrid::operator=(other);
200         type_  = other.type_;
201         numbered_ = other.numbered_;
202         numbers_ = other.numbers_;
203         buffer_ = other.buffer_;
204         for (size_t i = 0; i < label_.size(); ++i)
205                 delete label_[i];
206         label_ = other.label_;
207         for (size_t i = 0; i != label_.size(); ++i) {
208                 if (label_[i])
209                         label_[i] = new InsetLabel(*label_[i]);
210         }
211         preview_.reset(new RenderPreview(*other.preview_, this));
212
213         return *this;
214 }
215
216
217 void InsetMathHull::setBuffer(Buffer & buffer)
218 {
219         InsetMathGrid::setBuffer(buffer);
220
221         for (size_t i = 0; i != label_.size(); ++i) {
222                 if (label_[i])
223                         label_[i]->setBuffer(buffer);
224         }
225 }
226
227
228 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         docstring lab;
888         if (type_ == hullMultline) {
889                 if (row + 1 == nrows())  {
890                         numbered_[row] = false;
891                         lab = label(row);
892                 } else
893                         numbered = false;
894         }
895
896         numbered_.insert(numbered_.begin() + row + 1, numbered);
897         numbers_.insert(numbers_.begin() + row + 1, empty_docstring());
898         label_.insert(label_.begin() + row + 1, dummy_pointer);
899         if (!lab.empty())
900                 label(row + 1, lab);
901         InsetMathGrid::addRow(row);
902 }
903
904
905 void InsetMathHull::swapRow(row_type row)
906 {
907         if (nrows() <= 1)
908                 return;
909         if (row + 1 == nrows())
910                 --row;
911         // gcc implements the standard std::vector<bool> which is *not* a container:
912         //   http://www.gotw.ca/publications/N1185.pdf
913         // As a results, it doesn't like this:
914         //      swap(numbered_[row], numbered_[row + 1]);
915         // so we do it manually:
916         bool const b = numbered_[row];
917         numbered_[row] = numbered_[row + 1];
918         numbered_[row + 1] = b;
919         swap(numbers_[row], numbers_[row + 1]);
920         swap(label_[row], label_[row + 1]);
921         InsetMathGrid::swapRow(row);
922 }
923
924
925 void InsetMathHull::delRow(row_type row)
926 {
927         if (nrows() <= 1 || !rowChangeOK())
928                 return;
929         if (row + 1 == nrows() && type_ == hullMultline) {
930                 bool const b = numbered_[row - 1];
931                 numbered_[row - 1] = numbered_[row];
932                 numbered_[row] = b;
933                 swap(numbers_[row - 1], numbers_[row]);
934                 swap(label_[row - 1], label_[row]);
935                 InsetMathGrid::delRow(row);
936                 return;
937         }
938         InsetMathGrid::delRow(row);
939         // The last dummy row has no number info nor a label.
940         // Test nrows() + 1 because we have already erased the row.
941         if (row == nrows() + 1)
942                 row--;
943         numbered_.erase(numbered_.begin() + row);
944         numbers_.erase(numbers_.begin() + row);
945         delete label_[row];
946         label_.erase(label_.begin() + row);
947 }
948
949
950 void InsetMathHull::addCol(col_type col)
951 {
952         if (!colChangeOK())
953                 return;
954         InsetMathGrid::addCol(col);
955 }
956
957
958 void InsetMathHull::delCol(col_type col)
959 {
960         if (ncols() <= 1 || !colChangeOK())
961                 return;
962         InsetMathGrid::delCol(col);
963 }
964
965
966 docstring InsetMathHull::nicelabel(row_type row) const
967 {
968         if (!numbered_[row])
969                 return docstring();
970         docstring const & val = numbers_[row];
971         if (!label_[row])
972                 return '(' + val + ')';
973         return '(' + val + ',' + label_[row]->screenLabel() + ')';
974 }
975
976
977 void InsetMathHull::glueall(HullType type)
978 {
979         MathData ar;
980         for (idx_type i = 0; i < nargs(); ++i)
981                 ar.append(cell(i));
982         InsetLabel * label = 0;
983         if (type == hullEquation) {
984                 // preserve first non-empty label
985                 for (row_type row = 0; row < nrows(); ++row) {
986                         if (label_[row]) {
987                                 label = label_[row];
988                                 label_[row] = 0;
989                                 break;
990                         }
991                 }
992         }
993         *this = InsetMathHull(buffer_, hullSimple);
994         label_[0] = label;
995         cell(0) = ar;
996         setDefaults();
997 }
998
999
1000 void InsetMathHull::splitTo2Cols()
1001 {
1002         LASSERT(ncols() == 1, /**/);
1003         InsetMathGrid::addCol(1);
1004         for (row_type row = 0; row < nrows(); ++row) {
1005                 idx_type const i = 2 * row;
1006                 pos_type pos = firstRelOp(cell(i));
1007                 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1008                 cell(i).erase(pos, cell(i).size());
1009         }
1010 }
1011
1012
1013 void InsetMathHull::splitTo3Cols()
1014 {
1015         LASSERT(ncols() < 3, /**/);
1016         if (ncols() < 2)
1017                 splitTo2Cols();
1018         InsetMathGrid::addCol(2);
1019         for (row_type row = 0; row < nrows(); ++row) {
1020                 idx_type const i = 3 * row + 1;
1021                 if (cell(i).size()) {
1022                         cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1023                         cell(i).erase(1, cell(i).size());
1024                 }
1025         }
1026 }
1027
1028
1029 void InsetMathHull::changeCols(col_type cols)
1030 {
1031         if (ncols() == cols)
1032                 return;
1033         else if (ncols() < cols) {
1034                 // split columns
1035                 if (cols < 3)
1036                         splitTo2Cols();
1037                 else {
1038                         splitTo3Cols();
1039                         while (ncols() < cols)
1040                                 InsetMathGrid::addCol(ncols());
1041                 }
1042                 return;
1043         }
1044
1045         // combine columns
1046         for (row_type row = 0; row < nrows(); ++row) {
1047                 idx_type const i = row * ncols();
1048                 for (col_type col = cols; col < ncols(); ++col) {
1049                         cell(i + cols - 1).append(cell(i + col));
1050                 }
1051         }
1052         // delete columns
1053         while (ncols() > cols) {
1054                 InsetMathGrid::delCol(ncols() - 1);
1055         }
1056 }
1057
1058
1059 HullType InsetMathHull::getType() const
1060 {
1061         return type_;
1062 }
1063
1064
1065 void InsetMathHull::setType(HullType type)
1066 {
1067         type_ = type;
1068         setDefaults();
1069 }
1070
1071
1072 void InsetMathHull::mutate(HullType newtype)
1073 {
1074         //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1075
1076         // we try to move along the chain
1077         // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1078         //                                     ^                                     |
1079         //                                     +-------------------------------------+
1080         // we use eqnarray as intermediate type for mutations that are not
1081         // directly supported because it handles labels and numbering for
1082         // "down mutation".
1083
1084         if (newtype == type_) {
1085                 // done
1086         }
1087
1088         else if (newtype < hullNone) {
1089                 // unknown type
1090                 dump();
1091         }
1092
1093         else if (type_ == hullNone) {
1094                 setType(hullSimple);
1095                 numbered(0, false);
1096                 mutate(newtype);
1097         }
1098
1099         else if (type_ == hullSimple) {
1100                 if (newtype == hullNone) {
1101                         setType(hullNone);
1102                         numbered(0, false);
1103                 } else {
1104                         setType(hullEquation);
1105                         numbered(0, label_[0] ? true : false);
1106                         mutate(newtype);
1107                 }
1108         }
1109
1110         else if (type_ == hullEquation) {
1111                 if (newtype < type_) {
1112                         setType(hullSimple);
1113                         numbered(0, false);
1114                         mutate(newtype);
1115                 } else if (newtype == hullEqnArray) {
1116                         // split it "nicely" on the first relop
1117                         splitTo3Cols();
1118                         setType(hullEqnArray);
1119                 } else if (newtype == hullMultline || newtype == hullGather) {
1120                         setType(newtype);
1121                 } else {
1122                         // split it "nicely"
1123                         splitTo2Cols();
1124                         setType(hullAlign);
1125                         mutate(newtype);
1126                 }
1127         }
1128
1129         else if (type_ == hullEqnArray) {
1130                 if (newtype < type_) {
1131                         glueall(newtype);
1132                         mutate(newtype);
1133                 } else { // align & Co.
1134                         changeCols(2);
1135                         setType(hullAlign);
1136                         mutate(newtype);
1137                 }
1138         }
1139
1140         else if (type_ ==  hullAlign || type_ == hullAlignAt ||
1141                  type_ == hullXAlignAt || type_ == hullFlAlign) {
1142                 if (newtype < hullAlign) {
1143                         changeCols(3);
1144                         setType(hullEqnArray);
1145                         mutate(newtype);
1146                 } else if (newtype == hullGather || newtype == hullMultline) {
1147                         changeCols(1);
1148                         setType(newtype);
1149                 } else if (newtype ==   hullXXAlignAt) {
1150                         for (row_type row = 0; row < nrows(); ++row)
1151                                 numbered(row, false);
1152                         setType(newtype);
1153                 } else {
1154                         setType(newtype);
1155                 }
1156         }
1157
1158         else if (type_ == hullXXAlignAt) {
1159                 for (row_type row = 0; row < nrows(); ++row)
1160                         numbered(row, false);
1161                 if (newtype < hullAlign) {
1162                         changeCols(3);
1163                         setType(hullEqnArray);
1164                         mutate(newtype);
1165                 } else if (newtype == hullGather || newtype == hullMultline) {
1166                         changeCols(1);
1167                         setType(newtype);
1168                 } else {
1169                         setType(newtype);
1170                 }
1171         }
1172
1173         else if (type_ == hullMultline || type_ == hullGather) {
1174                 if (newtype == hullGather || newtype == hullMultline)
1175                         setType(newtype);
1176                 else if (newtype == hullAlign || newtype == hullFlAlign  ||
1177                          newtype == hullAlignAt || newtype == hullXAlignAt) {
1178                         splitTo2Cols();
1179                         setType(newtype);
1180                 } else if (newtype ==   hullXXAlignAt) {
1181                         splitTo2Cols();
1182                         for (row_type row = 0; row < nrows(); ++row)
1183                                 numbered(row, false);
1184                         setType(newtype);
1185                 } else {
1186                         splitTo3Cols();
1187                         setType(hullEqnArray);
1188                         mutate(newtype);
1189                 }
1190         }
1191
1192         else {
1193                 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1194                        << "' to '" << to_utf8(hullName(newtype))
1195                        << "' not implemented" << endl;
1196         }
1197 }
1198
1199
1200 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1201                 bool last_eoln) const
1202 {
1203         docstring res;
1204         if (numberedType()) {
1205                 if (label_[row] && numbered_[row]) {
1206                         docstring const name =
1207                                 latex ? escape(label_[row]->getParam("name"))
1208                                       : label_[row]->getParam("name");
1209                         res += "\\label{" + name + '}';
1210                 }
1211                 if (!numbered_[row] && (type_ != hullMultline))
1212                         res += "\\nonumber ";
1213         }
1214         // Never add \\ on the last empty line of eqnarray and friends
1215         last_eoln = false;
1216         return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1217 }
1218
1219
1220 void InsetMathHull::write(WriteStream & os) const
1221 {
1222         ModeSpecifier specifier(os, MATH_MODE);
1223         header_write(os);
1224         InsetMathGrid::write(os);
1225         footer_write(os);
1226 }
1227
1228
1229 void InsetMathHull::normalize(NormalStream & os) const
1230 {
1231         os << "[formula " << hullName(type_) << ' ';
1232         InsetMathGrid::normalize(os);
1233         os << "] ";
1234 }
1235
1236
1237 void InsetMathHull::infoize(odocstream & os) const
1238 {
1239         os << "Type: " << hullName(type_);
1240 }
1241
1242
1243 void InsetMathHull::check() const
1244 {
1245         LASSERT(numbered_.size() == nrows(), /**/);
1246         LASSERT(numbers_.size() == nrows(), /**/);
1247         LASSERT(label_.size() == nrows(), /**/);
1248 }
1249
1250
1251 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1252 {
1253         docstring dlang;
1254         docstring extra;
1255         idocstringstream iss(func.argument());
1256         iss >> dlang >> extra;
1257         if (extra.empty())
1258                 extra = from_ascii("noextra");
1259         string const lang = to_ascii(dlang);
1260
1261         // FIXME: temporarily disabled
1262         //if (cur.selection()) {
1263         //      MathData ar;
1264         //      selGet(cur.ar);
1265         //      lyxerr << "use selection: " << ar << endl;
1266         //      insert(pipeThroughExtern(lang, extra, ar));
1267         //      return;
1268         //}
1269
1270         // only inline, display or eqnarray math is allowed
1271         if (getType() > hullEqnArray) {
1272                 frontend::Alert::warning(_("Bad math environment"),
1273                                 _("Computation cannot be performed for AMS "
1274                                   "math environments.\nChange the math "
1275                                   "formula type and try again."));
1276                 return;
1277         }
1278
1279         MathData eq;
1280         eq.push_back(MathAtom(new InsetMathChar('=')));
1281
1282         // go to first item in line
1283         cur.idx() -= cur.idx() % ncols();
1284         cur.pos() = 0;
1285
1286         if (getType() == hullSimple) {
1287                 size_type pos = cur.cell().find_last(eq);
1288                 MathData ar;
1289                 if (cur.inMathed() && cur.selection()) {
1290                         asArray(grabAndEraseSelection(cur), ar);
1291                 } else if (pos == cur.cell().size()) {
1292                         ar = cur.cell();
1293                         lyxerr << "use whole cell: " << ar << endl;
1294                 } else {
1295                         ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1296                         lyxerr << "use partial cell form pos: " << pos << endl;
1297                 }
1298                 cur.cell().append(eq);
1299                 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1300                 cur.pos() = cur.lastpos();
1301                 return;
1302         }
1303
1304         if (getType() == hullEquation) {
1305                 lyxerr << "use equation inset" << endl;
1306                 mutate(hullEqnArray);
1307                 MathData & ar = cur.cell();
1308                 lyxerr << "use cell: " << ar << endl;
1309                 ++cur.idx();
1310                 cur.cell() = eq;
1311                 ++cur.idx();
1312                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1313                 // move to end of line
1314                 cur.pos() = cur.lastpos();
1315                 return;
1316         }
1317
1318         {
1319                 lyxerr << "use eqnarray" << endl;
1320                 cur.idx() += 2 - cur.idx() % ncols();
1321                 cur.pos() = 0;
1322                 MathData ar = cur.cell();
1323                 lyxerr << "use cell: " << ar << endl;
1324                 // FIXME: temporarily disabled
1325                 addRow(cur.row());
1326                 ++cur.idx();
1327                 ++cur.idx();
1328                 cur.cell() = eq;
1329                 ++cur.idx();
1330                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1331                 cur.pos() = cur.lastpos();
1332         }
1333 }
1334
1335
1336 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1337 {
1338         //lyxerr << "action: " << cmd.action() << endl;
1339         switch (cmd.action()) {
1340
1341         case LFUN_FINISHED_BACKWARD:
1342         case LFUN_FINISHED_FORWARD:
1343         case LFUN_FINISHED_RIGHT:
1344         case LFUN_FINISHED_LEFT:
1345                 //lyxerr << "action: " << cmd.action() << endl;
1346                 InsetMathGrid::doDispatch(cur, cmd);
1347                 cur.undispatched();
1348                 break;
1349
1350         case LFUN_BREAK_PARAGRAPH:
1351                 // just swallow this
1352                 break;
1353
1354         case LFUN_NEWLINE_INSERT:
1355                 // some magic for the common case
1356                 if (type_ == hullSimple || type_ == hullEquation) {
1357                         cur.recordUndoInset();
1358                         bool const align =
1359                                 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1360                         mutate(align ? hullAlign : hullEqnArray);
1361                         // mutate() may change labels and such.
1362                         cur.forceBufferUpdate();
1363                         cur.idx() = nrows() * ncols() - 1;
1364                         cur.pos() = cur.lastpos();
1365                 }
1366                 InsetMathGrid::doDispatch(cur, cmd);
1367                 break;
1368
1369         case LFUN_MATH_NUMBER_TOGGLE: {
1370                 //lyxerr << "toggling all numbers" << endl;
1371                 cur.recordUndoInset();
1372                 bool old = numberedType();
1373                 if (type_ == hullMultline)
1374                         numbered(nrows() - 1, !old);
1375                 else
1376                         for (row_type row = 0; row < nrows(); ++row)
1377                                 numbered(row, !old);
1378
1379                 cur.message(old ? _("No number") : _("Number"));
1380                 cur.forceBufferUpdate();
1381                 break;
1382         }
1383
1384         case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1385                 cur.recordUndoInset();
1386                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1387                 bool old = numbered(r);
1388                 cur.message(old ? _("No number") : _("Number"));
1389                 numbered(r, !old);
1390                 cur.forceBufferUpdate();
1391                 break;
1392         }
1393
1394         case LFUN_LABEL_INSERT: {
1395                 cur.recordUndoInset();
1396                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1397                 docstring old_label = label(r);
1398                 docstring const default_label = from_ascii("eq:");
1399                 if (old_label.empty())
1400                         old_label = default_label;
1401
1402                 InsetCommandParams p(LABEL_CODE);
1403                 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1404                 string const data = InsetCommand::params2string(p);
1405
1406                 if (cmd.argument().empty())
1407                         cur.bv().showDialog("label", data);
1408                 else {
1409                         FuncRequest fr(LFUN_INSET_INSERT, data);
1410                         dispatch(cur, fr);
1411                 }
1412                 break;
1413         }
1414
1415         case LFUN_LABEL_COPY_AS_REF: {
1416                 row_type row;
1417                 if (cmd.argument().empty() && &cur.inset() == this)
1418                         // if there is no argument and we're inside math, we retrieve
1419                         // the row number from the cursor position.
1420                         row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1421                 else {
1422                         // if there is an argument, find the corresponding label, else
1423                         // check whether there is at least one label.
1424                         for (row = 0; row != nrows(); ++row)
1425                                 if (numbered_[row] && label_[row]
1426                                           && (cmd.argument().empty() || label(row) == cmd.argument()))
1427                                         break;
1428                 }
1429
1430                 if (row == nrows())
1431                         break;
1432
1433                 InsetCommandParams p(REF_CODE, "ref");
1434                 p["reference"] = label(row);
1435                 cap::clearSelection();
1436                 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1437                 break;
1438         }
1439
1440         case LFUN_WORD_DELETE_FORWARD:
1441         case LFUN_CHAR_DELETE_FORWARD:
1442                 if (col(cur.idx()) + 1 == ncols()
1443                     && cur.pos() == cur.lastpos()
1444                     && !cur.selection()) {
1445                         if (!label(row(cur.idx())).empty()) {
1446                                 cur.recordUndoInset();
1447                                 label(row(cur.idx()), docstring());
1448                         } else if (numbered(row(cur.idx()))) {
1449                                 cur.recordUndoInset();
1450                                 numbered(row(cur.idx()), false);
1451                                 cur.forceBufferUpdate();
1452                         } else {
1453                                 InsetMathGrid::doDispatch(cur, cmd);
1454                                 return;
1455                         }
1456                 } else {
1457                         InsetMathGrid::doDispatch(cur, cmd);
1458                         return;
1459                 }
1460                 break;
1461
1462         case LFUN_INSET_INSERT: {
1463                 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1464                 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1465                 string const name = cmd.getArg(0);
1466                 if (name == "label") {
1467                         InsetCommandParams p(LABEL_CODE);
1468                         InsetCommand::string2params(to_utf8(cmd.argument()), p);
1469                         docstring str = p["name"];
1470                         cur.recordUndoInset();
1471                         row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1472                         str = trim(str);
1473                         if (!str.empty())
1474                                 numbered(r, true);
1475                         docstring old = label(r);
1476                         if (str != old) {
1477                                 if (label_[r])
1478                                         // The label will take care of the reference update.
1479                                         label(r, str);
1480                                 else {
1481                                         label(r, str);
1482                                         // Newly created inset so initialize it.
1483                                         label_[r]->initView();
1484                                 }
1485                         }
1486                         cur.forceBufferUpdate();
1487                         break;
1488                 }
1489                 InsetMathGrid::doDispatch(cur, cmd);
1490                 return;
1491         }
1492
1493         case LFUN_MATH_EXTERN:
1494                 cur.recordUndoInset();
1495                 doExtern(cur, cmd);
1496                 break;
1497
1498         case LFUN_MATH_MUTATE: {
1499                 cur.recordUndoInset();
1500                 row_type row = cur.row();
1501                 col_type col = cur.col();
1502                 mutate(hullType(cmd.argument()));
1503                 cur.idx() = row * ncols() + col;
1504                 if (cur.idx() > cur.lastidx()) {
1505                         cur.idx() = cur.lastidx();
1506                         cur.pos() = cur.lastpos();
1507                 }
1508                 if (cur.pos() > cur.lastpos())
1509                         cur.pos() = cur.lastpos();
1510
1511                 cur.forceBufferUpdate();
1512                 // FIXME: find some more clever handling of the selection,
1513                 // i.e. preserve it.
1514                 cur.clearSelection();
1515                 //cur.dispatched(FINISHED);
1516                 break;
1517         }
1518
1519         case LFUN_MATH_DISPLAY: {
1520                 cur.recordUndoInset();
1521                 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1522                 cur.idx() = 0;
1523                 cur.pos() = cur.lastpos();
1524                 //cur.dispatched(FINISHED);
1525                 break;
1526         }
1527
1528         default:
1529                 InsetMathGrid::doDispatch(cur, cmd);
1530                 break;
1531         }
1532 }
1533
1534
1535 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1536                 FuncStatus & status) const
1537 {
1538         switch (cmd.action()) {
1539         case LFUN_FINISHED_BACKWARD:
1540         case LFUN_FINISHED_FORWARD:
1541         case LFUN_FINISHED_RIGHT:
1542         case LFUN_FINISHED_LEFT:
1543         case LFUN_UP:
1544         case LFUN_DOWN:
1545         case LFUN_NEWLINE_INSERT:
1546         case LFUN_MATH_EXTERN:
1547                 // we handle these
1548                 status.setEnabled(true);
1549                 return true;
1550
1551         // we never allow this in math, and we want to bind enter
1552         // to another actions in command-alternatives
1553         case LFUN_BREAK_PARAGRAPH:
1554                 status.setEnabled(false);
1555                 return true;
1556         case LFUN_MATH_MUTATE: {
1557                 HullType const ht = hullType(cmd.argument());
1558                 status.setOnOff(type_ == ht);
1559                 status.setEnabled(true);
1560
1561                 if (ht != hullSimple) {
1562                         Cursor tmpcur = cur;
1563                         while (!tmpcur.empty()) {
1564                                 InsetCode code = tmpcur.inset().lyxCode();
1565                                 if (code == BOX_CODE) {
1566                                         return true;
1567                                 } else if (code == TABULAR_CODE) {
1568                                         FuncRequest tmpcmd(LFUN_MATH_DISPLAY);
1569                                         if (tmpcur.getStatus(tmpcmd, status) && !status.enabled())
1570                                                 return true;
1571                                 }
1572                                 tmpcur.pop_back();
1573                         }
1574                 }
1575                 return true;
1576         }
1577         case LFUN_MATH_DISPLAY: {
1578                 bool enable = true;
1579                 if (cur.depth() > 1) {
1580                         Inset const & in = cur[cur.depth()-2].inset();
1581                         if (in.lyxCode() == SCRIPT_CODE)
1582                                 enable = display() != Inline;
1583                 }
1584                 status.setEnabled(enable);
1585                 return true;
1586         }
1587
1588         case LFUN_MATH_NUMBER_TOGGLE:
1589                 // FIXME: what is the right test, this or the one of
1590                 // LABEL_INSERT?
1591                 status.setEnabled(display() != Inline);
1592                 status.setOnOff(numberedType());
1593                 return true;
1594
1595         case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1596                 // FIXME: what is the right test, this or the one of
1597                 // LABEL_INSERT?
1598                 bool const enable = (type_ == hullMultline)
1599                         ? (nrows() - 1 == cur.row())
1600                         : display() != Inline;
1601                 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1602                 status.setEnabled(enable);
1603                 status.setOnOff(enable && numbered(r));
1604                 return true;
1605         }
1606
1607         case LFUN_LABEL_INSERT:
1608                 status.setEnabled(type_ != hullSimple);
1609                 return true;
1610
1611         case LFUN_LABEL_COPY_AS_REF: {
1612                 bool enabled = false;
1613                 row_type row;
1614                 if (cmd.argument().empty() && &cur.inset() == this) {
1615                         // if there is no argument and we're inside math, we retrieve
1616                         // the row number from the cursor position.
1617                         row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1618                         enabled = numberedType() && label_[row] && numbered_[row];
1619                 } else {
1620                         // if there is an argument, find the corresponding label, else
1621                         // check whether there is at least one label.
1622                         for (row_type row = 0; row != nrows(); ++row) {
1623                                 if (numbered_[row] && label_[row] && 
1624                                         (cmd.argument().empty() || label(row) == cmd.argument())) {
1625                                                 enabled = true;
1626                                                 break;
1627                                 }
1628                         }
1629                 }
1630                 status.setEnabled(enabled);
1631                 return true;
1632         }
1633
1634         case LFUN_INSET_INSERT:
1635                 if (cmd.getArg(0) == "label") {
1636                         status.setEnabled(type_ != hullSimple);
1637                         return true;
1638                 }
1639                 return InsetMathGrid::getStatus(cur, cmd, status);
1640
1641         case LFUN_INSET_MODIFY: {
1642                 istringstream is(to_utf8(cmd.argument()));
1643                 string s;
1644                 is >> s;
1645                 if (s != "tabular")
1646                         return InsetMathGrid::getStatus(cur, cmd, status);
1647                 is >> s;
1648                 if (!rowChangeOK()
1649                     && (s == "append-row"
1650                         || s == "delete-row"
1651                         || s == "copy-row")) {
1652                         status.message(bformat(
1653                                 from_utf8(N_("Can't change number of rows in '%1$s'")),
1654                                 hullName(type_)));
1655                         status.setEnabled(false);
1656                         return true;
1657                 }
1658                 if (!colChangeOK()
1659                     && (s == "append-column"
1660                         || s == "delete-column"
1661                         || s == "copy-column")) {
1662                         status.message(bformat(
1663                                 from_utf8(N_("Can't change number of columns in '%1$s'")),
1664                                 hullName(type_)));
1665                         status.setEnabled(false);
1666                         return true;
1667                 }
1668                 if ((type_ == hullSimple
1669                   || type_ == hullEquation
1670                   || type_ == hullNone) &&
1671                     (s == "add-hline-above" || s == "add-hline-below")) {
1672                         status.message(bformat(
1673                                 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1674                                 hullName(type_)));
1675                         status.setEnabled(false);
1676                         return true;
1677                 }
1678                 if (s == "add-vline-left" || s == "add-vline-right") {
1679                         status.message(bformat(
1680                                 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1681                                 hullName(type_)));
1682                         status.setEnabled(false);
1683                         return true;
1684                 }
1685                 if (s == "valign-top" || s == "valign-middle"
1686                  || s == "valign-bottom" || s == "align-left"
1687                  || s == "align-center" || s == "align-right") {
1688                         status.setEnabled(false);
1689                         return true;
1690                 }
1691                 return InsetMathGrid::getStatus(cur, cmd, status);
1692         }
1693
1694         default:
1695                 return InsetMathGrid::getStatus(cur, cmd, status);
1696         }
1697
1698         // This cannot really happen, but inserted to shut-up gcc
1699         return InsetMathGrid::getStatus(cur, cmd, status);
1700 }
1701
1702
1703 /////////////////////////////////////////////////////////////////////
1704
1705
1706
1707 // simply scrap this function if you want
1708 void InsetMathHull::mutateToText()
1709 {
1710 #if 0
1711         // translate to latex
1712         ostringstream os;
1713         latex(os, false, false);
1714         string str = os.str();
1715
1716         // insert this text
1717         Text * lt = view_->cursor().innerText();
1718         string::const_iterator cit = str.begin();
1719         string::const_iterator end = str.end();
1720         for (; cit != end; ++cit)
1721                 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1722
1723         // remove ourselves
1724         //dispatch(LFUN_ESCAPE);
1725 #endif
1726 }
1727
1728
1729 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1730         docstring const & font)
1731 {
1732         // this whole function is a hack and won't work for incremental font
1733         // changes...
1734         cur.recordUndo();
1735         if (cur.inset().asInsetMath()->name() == font)
1736                 cur.handleFont(to_utf8(font));
1737         else {
1738                 cur.handleNest(createInsetMath(font, cur.buffer()));
1739                 cur.insert(arg);
1740         }
1741 }
1742
1743
1744 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1745 {
1746         cur.recordUndo();
1747         Font font;
1748         bool b;
1749         font.fromString(to_utf8(arg), b);
1750         if (font.fontInfo().color() != Color_inherit) {
1751                 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1752                 cur.handleNest(at, 0);
1753         }
1754 }
1755
1756
1757 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1758 {
1759         cur.push(*this);
1760         bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1761                 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1762         enter_front ? idxFirst(cur) : idxLast(cur);
1763         // The inset formula dimension is not necessarily the same as the
1764         // one of the instant preview image, so we have to indicate to the
1765         // BufferView that a metrics update is needed.
1766         cur.screenUpdateFlags(Update::Force);
1767 }
1768
1769
1770 void InsetMathHull::revealCodes(Cursor & cur) const
1771 {
1772         if (!cur.inMathed())
1773                 return;
1774         odocstringstream os;
1775         cur.info(os);
1776         cur.message(os.str());
1777 /*
1778         // write something to the minibuffer
1779         // translate to latex
1780         cur.markInsert(bv);
1781         ostringstream os;
1782         write(os);
1783         string str = os.str();
1784         cur.markErase(bv);
1785         string::size_type pos = 0;
1786         string res;
1787         for (string::iterator it = str.begin(); it != str.end(); ++it) {
1788                 if (*it == '\n')
1789                         res += ' ';
1790                 else if (*it == '\0') {
1791                         res += "  -X-  ";
1792                         pos = it - str.begin();
1793                 }
1794                 else
1795                         res += *it;
1796         }
1797         if (pos > 30)
1798                 res = res.substr(pos - 30);
1799         if (res.size() > 60)
1800                 res = res.substr(0, 60);
1801         cur.message(res);
1802 */
1803 }
1804
1805
1806 /////////////////////////////////////////////////////////////////////
1807
1808
1809 #if 0
1810 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1811                                      bool, bool)
1812 {
1813         // FIXME: completely broken
1814         static InsetMathHull * lastformula = 0;
1815         static CursorBase current = DocIterator(ibegin(nucleus()));
1816         static MathData ar;
1817         static string laststr;
1818
1819         if (lastformula != this || laststr != str) {
1820                 //lyxerr << "reset lastformula to " << this << endl;
1821                 lastformula = this;
1822                 laststr = str;
1823                 current = ibegin(nucleus());
1824                 ar.clear();
1825                 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1826         } else {
1827                 increment(current);
1828         }
1829         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1830
1831         for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1832                 CursorSlice & top = it.back();
1833                 MathData const & a = top.asInsetMath()->cell(top.idx_);
1834                 if (a.matchpart(ar, top.pos_)) {
1835                         bv->cursor().setSelection(it, ar.size());
1836                         current = it;
1837                         top.pos_ += ar.size();
1838                         bv->update();
1839                         return true;
1840                 }
1841         }
1842
1843         //lyxerr << "not found!" << endl;
1844         lastformula = 0;
1845         return false;
1846 }
1847 #endif
1848
1849
1850 void InsetMathHull::write(ostream & os) const
1851 {
1852         odocstringstream oss;
1853         WriteStream wi(oss, false, false, WriteStream::wsDefault);
1854         oss << "Formula ";
1855         write(wi);
1856         os << to_utf8(oss.str());
1857 }
1858
1859
1860 void InsetMathHull::read(Lexer & lex)
1861 {
1862         MathAtom at;
1863         mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1864         operator=(*at->asHullInset());
1865 }
1866
1867
1868 bool InsetMathHull::readQuiet(Lexer & lex)
1869 {
1870         MathAtom at;
1871         bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1872         if (success)
1873                 operator=(*at->asHullInset());
1874         return success;
1875 }
1876
1877
1878 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1879 {
1880         // disables ASCII-art for export of equations. See #2275.
1881         if (0 && display()) {
1882                 Dimension dim;
1883                 TextMetricsInfo mi;
1884                 metricsT(mi, dim);
1885                 TextPainter tpain(dim.width(), dim.height());
1886                 drawT(tpain, 0, dim.ascent());
1887                 tpain.show(os, 3);
1888                 // reset metrics cache to "real" values
1889                 //metrics();
1890                 return tpain.textheight();
1891         } else {
1892                 odocstringstream oss;
1893                 Encoding const * const enc = encodings.fromLyXName("utf8");
1894                 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1895                 // Fix Bug #6139
1896                 if (type_ == hullRegexp)
1897                         write(wi);
1898                 else
1899                         wi << cell(0);
1900                 docstring const str = oss.str();
1901                 os << str;
1902                 return str.size();
1903         }
1904 }
1905
1906
1907 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1908 {
1909         MathStream ms(os);
1910         int res = 0;
1911         docstring name;
1912         if (getType() == hullSimple)
1913                 name = from_ascii("inlineequation");
1914         else
1915                 name = from_ascii("informalequation");
1916
1917         docstring bname = name;
1918         if (!label(0).empty())
1919                 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1920
1921         ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1922
1923         odocstringstream ls;
1924         if (runparams.flavor == OutputParams::XML) {
1925                 ms << MTag("alt role='tex' ");
1926                 // Workaround for db2latex: db2latex always includes equations with
1927                 // \ensuremath{} or \begin{display}\end{display}
1928                 // so we strip LyX' math environment
1929                 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1930                 InsetMathGrid::write(wi);
1931                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
1932                 ms << ETag("alt");
1933                 ms << MTag("math");
1934                 ms << ETag("alt");
1935                 ms << MTag("math");
1936                 InsetMathGrid::mathmlize(ms);
1937                 ms << ETag("math");
1938         } else {
1939                 TexRow texrow;
1940                 texrow.reset();
1941                 otexstream ols(ls, texrow);
1942                 ms << MTag("alt role='tex'");
1943                 latex(ols, runparams);
1944                 res = texrow.rows();
1945                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
1946                 ms << ETag("alt");
1947         }
1948
1949         ms << from_ascii("<graphic fileref=\"eqn/");
1950         if (!label(0).empty())
1951                 ms << sgml::cleanID(buffer(), runparams, label(0));
1952         else
1953                 ms << sgml::uniqueID(from_ascii("anon"));
1954
1955         if (runparams.flavor == OutputParams::XML)
1956                 ms << from_ascii("\"/>");
1957         else
1958                 ms << from_ascii("\">");
1959
1960         ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1961
1962         return ms.line() + res;
1963 }
1964
1965
1966 bool InsetMathHull::haveNumbers() const
1967 {
1968         bool havenumbers = false;
1969         // inline formulas are never numbered (bug 7351 part 3)
1970         if (getType() == hullSimple)
1971                 return havenumbers;
1972         for (size_t i = 0; i != numbered_.size(); ++i) {
1973                 if (numbered_[i]) {
1974                         havenumbers = true;
1975                         break;
1976                 }
1977         }
1978         return havenumbers;
1979 }
1980
1981
1982 // FIXME XHTML
1983 // We need to do something about alignment here.
1984 //
1985 // This duplicates code from InsetMathGrid, but
1986 // we need access here to number information,
1987 // and we simply do not have that in InsetMathGrid.
1988 void InsetMathHull::htmlize(HtmlStream & os) const
1989 {
1990         bool const havenumbers = haveNumbers();
1991         bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
1992
1993         if (!havetable) {
1994                 os << cell(index(0, 0));
1995                 return;
1996         }
1997
1998         os << MTag("table", "class='mathtable'");
1999         for (row_type row = 0; row < nrows(); ++row) {
2000                 os << MTag("tr");
2001                 for (col_type col = 0; col < ncols(); ++col) {
2002                         os << MTag("td");
2003                         os << cell(index(row, col));
2004                         os << ETag("td");
2005                 }
2006                 if (havenumbers) {
2007                         os << MTag("td");
2008                         docstring const & num = numbers_[row];
2009                         if (!num.empty())
2010                                 os << '(' << num << ')';
2011                   os << ETag("td");
2012                 }
2013                 os << ETag("tr");
2014         }
2015         os << ETag("table");
2016 }
2017
2018
2019 // this duplicates code from InsetMathGrid, but
2020 // we need access here to number information,
2021 // and we simply do not have that in InsetMathGrid.
2022 void InsetMathHull::mathmlize(MathStream & os) const
2023 {
2024         bool const havenumbers = haveNumbers();
2025         bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2026
2027         if (havetable)
2028                 os << MTag("mtable");
2029         char const * const celltag = havetable ? "mtd" : "mrow";
2030         // FIXME There does not seem to be wide support at the moment
2031         // for mlabeledtr, so we have to use just mtr for now.
2032         // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2033         char const * const rowtag = "mtr";
2034         for (row_type row = 0; row < nrows(); ++row) {
2035                 if (havetable)
2036                         os << MTag(rowtag);
2037                 for (col_type col = 0; col < ncols(); ++col) {
2038                         os << MTag(celltag)
2039                            << cell(index(row, col))
2040                            << ETag(celltag);
2041                 }
2042                 // fleqn?
2043                 if (havenumbers) {
2044                         os << MTag("mtd");
2045                         docstring const & num = numbers_[row];
2046                         if (!num.empty())
2047                                 os << '(' << num << ')';
2048                   os << ETag("mtd");
2049                 }
2050                 if (havetable)
2051                         os << ETag(rowtag);
2052         }
2053         if (havetable)
2054                 os << ETag("mtable");
2055 }
2056
2057
2058 void InsetMathHull::mathAsLatex(WriteStream & os) const
2059 {
2060         MathEnsurer ensurer(os, false);
2061         bool havenumbers = haveNumbers();
2062         bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2063
2064         if (!havetable) {
2065                 os << cell(index(0, 0));
2066                 return;
2067         }
2068
2069         os << "<table class='mathtable'>";
2070         for (row_type row = 0; row < nrows(); ++row) {
2071                 os << "<tr>";
2072                 for (col_type col = 0; col < ncols(); ++col) {
2073                         os << "<td class='math'>";
2074                         os << cell(index(row, col));
2075                         os << "</td>";
2076                 }
2077                 if (havenumbers) {
2078                         os << "<td>";
2079                         docstring const & num = numbers_[row];
2080                         if (!num.empty())
2081                                 os << '(' << num << ')';
2082                   os << "</td>";
2083                 }
2084                 os << "</tr>";
2085         }
2086         os << "</table>";
2087 }
2088
2089
2090 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2091 {
2092         BufferParams::MathOutput const mathtype = 
2093                 buffer().params().html_math_output;
2094
2095         bool success = false;
2096
2097         // we output all the labels just at the beginning of the equation.
2098         // this should be fine.
2099         for (size_t i = 0; i != label_.size(); ++i) {
2100                 InsetLabel const * const il = label_[i];
2101                 if (!il)
2102                         continue;
2103                 il->xhtml(xs, op);
2104         }
2105
2106         // FIXME Eventually we would like to do this inset by inset.
2107         if (mathtype == BufferParams::MathML) {
2108                 odocstringstream os;
2109                 MathStream ms(os);
2110                 try {
2111                         mathmlize(ms);
2112                         success = true;
2113                 } catch (MathExportException const &) {}
2114                 if (success) {
2115                         if (getType() == hullSimple)
2116                                 xs << html::StartTag("math", 
2117                                                         "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2118                         else 
2119                                 xs << html::StartTag("math", 
2120                                       "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2121                         xs << XHTMLStream::ESCAPE_NONE
2122                                  << os.str()
2123                                  << html::EndTag("math");
2124                 }
2125         } else if (mathtype == BufferParams::HTML) {
2126                 odocstringstream os;
2127                 HtmlStream ms(os);
2128                 try {
2129                         htmlize(ms);
2130                         success = true;
2131                 } catch (MathExportException const &) {}
2132                 if (success) {
2133                         string const tag = (getType() == hullSimple) ? "span" : "div";
2134                         xs << html::StartTag(tag, "class='formula'", true)
2135                            << XHTMLStream::ESCAPE_NONE
2136                            << os.str()
2137                            << html::EndTag(tag);
2138                 }
2139         }
2140         
2141         // what we actually want is this:
2142         // if (
2143         //     ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML) 
2144         //       && !success)
2145         //     || mathtype == BufferParams::Images
2146         //    )
2147         // but what follows is equivalent, since we'll enter only if either (a) we 
2148         // tried and failed with MathML or HTML or (b) didn't try yet at all but
2149         // aren't doing LaTeX, in which case we are doing Images.
2150         if (!success && mathtype != BufferParams::LaTeX) {
2151                 graphics::PreviewImage const * pimage = 0;
2152                 if (!op.dryrun) {
2153                         loadPreview(docit_);
2154                         pimage = preview_->getPreviewImage(buffer());
2155                         // FIXME Do we always have png?
2156                 }
2157
2158                 if (pimage || op.dryrun) {
2159                         string const filename = pimage ? pimage->filename().onlyFileName()
2160                                                        : "previewimage.png";
2161                         if (pimage) {
2162                                 // if we are not in the master buffer, then we need to see that the
2163                                 // generated image is copied there; otherwise, preview fails.
2164                                 Buffer const * mbuf = buffer().masterBuffer();
2165                                 if (mbuf != &buffer()) {
2166                                         string mbtmp = mbuf->temppath();
2167                                         FileName const mbufimg(support::addName(mbtmp, filename));
2168                                         pimage->filename().copyTo(mbufimg);
2169                                 }
2170                                 // add the file to the list of files to be exported
2171                                 op.exportdata->addExternalFile("xhtml", pimage->filename());
2172                         }
2173
2174                         string const tag = (getType() == hullSimple) ? "span" : "div";
2175                         xs << html::CR()
2176                            << html::StartTag(tag)
2177                                  << html::CompTag("img", "src=\"" + filename + "\"")
2178                                  << html::EndTag(tag)
2179                                  << html::CR();
2180                         success = true;
2181                 }
2182         }
2183         
2184         // so we'll pass this test if we've failed everything else, or
2185         // if mathtype was LaTeX, since we won't have entered any of the
2186         // earlier branches
2187         if (!success /* || mathtype != BufferParams::LaTeX */) {
2188                 // Unfortunately, we cannot use latexString() because we do not want
2189                 // $...$ or whatever.
2190                 odocstringstream ls;
2191                 WriteStream wi(ls, false, true, WriteStream::wsPreview);
2192                 ModeSpecifier specifier(wi, MATH_MODE);
2193                 mathAsLatex(wi);
2194                 docstring const latex = ls.str();
2195                 
2196                 // class='math' allows for use of jsMath
2197                 // http://www.math.union.edu/~dpvc/jsMath/
2198                 // FIXME XHTML
2199                 // probably should allow for some kind of customization here
2200                 string const tag = (getType() == hullSimple) ? "span" : "div";
2201                 xs << html::StartTag(tag, "class='math'")
2202                    << latex 
2203                    << html::EndTag(tag)
2204                    << html::CR();
2205         }
2206         return docstring();
2207 }
2208
2209
2210 void InsetMathHull::toString(odocstream & os) const
2211 {
2212         plaintext(os, OutputParams(0));
2213 }
2214
2215
2216 void InsetMathHull::forToc(docstring & os, size_t) const
2217 {
2218         odocstringstream ods;
2219         plaintext(ods, OutputParams(0));
2220         os += ods.str();
2221 }
2222
2223
2224 docstring InsetMathHull::contextMenuName() const
2225 {
2226         return from_ascii("context-math");
2227 }
2228
2229
2230 void InsetMathHull::recordLocation(DocIterator const & di)
2231 {
2232         docit_ = di;
2233 }
2234
2235 } // namespace lyx