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