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