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