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