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