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