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