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