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