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