]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathHull.cpp
Cmake export tests: Added sublabel handling also to revertedTests
[lyx.git] / src / mathed / InsetMathHull.cpp
1 /**
2  * \file InsetMathHull.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetMathHull.h"
14
15 #include "InsetMathChar.h"
16 #include "InsetMathColor.h"
17 #include "InsetMathFrac.h"
18 #include "InsetMathGrid.h"
19 #include "InsetMathNest.h"
20 #include "InsetMathScript.h"
21 #include "MathExtern.h"
22 #include "MathFactory.h"
23 #include "MathStream.h"
24 #include "MathSupport.h"
25
26 #include "Buffer.h"
27 #include "BufferParams.h"
28 #include "BufferView.h"
29 #include "ColorSet.h"
30 #include "CutAndPaste.h"
31 #include "Encoding.h"
32 #include "Exporter.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "Language.h"
36 #include "LaTeXFeatures.h"
37 #include "LyXRC.h"
38 #include "MacroTable.h"
39 #include "MathMacro.h"
40 #include "MathMacroTemplate.h"
41 #include "output_xhtml.h"
42 #include "Paragraph.h"
43 #include "ParIterator.h"
44 #include "sgml.h"
45 #include "TextClass.h"
46 #include "TextPainter.h"
47 #include "TocBackend.h"
48
49 #include "insets/InsetLabel.h"
50 #include "insets/InsetRef.h"
51 #include "insets/RenderPreview.h"
52
53 #include "graphics/GraphicsImage.h"
54 #include "graphics/PreviewImage.h"
55 #include "graphics/PreviewLoader.h"
56
57 #include "frontends/alert.h"
58 #include "frontends/Painter.h"
59
60 #include "support/convert.h"
61 #include "support/lassert.h"
62 #include "support/debug.h"
63 #include "support/filetools.h"
64 #include "support/gettext.h"
65 #include "support/lstrings.h"
66
67 #include <sstream>
68
69 using namespace std;
70 using namespace lyx::support;
71
72 namespace lyx {
73
74 using cap::grabAndEraseSelection;
75 using cap::reduceSelectionToOneCell;
76
77 namespace {
78
79         int getCols(HullType type)
80         {
81                 switch (type) {
82                         case hullEqnArray:
83                                 return 3;
84                         case hullAlign:
85                         case hullFlAlign:
86                         case hullAlignAt:
87                         case hullXAlignAt:
88                         case hullXXAlignAt:
89                                 return 2;
90                         default:
91                                 return 1;
92                 }
93         }
94
95
96         // returns position of first relation operator in the array
97         // used for "intelligent splitting"
98         size_t firstRelOp(MathData const & ar)
99         {
100                 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
101                         if ((*it)->isRelOp())
102                                 return it - ar.begin();
103                 return ar.size();
104         }
105
106
107         char const * star(bool numbered)
108         {
109                 return numbered ? "" : "*";
110         }
111
112
113 } // end anon namespace
114
115
116 HullType hullType(docstring const & s)
117 {
118         if (s == "none")      return hullNone;
119         if (s == "simple")    return hullSimple;
120         if (s == "equation")  return hullEquation;
121         if (s == "eqnarray")  return hullEqnArray;
122         if (s == "align")     return hullAlign;
123         if (s == "alignat")   return hullAlignAt;
124         if (s == "xalignat")  return hullXAlignAt;
125         if (s == "xxalignat") return hullXXAlignAt;
126         if (s == "multline")  return hullMultline;
127         if (s == "gather")    return hullGather;
128         if (s == "flalign")   return hullFlAlign;
129         if (s == "regexp")    return hullRegexp;
130         lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
131         return HullType(-1);
132 }
133
134
135 docstring hullName(HullType type)
136 {
137         switch (type) {
138                 case hullNone:       return from_ascii("none");
139                 case hullSimple:     return from_ascii("simple");
140                 case hullEquation:   return from_ascii("equation");
141                 case hullEqnArray:   return from_ascii("eqnarray");
142                 case hullAlign:      return from_ascii("align");
143                 case hullAlignAt:    return from_ascii("alignat");
144                 case hullXAlignAt:   return from_ascii("xalignat");
145                 case hullXXAlignAt:  return from_ascii("xxalignat");
146                 case hullMultline:   return from_ascii("multline");
147                 case hullGather:     return from_ascii("gather");
148                 case hullFlAlign:    return from_ascii("flalign");
149                 case hullRegexp:     return from_ascii("regexp");
150                 default:
151                         lyxerr << "unknown hull type '" << type << "'" << endl;
152                         return from_ascii("none");
153         }
154 }
155
156 static InsetLabel * dummy_pointer = 0;
157
158 InsetMathHull::InsetMathHull(Buffer * buf)
159         : InsetMathGrid(buf, 1, 1), type_(hullNone), numbered_(1, NUMBER),
160           numbers_(1, empty_docstring()), label_(1, dummy_pointer),
161           preview_(new RenderPreview(this)), use_preview_(false)
162 {
163         //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
164         //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
165         //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
166         //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
167         buffer_ = buf;
168         initMath();
169         setDefaults();
170 }
171
172
173 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
174         : InsetMathGrid(buf, getCols(type), 1), type_(type), numbered_(1, NUMBER),
175           numbers_(1, empty_docstring()), label_(1, dummy_pointer),
176           preview_(new RenderPreview(this)), use_preview_(false)
177 {
178         buffer_ = buf;
179         initMath();
180         setDefaults();
181 }
182
183
184 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
185 {
186         operator=(other);
187 }
188
189
190 InsetMathHull::~InsetMathHull()
191 {
192         for (size_t i = 0; i < label_.size(); ++i)
193                 delete label_[i];
194 }
195
196
197 Inset * InsetMathHull::clone() const
198 {
199         return new InsetMathHull(*this);
200 }
201
202
203 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
204 {
205         if (this == &other)
206                 return *this;
207         InsetMathGrid::operator=(other);
208         type_  = other.type_;
209         numbered_ = other.numbered_;
210         numbers_ = other.numbers_;
211         buffer_ = other.buffer_;
212         for (size_t i = 0; i < label_.size(); ++i)
213                 delete label_[i];
214         label_ = other.label_;
215         for (size_t i = 0; i != label_.size(); ++i) {
216                 if (label_[i])
217                         label_[i] = new InsetLabel(*label_[i]);
218         }
219         preview_.reset(new RenderPreview(*other.preview_, this));
220
221         return *this;
222 }
223
224
225 void InsetMathHull::setBuffer(Buffer & buffer)
226 {
227         InsetMathGrid::setBuffer(buffer);
228
229         for (size_t i = 0; i != label_.size(); ++i) {
230                 if (label_[i])
231                         label_[i]->setBuffer(buffer);
232         }
233 }
234
235
236 // FIXME This should really be controlled by the TOC level, or
237 // something of the sort.
238 namespace {
239         const char * counters_to_save[] = {"section", "chapter"};
240         unsigned int const numcnts = sizeof(counters_to_save)/sizeof(char *);
241 }
242
243
244 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
245 {
246         if (!buffer_) {
247                 //FIXME: buffer_ should be set at creation for this inset! Problem is
248                 // This inset is created at too many places (see Parser::parse1() in
249                 // MathParser.cpp).
250                 return;
251         }
252
253         // if any of the equations are numbered, then we want to save the values
254         // of some of the counters.
255         if (haveNumbers()) {
256                 BufferParams const & bp = buffer_->params();
257                 string const & lang = it->getParLanguage(bp)->code();
258                 Counters & cnts =
259                         buffer_->masterBuffer()->params().documentClass().counters();
260
261                 // right now, we only need to do this at export time
262                 if (utype == OutputUpdate) {
263                         for (size_t i = 0; i < numcnts; ++i) {
264                                 docstring const cnt = from_ascii(counters_to_save[i]);
265                                 if (cnts.hasCounter(cnt))
266                                         counter_map[cnt] = cnts.value(cnt);
267                         }
268                 }
269
270                 // this has to be done separately
271                 docstring const eqstr = from_ascii("equation");
272                 if (cnts.hasCounter(eqstr)) {
273                         if (utype == OutputUpdate)
274                                 counter_map[eqstr] = cnts.value(eqstr);
275                         for (size_t i = 0; i != label_.size(); ++i) {
276                                 if (numbered(i)) {
277                                         cnts.step(eqstr, utype);
278                                         numbers_[i] = cnts.theCounter(eqstr, lang);
279                                 } else
280                                         numbers_[i] = empty_docstring();
281                         }
282                 }
283         }
284
285         // now the labels
286         for (size_t i = 0; i != label_.size(); ++i) {
287                 if (label_[i])
288                         label_[i]->updateBuffer(it, utype);
289         }
290         // pass down
291         InsetMathGrid::updateBuffer(it, utype);
292 }
293
294
295 void InsetMathHull::addToToc(DocIterator const & pit, bool output_active,
296                                                          UpdateType utype) const
297 {
298         if (!buffer_) {
299                 //FIXME: buffer_ should be set at creation for this inset! Problem is
300                 // This inset is created at too many places (see Parser::parse1() in
301                 // MathParser.cpp).
302                 return;
303         }
304
305         shared_ptr<Toc> toc = buffer().tocBackend().toc("equation");
306
307         for (row_type row = 0; row != nrows(); ++row) {
308                 if (!numbered(row))
309                         continue;
310                 if (label_[row])
311                         label_[row]->addToToc(pit, output_active, utype);
312                 toc->push_back(TocItem(pit, 0, nicelabel(row), output_active));
313         }
314 }
315
316
317 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
318 {
319         if (use_preview_) {
320                 edit(cur, true);
321                 return this;
322         }
323         return InsetMathNest::editXY(cur, x, y);
324 }
325
326
327 InsetMath::mode_type InsetMathHull::currentMode() const
328 {
329         if (type_ == hullNone)
330                 return UNDECIDED_MODE;
331         // definitely math mode ...
332         return MATH_MODE;
333 }
334
335
336 bool InsetMathHull::idxFirst(Cursor & cur) const
337 {
338         cur.idx() = 0;
339         cur.pos() = 0;
340         return true;
341 }
342
343
344 bool InsetMathHull::idxLast(Cursor & cur) const
345 {
346         cur.idx() = nargs() - 1;
347         cur.pos() = cur.lastpos();
348         return true;
349 }
350
351
352 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::rowChangeOK() const
1044 {
1045         return
1046                 type_ == hullEqnArray || type_ == hullAlign ||
1047                 type_ == hullFlAlign || type_ == hullAlignAt ||
1048                 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
1049                 type_ == hullGather || type_ == hullMultline;
1050 }
1051
1052
1053 bool InsetMathHull::colChangeOK() const
1054 {
1055         return
1056                 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
1057                 type_ == hullXAlignAt || type_ == hullXXAlignAt;
1058 }
1059
1060
1061 void InsetMathHull::addRow(row_type row)
1062 {
1063         if (!rowChangeOK())
1064                 return;
1065
1066         bool numbered = numberedType();
1067         // Move the number and raw pointer, do not call label() (bug 7511)
1068         InsetLabel * label = dummy_pointer;
1069         docstring number = empty_docstring();
1070         if (type_ == hullMultline) {
1071                 if (row + 1 == nrows())  {
1072                         numbered_[row] = NONUMBER;
1073                         swap(label, label_[row]);
1074                         swap(number, numbers_[row]);
1075                 } else
1076                         numbered = false;
1077         }
1078
1079         numbered_.insert(numbered_.begin() + row + 1, numbered ? NUMBER : NONUMBER);
1080         numbers_.insert(numbers_.begin() + row + 1, number);
1081         label_.insert(label_.begin() + row + 1, label);
1082         InsetMathGrid::addRow(row);
1083 }
1084
1085
1086 void InsetMathHull::swapRow(row_type row)
1087 {
1088         if (nrows() <= 1)
1089                 return;
1090         if (row + 1 == nrows())
1091                 --row;
1092         swap(numbered_[row], numbered_[row + 1]);
1093         swap(numbers_[row], numbers_[row + 1]);
1094         swap(label_[row], label_[row + 1]);
1095         InsetMathGrid::swapRow(row);
1096 }
1097
1098
1099 void InsetMathHull::delRow(row_type row)
1100 {
1101         if (nrows() <= 1 || !rowChangeOK())
1102                 return;
1103         if (row + 1 == nrows() && type_ == hullMultline) {
1104                 swap(numbered_[row - 1], numbered_[row]);
1105                 swap(numbers_[row - 1], numbers_[row]);
1106                 swap(label_[row - 1], label_[row]);
1107                 InsetMathGrid::delRow(row);
1108                 return;
1109         }
1110         InsetMathGrid::delRow(row);
1111         // The last dummy row has no number info nor a label.
1112         // Test nrows() + 1 because we have already erased the row.
1113         if (row == nrows() + 1)
1114                 row--;
1115         numbered_.erase(numbered_.begin() + row);
1116         numbers_.erase(numbers_.begin() + row);
1117         delete label_[row];
1118         label_.erase(label_.begin() + row);
1119 }
1120
1121
1122 void InsetMathHull::addCol(col_type col)
1123 {
1124         if (!colChangeOK())
1125                 return;
1126         InsetMathGrid::addCol(col);
1127 }
1128
1129
1130 void InsetMathHull::delCol(col_type col)
1131 {
1132         if (ncols() <= 1 || !colChangeOK())
1133                 return;
1134         InsetMathGrid::delCol(col);
1135 }
1136
1137
1138 docstring InsetMathHull::nicelabel(row_type row) const
1139 {
1140         if (!numbered(row))
1141                 return docstring();
1142         docstring const & val = numbers_[row];
1143         if (!label_[row])
1144                 return '(' + val + ')';
1145         return '(' + val + ',' + label_[row]->screenLabel() + ')';
1146 }
1147
1148
1149 void InsetMathHull::glueall(HullType type)
1150 {
1151         MathData ar;
1152         for (idx_type i = 0; i < nargs(); ++i)
1153                 ar.append(cell(i));
1154         InsetLabel * label = 0;
1155         if (type == hullEquation) {
1156                 // preserve first non-empty label
1157                 for (row_type row = 0; row < nrows(); ++row) {
1158                         if (label_[row]) {
1159                                 label = label_[row];
1160                                 label_[row] = 0;
1161                                 break;
1162                         }
1163                 }
1164         }
1165         *this = InsetMathHull(buffer_, hullSimple);
1166         label_[0] = label;
1167         cell(0) = ar;
1168         setDefaults();
1169 }
1170
1171
1172 void InsetMathHull::splitTo2Cols()
1173 {
1174         LASSERT(ncols() == 1, return);
1175         InsetMathGrid::addCol(1);
1176         for (row_type row = 0; row < nrows(); ++row) {
1177                 idx_type const i = 2 * row;
1178                 pos_type pos = firstRelOp(cell(i));
1179                 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
1180                 cell(i).erase(pos, cell(i).size());
1181         }
1182 }
1183
1184
1185 void InsetMathHull::splitTo3Cols()
1186 {
1187         LASSERT(ncols() < 3, return);
1188         if (ncols() < 2)
1189                 splitTo2Cols();
1190         InsetMathGrid::addCol(2);
1191         for (row_type row = 0; row < nrows(); ++row) {
1192                 idx_type const i = 3 * row + 1;
1193                 if (!cell(i).empty()) {
1194                         cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
1195                         cell(i).erase(1, cell(i).size());
1196                 }
1197         }
1198 }
1199
1200
1201 void InsetMathHull::changeCols(col_type cols)
1202 {
1203         if (ncols() == cols)
1204                 return;
1205         else if (ncols() < cols) {
1206                 // split columns
1207                 if (cols < 3)
1208                         splitTo2Cols();
1209                 else {
1210                         splitTo3Cols();
1211                         while (ncols() < cols)
1212                                 InsetMathGrid::addCol(ncols());
1213                 }
1214                 return;
1215         }
1216
1217         // combine columns
1218         for (row_type row = 0; row < nrows(); ++row) {
1219                 idx_type const i = row * ncols();
1220                 for (col_type col = cols; col < ncols(); ++col) {
1221                         cell(i + cols - 1).append(cell(i + col));
1222                 }
1223         }
1224         // delete columns
1225         while (ncols() > cols) {
1226                 InsetMathGrid::delCol(ncols() - 1);
1227         }
1228 }
1229
1230
1231 HullType InsetMathHull::getType() const
1232 {
1233         return type_;
1234 }
1235
1236
1237 void InsetMathHull::setType(HullType type)
1238 {
1239         type_ = type;
1240         setDefaults();
1241 }
1242
1243
1244 void InsetMathHull::mutate(HullType newtype)
1245 {
1246         //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
1247
1248         // we try to move along the chain
1249         // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
1250         //                                     ^                                     |
1251         //                                     +-------------------------------------+
1252         // we use eqnarray as intermediate type for mutations that are not
1253         // directly supported because it handles labels and numbering for
1254         // "down mutation".
1255
1256         if (newtype == type_) {
1257                 // done
1258         }
1259
1260         else if (newtype < hullNone) {
1261                 // unknown type
1262                 dump();
1263         }
1264
1265         else if (type_ == hullNone) {
1266                 setType(hullSimple);
1267                 numbered(0, false);
1268                 mutate(newtype);
1269         }
1270
1271         else if (type_ == hullSimple) {
1272                 if (newtype == hullNone) {
1273                         setType(hullNone);
1274                         numbered(0, false);
1275                 } else {
1276                         setType(hullEquation);
1277                         numbered(0, label_[0] ? true : false);
1278                         mutate(newtype);
1279                 }
1280         }
1281
1282         else if (type_ == hullEquation) {
1283                 if (newtype < type_) {
1284                         setType(hullSimple);
1285                         numbered(0, false);
1286                         mutate(newtype);
1287                 } else if (newtype == hullEqnArray) {
1288                         // split it "nicely" on the first relop
1289                         splitTo3Cols();
1290                         setType(hullEqnArray);
1291                 } else if (newtype == hullMultline || newtype == hullGather) {
1292                         setType(newtype);
1293                 } else {
1294                         // split it "nicely"
1295                         splitTo2Cols();
1296                         setType(hullAlign);
1297                         mutate(newtype);
1298                 }
1299         }
1300
1301         else if (type_ == hullEqnArray) {
1302                 if (newtype < type_) {
1303                         glueall(newtype);
1304                         mutate(newtype);
1305                 } else { // align & Co.
1306                         changeCols(2);
1307                         setType(hullAlign);
1308                         mutate(newtype);
1309                 }
1310         }
1311
1312         else if (type_ ==  hullAlign || type_ == hullAlignAt ||
1313                  type_ == hullXAlignAt || type_ == hullFlAlign) {
1314                 if (newtype < hullAlign) {
1315                         changeCols(3);
1316                         setType(hullEqnArray);
1317                         mutate(newtype);
1318                 } else if (newtype == hullGather || newtype == hullMultline) {
1319                         changeCols(1);
1320                         setType(newtype);
1321                 } else if (newtype ==   hullXXAlignAt) {
1322                         for (row_type row = 0; row < nrows(); ++row)
1323                                 numbered(row, false);
1324                         setType(newtype);
1325                 } else {
1326                         setType(newtype);
1327                 }
1328         }
1329
1330         else if (type_ == hullXXAlignAt) {
1331                 for (row_type row = 0; row < nrows(); ++row)
1332                         numbered(row, false);
1333                 if (newtype < hullAlign) {
1334                         changeCols(3);
1335                         setType(hullEqnArray);
1336                         mutate(newtype);
1337                 } else if (newtype == hullGather || newtype == hullMultline) {
1338                         changeCols(1);
1339                         setType(newtype);
1340                 } else {
1341                         setType(newtype);
1342                 }
1343         }
1344
1345         else if (type_ == hullMultline || type_ == hullGather) {
1346                 if (newtype == hullGather || newtype == hullMultline)
1347                         setType(newtype);
1348                 else if (newtype == hullAlign || newtype == hullFlAlign  ||
1349                          newtype == hullAlignAt || newtype == hullXAlignAt) {
1350                         splitTo2Cols();
1351                         setType(newtype);
1352                 } else if (newtype ==   hullXXAlignAt) {
1353                         splitTo2Cols();
1354                         for (row_type row = 0; row < nrows(); ++row)
1355                                 numbered(row, false);
1356                         setType(newtype);
1357                 } else {
1358                         splitTo3Cols();
1359                         setType(hullEqnArray);
1360                         mutate(newtype);
1361                 }
1362         }
1363
1364         else {
1365                 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1366                        << "' to '" << to_utf8(hullName(newtype))
1367                        << "' not implemented" << endl;
1368         }
1369 }
1370
1371
1372 docstring InsetMathHull::eolString(row_type row, bool fragile, bool latex,
1373                 bool last_eoln) const
1374 {
1375         docstring res;
1376         if (numberedType()) {
1377                 if (label_[row] && numbered(row)) {
1378                         docstring const name =
1379                                 latex ? escape(label_[row]->getParam("name"))
1380                                       : label_[row]->getParam("name");
1381                         res += "\\label{" + name + '}';
1382                 }
1383                 if (type_ != hullMultline) {
1384                         if (numbered_[row]  == NONUMBER)
1385                                 res += "\\nonumber ";
1386                         else if (numbered_[row]  == NOTAG)
1387                                 res += "\\notag ";
1388                 }
1389         }
1390         // Never add \\ on the last empty line of eqnarray and friends
1391         last_eoln = false;
1392         return res + InsetMathGrid::eolString(row, fragile, latex, last_eoln);
1393 }
1394
1395 void InsetMathHull::write(WriteStream & os) const
1396 {
1397         ModeSpecifier specifier(os, MATH_MODE);
1398         header_write(os);
1399         InsetMathGrid::write(os);
1400         footer_write(os);
1401 }
1402
1403
1404 void InsetMathHull::normalize(NormalStream & os) const
1405 {
1406         os << "[formula " << hullName(type_) << ' ';
1407         InsetMathGrid::normalize(os);
1408         os << "] ";
1409 }
1410
1411
1412 void InsetMathHull::infoize(odocstream & os) const
1413 {
1414         os << bformat(_("Type: %1$s"), hullName(type_));
1415 }
1416
1417
1418 void InsetMathHull::check() const
1419 {
1420         LATTEST(numbered_.size() == nrows());
1421         LATTEST(numbers_.size() == nrows());
1422         LATTEST(label_.size() == nrows());
1423 }
1424
1425
1426 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1427 {
1428         docstring dlang;
1429         docstring extra;
1430         idocstringstream iss(func.argument());
1431         iss >> dlang >> extra;
1432         if (extra.empty())
1433                 extra = from_ascii("noextra");
1434         string const lang = to_ascii(dlang);
1435
1436         // replace selection with result of computation
1437         if (reduceSelectionToOneCell(cur)) {
1438                 MathData ar;
1439                 asArray(grabAndEraseSelection(cur), ar);
1440                 lyxerr << "use selection: " << ar << endl;
1441                 cur.insert(pipeThroughExtern(lang, extra, ar));
1442                 return;
1443         }
1444
1445         // only inline, display or eqnarray math is allowed
1446         if (getType() > hullEqnArray) {
1447                 frontend::Alert::warning(_("Bad math environment"),
1448                                 _("Computation cannot be performed for AMS "
1449                                   "math environments.\nChange the math "
1450                                   "formula type and try again."));
1451                 return;
1452         }
1453
1454         MathData eq;
1455         eq.push_back(MathAtom(new InsetMathChar('=')));
1456
1457         // go to first item in line
1458         cur.idx() -= cur.idx() % ncols();
1459         cur.pos() = 0;
1460
1461         if (getType() == hullSimple) {
1462                 size_type pos = cur.cell().find_last(eq);
1463                 MathData ar;
1464                 if (pos == cur.cell().size()) {
1465                         ar = cur.cell();
1466                         lyxerr << "use whole cell: " << ar << endl;
1467                 } else {
1468                         ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1469                         lyxerr << "use partial cell form pos: " << pos << endl;
1470                 }
1471                 cur.cell().append(eq);
1472                 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1473                 cur.pos() = cur.lastpos();
1474                 return;
1475         }
1476
1477         if (getType() == hullEquation) {
1478                 lyxerr << "use equation inset" << endl;
1479                 mutate(hullEqnArray);
1480                 MathData & ar = cur.cell();
1481                 lyxerr << "use cell: " << ar << endl;
1482                 ++cur.idx();
1483                 cur.cell() = eq;
1484                 ++cur.idx();
1485                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1486                 // move to end of line
1487                 cur.pos() = cur.lastpos();
1488                 return;
1489         }
1490
1491         {
1492                 lyxerr << "use eqnarray" << endl;
1493                 cur.idx() += 2 - cur.idx() % ncols();
1494                 cur.pos() = 0;
1495                 MathData ar = cur.cell();
1496                 lyxerr << "use cell: " << ar << endl;
1497                 // FIXME: temporarily disabled
1498                 addRow(cur.row());
1499                 ++cur.idx();
1500                 ++cur.idx();
1501                 cur.cell() = eq;
1502                 ++cur.idx();
1503                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1504                 cur.pos() = cur.lastpos();
1505         }
1506 }
1507
1508
1509 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1510 {
1511         //lyxerr << "action: " << cmd.action() << endl;
1512         switch (cmd.action()) {
1513
1514         case LFUN_FINISHED_BACKWARD:
1515         case LFUN_FINISHED_FORWARD:
1516         case LFUN_FINISHED_RIGHT:
1517         case LFUN_FINISHED_LEFT:
1518                 //lyxerr << "action: " << cmd.action() << endl;
1519                 InsetMathGrid::doDispatch(cur, cmd);
1520                 break;
1521
1522         case LFUN_PARAGRAPH_BREAK:
1523                 // just swallow this
1524                 break;
1525
1526         case LFUN_NEWLINE_INSERT:
1527                 // some magic for the common case
1528                 if (type_ == hullSimple || type_ == hullEquation) {
1529                         cur.recordUndoInset();
1530                         bool const align =
1531                                 cur.bv().buffer().params().use_package("amsmath") == BufferParams::package_on;
1532                         mutate(align ? hullAlign : hullEqnArray);
1533                         // mutate() may change labels and such.
1534                         cur.forceBufferUpdate();
1535                         cur.idx() = nrows() * ncols() - 1;
1536                         cur.pos() = cur.lastpos();
1537                 }
1538                 InsetMathGrid::doDispatch(cur, cmd);
1539                 break;
1540
1541         case LFUN_MATH_NUMBER_TOGGLE: {
1542                 //lyxerr << "toggling all numbers" << endl;
1543                 cur.recordUndoInset();
1544                 bool old = numberedType();
1545                 if (type_ == hullMultline)
1546                         numbered(nrows() - 1, !old);
1547                 else
1548                         for (row_type row = 0; row < nrows(); ++row)
1549                                 numbered(row, !old);
1550
1551                 cur.message(old ? _("No number") : _("Number"));
1552                 cur.forceBufferUpdate();
1553                 break;
1554         }
1555
1556         case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1557                 cur.recordUndoInset();
1558                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1559                 bool old = numbered(r);
1560                 cur.message(old ? _("No number") : _("Number"));
1561                 numbered(r, !old);
1562                 cur.forceBufferUpdate();
1563                 break;
1564         }
1565
1566         case LFUN_LABEL_INSERT: {
1567                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1568                 docstring old_label = label(r);
1569                 docstring const default_label = from_ascii("eq:");
1570                 if (old_label.empty())
1571                         old_label = default_label;
1572
1573                 InsetCommandParams p(LABEL_CODE);
1574                 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1575                 string const data = InsetCommand::params2string(p);
1576
1577                 if (cmd.argument().empty())
1578                         cur.bv().showDialog("label", data);
1579                 else {
1580                         FuncRequest fr(LFUN_INSET_INSERT, data);
1581                         dispatch(cur, fr);
1582                 }
1583                 break;
1584         }
1585
1586         case LFUN_LABEL_COPY_AS_REFERENCE: {
1587                 row_type row;
1588                 if (cmd.argument().empty() && &cur.inset() == this)
1589                         // if there is no argument and we're inside math, we retrieve
1590                         // the row number from the cursor position.
1591                         row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1592                 else {
1593                         // if there is an argument, find the corresponding label, else
1594                         // check whether there is at least one label.
1595                         for (row = 0; row != nrows(); ++row)
1596                                 if (numbered(row) && label_[row]
1597                                           && (cmd.argument().empty() || label(row) == cmd.argument()))
1598                                         break;
1599                 }
1600
1601                 if (row == nrows())
1602                         break;
1603
1604                 InsetCommandParams p(REF_CODE, "ref");
1605                 p["reference"] = label(row);
1606                 cap::clearSelection();
1607                 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1608                 break;
1609         }
1610
1611         case LFUN_WORD_DELETE_FORWARD:
1612         case LFUN_CHAR_DELETE_FORWARD:
1613                 if (col(cur.idx()) + 1 == ncols()
1614                     && cur.pos() == cur.lastpos()
1615                     && !cur.selection()) {
1616                         if (!label(row(cur.idx())).empty()) {
1617                                 cur.recordUndoInset();
1618                                 label(row(cur.idx()), docstring());
1619                         } else if (numbered(row(cur.idx()))) {
1620                                 cur.recordUndoInset();
1621                                 numbered(row(cur.idx()), false);
1622                                 cur.forceBufferUpdate();
1623                         } else {
1624                                 InsetMathGrid::doDispatch(cur, cmd);
1625                                 return;
1626                         }
1627                 } else {
1628                         InsetMathGrid::doDispatch(cur, cmd);
1629                         return;
1630                 }
1631                 break;
1632
1633         case LFUN_INSET_INSERT: {
1634                 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1635                 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1636                 string const name = cmd.getArg(0);
1637                 if (name == "label") {
1638                         InsetCommandParams p(LABEL_CODE);
1639                         InsetCommand::string2params(to_utf8(cmd.argument()), p);
1640                         docstring str = p["name"];
1641                         cur.recordUndoInset();
1642                         row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1643                         str = trim(str);
1644                         if (!str.empty())
1645                                 numbered(r, true);
1646                         docstring old = label(r);
1647                         if (str != old) {
1648                                 if (label_[r])
1649                                         // The label will take care of the reference update.
1650                                         label(r, str);
1651                                 else {
1652                                         label(r, str);
1653                                         // Newly created inset so initialize it.
1654                                         label_[r]->initView();
1655                                 }
1656                         }
1657                         cur.forceBufferUpdate();
1658                         break;
1659                 }
1660                 InsetMathGrid::doDispatch(cur, cmd);
1661                 return;
1662         }
1663
1664         case LFUN_MATH_EXTERN:
1665                 cur.recordUndoInset();
1666                 doExtern(cur, cmd);
1667                 break;
1668
1669         case LFUN_MATH_MUTATE: {
1670                 cur.recordUndoInset();
1671                 row_type row = cur.row();
1672                 col_type col = cur.col();
1673                 mutate(hullType(cmd.argument()));
1674                 cur.idx() = row * ncols() + col;
1675                 if (cur.idx() > cur.lastidx()) {
1676                         cur.idx() = cur.lastidx();
1677                         cur.pos() = cur.lastpos();
1678                 }
1679                 if (cur.pos() > cur.lastpos())
1680                         cur.pos() = cur.lastpos();
1681
1682                 cur.forceBufferUpdate();
1683                 // FIXME: find some more clever handling of the selection,
1684                 // i.e. preserve it.
1685                 cur.clearSelection();
1686                 //cur.dispatched(FINISHED);
1687                 break;
1688         }
1689
1690         case LFUN_MATH_DISPLAY: {
1691                 cur.recordUndoInset();
1692                 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1693                 // if the cursor is in a cell that got merged, move it to
1694                 // start of the hull inset.
1695                 if (cur.idx() > 0) {
1696                         cur.idx() = 0;
1697                         cur.pos() = 0;
1698                 }
1699                 if (cur.pos() > cur.lastpos())
1700                         cur.pos() = cur.lastpos();
1701
1702                 break;
1703         }
1704
1705         default:
1706                 InsetMathGrid::doDispatch(cur, cmd);
1707                 break;
1708         }
1709 }
1710
1711
1712 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1713                 FuncStatus & status) const
1714 {
1715         switch (cmd.action()) {
1716         case LFUN_FINISHED_BACKWARD:
1717         case LFUN_FINISHED_FORWARD:
1718         case LFUN_FINISHED_RIGHT:
1719         case LFUN_FINISHED_LEFT:
1720         case LFUN_UP:
1721         case LFUN_DOWN:
1722         case LFUN_NEWLINE_INSERT:
1723         case LFUN_MATH_EXTERN:
1724                 // we handle these
1725                 status.setEnabled(true);
1726                 return true;
1727
1728         // we never allow this in math, and we want to bind enter
1729         // to another actions in command-alternatives
1730         case LFUN_PARAGRAPH_BREAK:
1731                 status.setEnabled(false);
1732                 return true;
1733         case LFUN_MATH_MUTATE: {
1734                 HullType const ht = hullType(cmd.argument());
1735                 status.setOnOff(type_ == ht);
1736                 status.setEnabled(true);
1737
1738                 if (ht != hullSimple) {
1739                         Cursor tmpcur = cur;
1740                         while (!tmpcur.empty()) {
1741                                 InsetCode code = tmpcur.inset().lyxCode();
1742                                 if (code == BOX_CODE) {
1743                                         return true;
1744                                 } else if (code == TABULAR_CODE) {
1745                                         FuncRequest tmpcmd(LFUN_MATH_DISPLAY);
1746                                         if (tmpcur.getStatus(tmpcmd, status) && !status.enabled())
1747                                                 return true;
1748                                 }
1749                                 tmpcur.pop_back();
1750                         }
1751                 }
1752                 return true;
1753         }
1754         case LFUN_MATH_DISPLAY: {
1755                 bool enable = true;
1756                 if (cur.depth() > 1) {
1757                         Inset const & in = cur[cur.depth()-2].inset();
1758                         if (in.lyxCode() == SCRIPT_CODE)
1759                                 enable = display() != Inline;
1760                 }
1761                 status.setEnabled(enable);
1762                 status.setOnOff(display() != Inline);
1763                 return true;
1764         }
1765
1766         case LFUN_MATH_NUMBER_TOGGLE:
1767                 // FIXME: what is the right test, this or the one of
1768                 // LABEL_INSERT?
1769                 status.setEnabled(display() != Inline);
1770                 status.setOnOff(numberedType());
1771                 return true;
1772
1773         case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1774                 // FIXME: what is the right test, this or the one of
1775                 // LABEL_INSERT?
1776                 bool const enable = (type_ == hullMultline)
1777                         ? (nrows() - 1 == cur.row())
1778                         : display() != Inline;
1779                 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1780                 status.setEnabled(enable);
1781                 status.setOnOff(enable && numbered(r));
1782                 return true;
1783         }
1784
1785         case LFUN_LABEL_INSERT:
1786                 status.setEnabled(type_ != hullSimple);
1787                 return true;
1788
1789         case LFUN_LABEL_COPY_AS_REFERENCE: {
1790                 bool enabled = false;
1791                 row_type row;
1792                 if (cmd.argument().empty() && &cur.inset() == this) {
1793                         // if there is no argument and we're inside math, we retrieve
1794                         // the row number from the cursor position.
1795                         row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1796                         enabled = numberedType() && label_[row] && numbered(row);
1797                 } else {
1798                         // if there is an argument, find the corresponding label, else
1799                         // check whether there is at least one label.
1800                         for (row_type row = 0; row != nrows(); ++row) {
1801                                 if (numbered(row) && label_[row] &&
1802                                         (cmd.argument().empty() || label(row) == cmd.argument())) {
1803                                                 enabled = true;
1804                                                 break;
1805                                 }
1806                         }
1807                 }
1808                 status.setEnabled(enabled);
1809                 return true;
1810         }
1811
1812         case LFUN_INSET_INSERT:
1813                 if (cmd.getArg(0) == "label") {
1814                         status.setEnabled(type_ != hullSimple);
1815                         return true;
1816                 }
1817                 return InsetMathGrid::getStatus(cur, cmd, status);
1818
1819         case LFUN_INSET_MODIFY: {
1820                 istringstream is(to_utf8(cmd.argument()));
1821                 string s;
1822                 is >> s;
1823                 if (s != "tabular")
1824                         return InsetMathGrid::getStatus(cur, cmd, status);
1825                 is >> s;
1826                 if (!rowChangeOK()
1827                     && (s == "append-row"
1828                         || s == "delete-row"
1829                         || s == "copy-row")) {
1830                         status.message(bformat(
1831                                 from_utf8(N_("Can't change number of rows in '%1$s'")),
1832                                 hullName(type_)));
1833                         status.setEnabled(false);
1834                         return true;
1835                 }
1836                 if (!colChangeOK()
1837                     && (s == "append-column"
1838                         || s == "delete-column"
1839                         || s == "copy-column")) {
1840                         status.message(bformat(
1841                                 from_utf8(N_("Can't change number of columns in '%1$s'")),
1842                                 hullName(type_)));
1843                         status.setEnabled(false);
1844                         return true;
1845                 }
1846                 if ((type_ == hullSimple
1847                   || type_ == hullEquation
1848                   || type_ == hullNone) &&
1849                     (s == "add-hline-above" || s == "add-hline-below")) {
1850                         status.message(bformat(
1851                                 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1852                                 hullName(type_)));
1853                         status.setEnabled(false);
1854                         return true;
1855                 }
1856                 if (s == "add-vline-left" || s == "add-vline-right") {
1857                         status.message(bformat(
1858                                 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1859                                 hullName(type_)));
1860                         status.setEnabled(false);
1861                         return true;
1862                 }
1863                 if (s == "valign-top" || s == "valign-middle"
1864                  || s == "valign-bottom" || s == "align-left"
1865                  || s == "align-center" || s == "align-right") {
1866                         status.setEnabled(false);
1867                         return true;
1868                 }
1869                 return InsetMathGrid::getStatus(cur, cmd, status);
1870         }
1871
1872         default:
1873                 return InsetMathGrid::getStatus(cur, cmd, status);
1874         }
1875
1876         // This cannot really happen, but inserted to shut-up gcc
1877         return InsetMathGrid::getStatus(cur, cmd, status);
1878 }
1879
1880
1881 /////////////////////////////////////////////////////////////////////
1882
1883
1884
1885 // simply scrap this function if you want
1886 void InsetMathHull::mutateToText()
1887 {
1888 #if 0
1889         // translate to latex
1890         ostringstream os;
1891         latex(os, false, false);
1892         string str = os.str();
1893
1894         // insert this text
1895         Text * lt = view_->cursor().innerText();
1896         string::const_iterator cit = str.begin();
1897         string::const_iterator end = str.end();
1898         for (; cit != end; ++cit)
1899                 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1900
1901         // remove ourselves
1902         //dispatch(LFUN_ESCAPE);
1903 #endif
1904 }
1905
1906
1907 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1908         docstring const & font)
1909 {
1910         // this whole function is a hack and won't work for incremental font
1911         // changes...
1912         cur.recordUndo();
1913         if (cur.inset().asInsetMath()->name() == font)
1914                 cur.handleFont(to_utf8(font));
1915         else {
1916                 cur.handleNest(createInsetMath(font, cur.buffer()));
1917                 cur.insert(arg);
1918         }
1919 }
1920
1921
1922 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1923 {
1924         cur.recordUndo();
1925         Font font;
1926         bool b;
1927         font.fromString(to_utf8(arg), b);
1928         if (font.fontInfo().color() != Color_inherit) {
1929                 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1930                 cur.handleNest(at, 0);
1931         }
1932 }
1933
1934
1935 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1936 {
1937         cur.push(*this);
1938         bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1939                 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1940         enter_front ? idxFirst(cur) : idxLast(cur);
1941         // The inset formula dimension is not necessarily the same as the
1942         // one of the instant preview image, so we have to indicate to the
1943         // BufferView that a metrics update is needed.
1944         cur.screenUpdateFlags(Update::Force);
1945 }
1946
1947
1948 void InsetMathHull::revealCodes(Cursor & cur) const
1949 {
1950         if (!cur.inMathed())
1951                 return;
1952         odocstringstream os;
1953         cur.info(os);
1954         cur.message(os.str());
1955 /*
1956         // write something to the minibuffer
1957         // translate to latex
1958         cur.markInsert(bv);
1959         ostringstream os;
1960         write(os);
1961         string str = os.str();
1962         cur.markErase(bv);
1963         string::size_type pos = 0;
1964         string res;
1965         for (string::iterator it = str.begin(); it != str.end(); ++it) {
1966                 if (*it == '\n')
1967                         res += ' ';
1968                 else if (*it == '\0') {
1969                         res += "  -X-  ";
1970                         pos = it - str.begin();
1971                 }
1972                 else
1973                         res += *it;
1974         }
1975         if (pos > 30)
1976                 res = res.substr(pos - 30);
1977         if (res.size() > 60)
1978                 res = res.substr(0, 60);
1979         cur.message(res);
1980 */
1981 }
1982
1983
1984 /////////////////////////////////////////////////////////////////////
1985
1986
1987 #if 0
1988 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1989                                      bool, bool)
1990 {
1991         // FIXME: completely broken
1992         static InsetMathHull * lastformula = 0;
1993         static CursorBase current = DocIterator(ibegin(nucleus()));
1994         static MathData ar;
1995         static string laststr;
1996
1997         if (lastformula != this || laststr != str) {
1998                 //lyxerr << "reset lastformula to " << this << endl;
1999                 lastformula = this;
2000                 laststr = str;
2001                 current = ibegin(nucleus());
2002                 ar.clear();
2003                 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
2004         } else {
2005                 increment(current);
2006         }
2007         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
2008
2009         for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
2010                 CursorSlice & top = it.back();
2011                 MathData const & a = top.asInsetMath()->cell(top.idx_);
2012                 if (a.matchpart(ar, top.pos_)) {
2013                         bv->cursor().setSelection(it, ar.size());
2014                         current = it;
2015                         top.pos_ += ar.size();
2016                         bv->update();
2017                         return true;
2018                 }
2019         }
2020
2021         //lyxerr << "not found!" << endl;
2022         lastformula = 0;
2023         return false;
2024 }
2025 #endif
2026
2027
2028 void InsetMathHull::write(ostream & os) const
2029 {
2030         odocstringstream oss;
2031         TexRow texrow(false);
2032         otexrowstream ots(oss,texrow);
2033         WriteStream wi(ots, false, false, WriteStream::wsDefault);
2034         oss << "Formula ";
2035         write(wi);
2036         os << to_utf8(oss.str());
2037 }
2038
2039
2040 void InsetMathHull::read(Lexer & lex)
2041 {
2042         MathAtom at;
2043         mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
2044         operator=(*at->asHullInset());
2045 }
2046
2047
2048 bool InsetMathHull::readQuiet(Lexer & lex)
2049 {
2050         MathAtom at;
2051         bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
2052         if (success)
2053                 operator=(*at->asHullInset());
2054         return success;
2055 }
2056
2057
2058 int InsetMathHull::plaintext(odocstringstream & os,
2059         OutputParams const & op, size_t max_length) const
2060 {
2061         // disables ASCII-art for export of equations. See #2275.
2062         if (0 && display()) {
2063                 Dimension dim;
2064                 TextMetricsInfo mi;
2065                 metricsT(mi, dim);
2066                 TextPainter tpain(dim.width(), dim.height());
2067                 drawT(tpain, 0, dim.ascent());
2068                 tpain.show(os, 3);
2069                 // reset metrics cache to "real" values
2070                 //metrics();
2071                 return tpain.textheight();
2072         }
2073
2074         odocstringstream oss;
2075         TexRow texrow(false);
2076         otexrowstream ots(oss,texrow);
2077         Encoding const * const enc = encodings.fromLyXName("utf8");
2078         WriteStream wi(ots, false, true, WriteStream::wsDefault, enc);
2079
2080         // Fix Bug #6139
2081         if (type_ == hullRegexp)
2082                 write(wi);
2083         else {
2084                 for (row_type r = 0; r < nrows(); ++r) {
2085                         for (col_type c = 0; c < ncols(); ++c)
2086                                 wi << (c == 0 ? "" : "\t") << cell(index(r, c));
2087                         // if it's for the TOC, we write just the first line
2088                         // and do not include the newline.
2089                         if (op.for_toc || op.for_tooltip || oss.str().size() >= max_length)
2090                                 break;
2091                         if (r < nrows() - 1)
2092                                 wi << "\n";
2093                 }
2094         }
2095         docstring const str = oss.str();
2096         os << str;
2097         return str.size();
2098 }
2099
2100
2101 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
2102 {
2103         MathStream ms(os);
2104         int res = 0;
2105         docstring name;
2106         if (getType() == hullSimple)
2107                 name = from_ascii("inlineequation");
2108         else
2109                 name = from_ascii("informalequation");
2110
2111         docstring bname = name;
2112         if (!label(0).empty())
2113                 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
2114
2115         ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
2116
2117         odocstringstream ls;
2118         TexRow texrow;
2119         otexstream ols(ls, texrow);
2120         if (runparams.flavor == OutputParams::XML) {
2121                 ms << MTag("alt role='tex' ");
2122                 // Workaround for db2latex: db2latex always includes equations with
2123                 // \ensuremath{} or \begin{display}\end{display}
2124                 // so we strip LyX' math environment
2125                 WriteStream wi(ols, false, false, WriteStream::wsDefault, runparams.encoding);
2126                 InsetMathGrid::write(wi);
2127                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
2128                 ms << ETag("alt");
2129                 ms << MTag("math");
2130                 ms << ETag("alt");
2131                 ms << MTag("math");
2132                 InsetMathGrid::mathmlize(ms);
2133                 ms << ETag("math");
2134         } else {
2135                 ms << MTag("alt role='tex'");
2136                 latex(ols, runparams);
2137                 res = texrow.rows();
2138                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
2139                 ms << ETag("alt");
2140         }
2141
2142         ms << from_ascii("<graphic fileref=\"eqn/");
2143         if (!label(0).empty())
2144                 ms << sgml::cleanID(buffer(), runparams, label(0));
2145         else
2146                 ms << sgml::uniqueID(from_ascii("anon"));
2147
2148         if (runparams.flavor == OutputParams::XML)
2149                 ms << from_ascii("\"/>");
2150         else
2151                 ms << from_ascii("\">");
2152
2153         ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
2154
2155         return ms.line() + res;
2156 }
2157
2158
2159 bool InsetMathHull::haveNumbers() const
2160 {
2161         bool havenumbers = false;
2162         // inline formulas are never numbered (bug 7351 part 3)
2163         if (getType() == hullSimple)
2164                 return havenumbers;
2165         for (size_t i = 0; i != numbered_.size(); ++i) {
2166                 if (numbered(i)) {
2167                         havenumbers = true;
2168                         break;
2169                 }
2170         }
2171         return havenumbers;
2172 }
2173
2174
2175 // FIXME XHTML
2176 // We need to do something about alignment here.
2177 //
2178 // This duplicates code from InsetMathGrid, but
2179 // we need access here to number information,
2180 // and we simply do not have that in InsetMathGrid.
2181 void InsetMathHull::htmlize(HtmlStream & os) const
2182 {
2183         bool const havenumbers = haveNumbers();
2184         bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2185
2186         if (!havetable) {
2187                 os << cell(index(0, 0));
2188                 return;
2189         }
2190
2191         os << MTag("table", "class='mathtable'");
2192         for (row_type row = 0; row < nrows(); ++row) {
2193                 os << MTag("tr");
2194                 for (col_type col = 0; col < ncols(); ++col) {
2195                         os << MTag("td");
2196                         os << cell(index(row, col));
2197                         os << ETag("td");
2198                 }
2199                 if (havenumbers) {
2200                         os << MTag("td");
2201                         docstring const & num = numbers_[row];
2202                         if (!num.empty())
2203                                 os << '(' << num << ')';
2204                   os << ETag("td");
2205                 }
2206                 os << ETag("tr");
2207         }
2208         os << ETag("table");
2209 }
2210
2211
2212 // this duplicates code from InsetMathGrid, but
2213 // we need access here to number information,
2214 // and we simply do not have that in InsetMathGrid.
2215 void InsetMathHull::mathmlize(MathStream & os) const
2216 {
2217         bool const havenumbers = haveNumbers();
2218         bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2219
2220         if (havetable)
2221                 os << MTag("mtable");
2222         char const * const celltag = havetable ? "mtd" : "mrow";
2223         // FIXME There does not seem to be wide support at the moment
2224         // for mlabeledtr, so we have to use just mtr for now.
2225         // char const * const rowtag = havenumbers ? "mlabeledtr" : "mtr";
2226         char const * const rowtag = "mtr";
2227         for (row_type row = 0; row < nrows(); ++row) {
2228                 if (havetable)
2229                         os << MTag(rowtag);
2230                 for (col_type col = 0; col < ncols(); ++col) {
2231                         os << MTag(celltag)
2232                            << cell(index(row, col))
2233                            << ETag(celltag);
2234                 }
2235                 // fleqn?
2236                 if (havenumbers) {
2237                         os << MTag("mtd");
2238                         docstring const & num = numbers_[row];
2239                         if (!num.empty())
2240                                 os << '(' << num << ')';
2241                   os << ETag("mtd");
2242                 }
2243                 if (havetable)
2244                         os << ETag(rowtag);
2245         }
2246         if (havetable)
2247                 os << ETag("mtable");
2248 }
2249
2250
2251 void InsetMathHull::mathAsLatex(WriteStream & os) const
2252 {
2253         MathEnsurer ensurer(os, false);
2254         bool havenumbers = haveNumbers();
2255         bool const havetable = havenumbers || nrows() > 1 || ncols() > 1;
2256
2257         if (!havetable) {
2258                 os << cell(index(0, 0));
2259                 return;
2260         }
2261
2262         os << "<table class='mathtable'>";
2263         for (row_type row = 0; row < nrows(); ++row) {
2264                 os << "<tr>";
2265                 for (col_type col = 0; col < ncols(); ++col) {
2266                         os << "<td class='math'>";
2267                         os << cell(index(row, col));
2268                         os << "</td>";
2269                 }
2270                 if (havenumbers) {
2271                         os << "<td>";
2272                         docstring const & num = numbers_[row];
2273                         if (!num.empty())
2274                                 os << '(' << num << ')';
2275                   os << "</td>";
2276                 }
2277                 os << "</tr>";
2278         }
2279         os << "</table>";
2280 }
2281
2282
2283 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const & op) const
2284 {
2285         BufferParams::MathOutput const mathtype =
2286                 buffer().masterBuffer()->params().html_math_output;
2287
2288         bool success = false;
2289
2290         // we output all the labels just at the beginning of the equation.
2291         // this should be fine.
2292         for (size_t i = 0; i != label_.size(); ++i) {
2293                 InsetLabel const * const il = label_[i];
2294                 if (!il)
2295                         continue;
2296                 il->xhtml(xs, op);
2297         }
2298
2299         // FIXME Eventually we would like to do this inset by inset.
2300         if (mathtype == BufferParams::MathML) {
2301                 odocstringstream os;
2302                 MathStream ms(os);
2303                 try {
2304                         mathmlize(ms);
2305                         success = true;
2306                 } catch (MathExportException const &) {}
2307                 if (success) {
2308                         if (getType() == hullSimple)
2309                                 xs << html::StartTag("math",
2310                                                         "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2311                         else
2312                                 xs << html::StartTag("math",
2313                                       "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
2314                         xs << XHTMLStream::ESCAPE_NONE
2315                                  << os.str()
2316                                  << html::EndTag("math");
2317                 }
2318         } else if (mathtype == BufferParams::HTML) {
2319                 odocstringstream os;
2320                 HtmlStream ms(os);
2321                 try {
2322                         htmlize(ms);
2323                         success = true;
2324                 } catch (MathExportException const &) {}
2325                 if (success) {
2326                         string const tag = (getType() == hullSimple) ? "span" : "div";
2327                         xs << html::StartTag(tag, "class='formula'", true)
2328                            << XHTMLStream::ESCAPE_NONE
2329                            << os.str()
2330                            << html::EndTag(tag);
2331                 }
2332         }
2333
2334         // what we actually want is this:
2335         // if (
2336         //     ((mathtype == BufferParams::MathML || mathtype == BufferParams::HTML)
2337         //       && !success)
2338         //     || mathtype == BufferParams::Images
2339         //    )
2340         // but what follows is equivalent, since we'll enter only if either (a) we
2341         // tried and failed with MathML or HTML or (b) didn't try yet at all but
2342         // aren't doing LaTeX, in which case we are doing Images.
2343         if (!success && mathtype != BufferParams::LaTeX) {
2344                 graphics::PreviewImage const * pimage = 0;
2345                 if (!op.dryrun) {
2346                         loadPreview(docit_);
2347                         pimage = preview_->getPreviewImage(buffer());
2348                         // FIXME Do we always have png?
2349                 }
2350
2351                 if (pimage || op.dryrun) {
2352                         string const filename = pimage ? pimage->filename().onlyFileName()
2353                                                        : "previewimage.png";
2354                         if (pimage) {
2355                                 // if we are not in the master buffer, then we need to see that the
2356                                 // generated image is copied there; otherwise, preview fails.
2357                                 Buffer const * mbuf = buffer().masterBuffer();
2358                                 if (mbuf != &buffer()) {
2359                                         string mbtmp = mbuf->temppath();
2360                                         FileName const mbufimg(support::addName(mbtmp, filename));
2361                                         pimage->filename().copyTo(mbufimg);
2362                                 }
2363                                 // add the file to the list of files to be exported
2364                                 op.exportdata->addExternalFile("xhtml", pimage->filename());
2365                         }
2366
2367                         string const tag = (getType() == hullSimple) ? "span" : "div";
2368                         xs << html::CR()
2369                            << html::StartTag(tag)
2370                                  << html::CompTag("img", "src=\"" + filename + "\" alt=\"Mathematical Equation\"")
2371                                  << html::EndTag(tag)
2372                                  << html::CR();
2373                         success = true;
2374                 }
2375         }
2376
2377         // so we'll pass this test if we've failed everything else, or
2378         // if mathtype was LaTeX, since we won't have entered any of the
2379         // earlier branches
2380         if (!success /* || mathtype != BufferParams::LaTeX */) {
2381                 // Unfortunately, we cannot use latexString() because we do not want
2382                 // $...$ or whatever.
2383                 odocstringstream ls;
2384                 TexRow texrow(false);
2385                 otexrowstream ots(ls,texrow);
2386                 WriteStream wi(ots, false, true, WriteStream::wsPreview);
2387                 ModeSpecifier specifier(wi, MATH_MODE);
2388                 mathAsLatex(wi);
2389                 docstring const latex = ls.str();
2390
2391                 // class='math' allows for use of jsMath
2392                 // http://www.math.union.edu/~dpvc/jsMath/
2393                 // FIXME XHTML
2394                 // probably should allow for some kind of customization here
2395                 string const tag = (getType() == hullSimple) ? "span" : "div";
2396                 xs << html::StartTag(tag, "class='math'")
2397                    << latex
2398                    << html::EndTag(tag)
2399                    << html::CR();
2400         }
2401         return docstring();
2402 }
2403
2404
2405 void InsetMathHull::toString(odocstream & os) const
2406 {
2407         odocstringstream ods;
2408         plaintext(ods, OutputParams(0));
2409         os << ods.str();
2410 }
2411
2412
2413 void InsetMathHull::forOutliner(docstring & os, size_t const, bool const) const
2414 {
2415         odocstringstream ods;
2416         OutputParams op(0);
2417         op.for_toc = true;
2418         // FIXME: this results in spilling TeX into the LyXHTML output since the
2419         // outliner is used to generate the LyXHTML list of figures/etc.
2420         plaintext(ods, op);
2421         os += ods.str();
2422 }
2423
2424
2425 string InsetMathHull::contextMenuName() const
2426 {
2427         return "context-math";
2428 }
2429
2430
2431 void InsetMathHull::recordLocation(DocIterator const & di)
2432 {
2433         docit_ = di;
2434 }
2435
2436 } // namespace lyx