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