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