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