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