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