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