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