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