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