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