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