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