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