]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathHull.cpp
The beginnings of pure HTML output of math, for our internal XHTML
[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 "FuncRequest.h"
29 #include "FuncStatus.h"
30 #include "LaTeXFeatures.h"
31 #include "LyXRC.h"
32 #include "MacroTable.h"
33 #include "output_xhtml.h"
34 #include "sgml.h"
35 #include "TextPainter.h"
36 #include "TocBackend.h"
37
38 #include "insets/InsetLabel.h"
39 #include "insets/InsetRef.h"
40 #include "insets/RenderPreview.h"
41
42 #include "graphics/PreviewImage.h"
43 #include "graphics/PreviewLoader.h"
44
45 #include "frontends/Painter.h"
46
47 #include "support/lassert.h"
48 #include "support/debug.h"
49 #include "support/gettext.h"
50 #include "support/lstrings.h"
51
52 #include <sstream>
53
54 using namespace std;
55 using namespace lyx::support;
56
57 namespace lyx {
58
59 using cap::grabAndEraseSelection;
60
61 namespace {
62
63         int getCols(HullType type)
64         {
65                 switch (type) {
66                         case hullEqnArray:
67                                 return 3;
68                         case hullAlign:
69                         case hullFlAlign:
70                         case hullAlignAt:
71                         case hullXAlignAt:
72                         case hullXXAlignAt:
73                                 return 2;
74                         default:
75                                 return 1;
76                 }
77         }
78
79
80         // returns position of first relation operator in the array
81         // used for "intelligent splitting"
82         size_t firstRelOp(MathData const & ar)
83         {
84                 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
85                         if ((*it)->isRelOp())
86                                 return it - ar.begin();
87                 return ar.size();
88         }
89
90
91         char const * star(bool numbered)
92         {
93                 return numbered ? "" : "*";
94         }
95
96
97 } // end anon namespace
98
99
100 HullType hullType(docstring const & s)
101 {
102         if (s == "none")      return hullNone;
103         if (s == "simple")    return hullSimple;
104         if (s == "equation")  return hullEquation;
105         if (s == "eqnarray")  return hullEqnArray;
106         if (s == "align")     return hullAlign;
107         if (s == "alignat")   return hullAlignAt;
108         if (s == "xalignat")  return hullXAlignAt;
109         if (s == "xxalignat") return hullXXAlignAt;
110         if (s == "multline")  return hullMultline;
111         if (s == "gather")    return hullGather;
112         if (s == "flalign")   return hullFlAlign;
113         if (s == "regexp")    return hullRegexp;
114         lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
115         return HullType(-1);
116 }
117
118
119 docstring hullName(HullType type)
120 {
121         switch (type) {
122                 case hullNone:       return from_ascii("none");
123                 case hullSimple:     return from_ascii("simple");
124                 case hullEquation:   return from_ascii("equation");
125                 case hullEqnArray:   return from_ascii("eqnarray");
126                 case hullAlign:      return from_ascii("align");
127                 case hullAlignAt:    return from_ascii("alignat");
128                 case hullXAlignAt:   return from_ascii("xalignat");
129                 case hullXXAlignAt:  return from_ascii("xxalignat");
130                 case hullMultline:   return from_ascii("multline");
131                 case hullGather:     return from_ascii("gather");
132                 case hullFlAlign:    return from_ascii("flalign");
133                 case hullRegexp:     return from_ascii("regexp");
134                 default:
135                         lyxerr << "unknown hull type '" << type << "'" << endl;
136                         return from_ascii("none");
137         }
138 }
139
140 static InsetLabel * dummy_pointer = 0;
141
142 InsetMathHull::InsetMathHull(Buffer * buf)
143         : InsetMathGrid(buf, 1, 1), type_(hullNone), nonum_(1, false),
144           label_(1, dummy_pointer), preview_(new RenderPreview(this))
145 {
146         //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
147         //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
148         //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
149         //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
150         buffer_ = buf;
151         initMath();
152         setDefaults();
153 }
154
155
156 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
157         : InsetMathGrid(buf, getCols(type), 1), type_(type), nonum_(1, false),
158           label_(1, dummy_pointer), preview_(new RenderPreview(this))
159 {
160         buffer_ = buf;
161         initMath();
162         setDefaults();
163 }
164
165
166 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
167 {
168         operator=(other);
169 }
170
171
172 InsetMathHull::~InsetMathHull()
173 {
174         for (size_t i = 0; i < label_.size(); ++i)
175                 delete label_[i];
176 }
177
178
179 Inset * InsetMathHull::clone() const
180 {
181         return new InsetMathHull(*this);
182 }
183
184
185 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
186 {
187         if (this == &other)
188                 return *this;
189         InsetMathGrid::operator=(other);
190         type_  = other.type_;
191         nonum_ = other.nonum_;
192         buffer_ = other.buffer_;
193         for (size_t i = 0; i < label_.size(); ++i)
194                 delete label_[i];
195         label_ = other.label_;
196         for (size_t i = 0; i != label_.size(); ++i) {
197                 if (label_[i])
198                         label_[i] = new InsetLabel(*label_[i]);
199         }
200         preview_.reset(new RenderPreview(*other.preview_, this));
201
202         return *this;
203 }
204
205
206 void InsetMathHull::setBuffer(Buffer & buffer)
207 {
208         InsetMathGrid::setBuffer(buffer);
209
210         for (size_t i = 0; i != label_.size(); ++i) {
211                 if (label_[i])
212                         label_[i]->setBuffer(buffer);
213         }
214 }
215
216
217 void InsetMathHull::updateBuffer(ParIterator const & it, UpdateType utype)
218 {
219         if (!buffer_) {
220                 //FIXME: buffer_ should be set at creation for this inset! Problem is
221                 // This inset is created at too many places (see Parser::parse1() in
222                 // MathParser.cpp).
223                 return;
224         }
225         for (size_t i = 0; i != label_.size(); ++i) {
226                 if (label_[i])
227                         label_[i]->updateBuffer(it, utype);
228         }
229         // pass down
230         InsetMathGrid::updateBuffer(it, utype);
231 }
232
233
234 void InsetMathHull::addToToc(DocIterator const & pit)
235 {
236         if (!buffer_) {
237                 //FIXME: buffer_ should be set at creation for this inset! Problem is
238                 // This inset is created at too many places (see Parser::parse1() in
239                 // MathParser.cpp).
240                 return;
241         }
242
243         Toc & toc = buffer().tocBackend().toc("equation");
244
245         for (row_type row = 0; row != nrows(); ++row) {
246                 if (nonum_[row])
247                         continue;
248                 if (label_[row])
249                         label_[row]->addToToc(pit);
250                 toc.push_back(TocItem(pit, 0, nicelabel(row)));
251         }
252 }
253
254
255 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
256 {
257         if (use_preview_) {
258                 edit(cur, true);
259                 return this;
260         }
261         return InsetMathNest::editXY(cur, x, y);
262 }
263
264
265 InsetMath::mode_type InsetMathHull::currentMode() const
266 {
267         if (type_ == hullNone)
268                 return UNDECIDED_MODE;
269         // definitely math mode ...
270         return MATH_MODE;
271 }
272
273
274 bool InsetMathHull::idxFirst(Cursor & cur) const
275 {
276         cur.idx() = 0;
277         cur.pos() = 0;
278         return true;
279 }
280
281
282 bool InsetMathHull::idxLast(Cursor & cur) const
283 {
284         cur.idx() = nargs() - 1;
285         cur.pos() = cur.lastpos();
286         return true;
287 }
288
289
290 char InsetMathHull::defaultColAlign(col_type col)
291 {
292         if (type_ == hullEqnArray)
293                 return "rcl"[col];
294         if (type_ == hullGather)
295                 return 'c';
296         if (type_ >= hullAlign)
297                 return "rl"[col & 1];
298         return 'c';
299 }
300
301
302 int InsetMathHull::defaultColSpace(col_type col)
303 {
304         if (type_ == hullAlign || type_ == hullAlignAt)
305                 return 0;
306         if (type_ == hullXAlignAt)
307                 return (col & 1) ? 20 : 0;
308         if (type_ == hullXXAlignAt || type_ == hullFlAlign)
309                 return (col & 1) ? 40 : 0;
310         return 0;
311 }
312
313
314 docstring InsetMathHull::standardFont() const
315 {
316         docstring font_name;
317         switch (type_) {
318         case hullRegexp:
319                 font_name = from_ascii("texttt");
320                 break;
321         case hullNone:
322                 font_name = from_ascii("lyxnochange");
323                 break;
324         default:
325                 font_name = from_ascii("mathnormal");
326         }
327         return font_name;
328 }
329
330
331 bool InsetMathHull::previewState(BufferView * bv) const
332 {
333         if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
334                 graphics::PreviewImage const * pimage =
335                         preview_->getPreviewImage(bv->buffer());
336                 return pimage && pimage->image();
337         }
338         return false;
339 }
340
341
342 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
343 {
344         if (previewState(mi.base.bv)) {
345                 preview_->metrics(mi, dim);
346                 // insert a one pixel gap in front of the formula
347                 dim.wid += 1;
348                 if (display())
349                         dim.des += displayMargin();
350                 // Cache the inset dimension.
351                 setDimCache(mi, dim);
352                 return;
353         }
354
355         FontSetChanger dummy1(mi.base, standardFont());
356         StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
357
358         // let the cells adjust themselves
359         InsetMathGrid::metrics(mi, dim);
360
361         if (display()) {
362                 dim.asc += displayMargin();
363                 dim.des += displayMargin();
364         }
365
366         if (numberedType()) {
367                 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
368                 int l = 0;
369                 for (row_type row = 0; row < nrows(); ++row)
370                         l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
371
372                 if (l)
373                         dim.wid += 30 + l;
374         }
375
376         // make it at least as high as the current font
377         int asc = 0;
378         int des = 0;
379         math_font_max_dim(mi.base.font, asc, des);
380         dim.asc = max(dim.asc, asc);
381         dim.des = max(dim.des, des);
382         // Cache the inset dimension.
383         // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
384         setDimCache(mi, dim);
385 }
386
387
388 ColorCode InsetMathHull::backgroundColor(PainterInfo const & pi) const
389 {
390         if (previewState(pi.base.bv))
391                 return graphics::PreviewLoader::backgroundColor();
392         return Color_mathbg;
393 }
394
395
396 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
397 {
398         Dimension const dim = dimension(*pi.base.bv);
399         pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
400                 dim.asc + dim.des - 1, pi.backgroundColor(this));
401 }
402
403
404 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
405 {
406         use_preview_ = previewState(pi.base.bv);
407
408         if (type_ == hullRegexp) {
409                 Dimension const dim = dimension(*pi.base.bv);
410                 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
411                         dim.width() - 2, dim.height() - 2, Color_regexpframe);
412         }
413         if (use_preview_) {
414                 // one pixel gap in front
415                 preview_->draw(pi, x + 1, y);
416                 setPosCache(pi, x, y);
417                 return;
418         }
419
420         FontSetChanger dummy1(pi.base, standardFont());
421         StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
422         InsetMathGrid::draw(pi, x + 1, y);
423
424         if (numberedType()) {
425                 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
426                 for (row_type row = 0; row < nrows(); ++row) {
427                         int const yy = y + rowinfo_[row].offset_;
428                         FontSetChanger dummy(pi.base, from_ascii("mathrm"));
429                         docstring const nl = nicelabel(row);
430                         pi.draw(xx, yy, nl);
431                 }
432         }
433         setPosCache(pi, x, y);
434 }
435
436
437 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
438 {
439         if (display()) {
440                 InsetMathGrid::metricsT(mi, dim);
441         } else {
442                 odocstringstream os;
443                 WriteStream wi(os, false, true, WriteStream::wsDefault);
444                 write(wi);
445                 dim.wid = os.str().size();
446                 dim.asc = 1;
447                 dim.des = 0;
448         }
449 }
450
451
452 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
453 {
454         if (display()) {
455                 InsetMathGrid::drawT(pain, x, y);
456         } else {
457                 odocstringstream os;
458                 WriteStream wi(os, false, true, WriteStream::wsDefault);
459                 write(wi);
460                 pain.draw(x, y, os.str().c_str());
461         }
462 }
463
464
465 static docstring latexString(InsetMathHull const & inset)
466 {
467         odocstringstream ls;
468         // This has to be static, because a preview snippet or a math
469         // macro containing math in text mode (such as $\text{$\phi$}$ or
470         // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
471         // first time as a whole, and the second time only the inner math.
472         // In this last case inset.buffer() would be invalid.
473         static Encoding const * encoding = 0;
474         if (inset.isBufferValid())
475                 encoding = &(inset.buffer().params().encoding());
476         WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
477         inset.write(wi);
478         return ls.str();
479 }
480
481
482 void InsetMathHull::initUnicodeMath() const
483 {
484         // Trigger classification of the unicode symbols in this inset
485         docstring const dummy = latexString(*this);
486 }
487
488
489 void InsetMathHull::addPreview(DocIterator const & inset_pos,
490         graphics::PreviewLoader & /*ploader*/) const
491 {
492         if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
493                 preparePreview(inset_pos);
494         }
495 }
496
497
498 void InsetMathHull::preparePreview(DocIterator const & pos) const  
499 {
500         Buffer const * buffer = pos.buffer();  
501
502         // collect macros at this position  
503         MacroNameSet macros;  
504         buffer->listMacroNames(macros);  
505         MacroNameSet::iterator it = macros.begin();  
506         MacroNameSet::iterator end = macros.end();  
507         odocstringstream macro_preamble;  
508         for (; it != end; ++it) {  
509                 MacroData const * data = buffer->getMacro(*it, pos, true);  
510                 if (data) {  
511                         data->write(macro_preamble, true);  
512                         macro_preamble << endl;  
513                 }
514         }  
515
516         docstring const snippet = macro_preamble.str() + latexString(*this);  
517         LYXERR(Debug::MACROS, "Preview snippet: " << snippet);  
518         preview_->addPreview(snippet, *buffer);  
519 }
520
521
522 void InsetMathHull::reloadPreview(DocIterator const & pos) const
523 {
524         preparePreview(pos);
525         preview_->startLoading(*pos.buffer());
526 }
527
528
529 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
530 {
531         if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
532                 reloadPreview(old);
533                 cur.updateFlags(Update::Force);
534         }
535         return false;
536 }
537
538
539 docstring InsetMathHull::label(row_type row) const
540 {
541         LASSERT(row < nrows(), /**/);
542         if (InsetLabel * il = label_[row])
543                 return il->screenLabel();
544         return docstring();
545 }
546
547
548 void InsetMathHull::label(row_type row, docstring const & label)
549 {
550         //lyxerr << "setting label '" << label << "' for row " << row << endl;
551         if (label_[row]) {
552                 if (label.empty()) {
553                         delete label_[row];
554                         label_[row] = dummy_pointer;
555                         // We need an update of the Buffer reference cache.
556                         // This is achieved by updateBuffer().
557                         if (buffer_)
558                                 buffer().updateBuffer();
559                 } else {
560                         if (buffer_)
561                                 label_[row]->updateCommand(label);
562                         else
563                                 label_[row]->setParam("name", label);
564                 }
565                 return;
566         }
567         InsetCommandParams p(LABEL_CODE);
568         p["name"] = label;
569         label_[row] = new InsetLabel(buffer_, p);
570         if (buffer_)
571                 label_[row]->setBuffer(buffer());
572 }
573
574
575 void InsetMathHull::numbered(row_type row, bool num)
576 {
577         nonum_[row] = !num;
578         if (nonum_[row] && label_[row]) {
579                 delete label_[row];
580                 label_[row] = 0;
581                 if (!buffer_) {
582                         // The buffer is set at the end of readInset.
583                         // When parsing the inset, buffer_ is 0.
584                         return;
585                 }
586                 // We need an update of the Buffer reference cache.
587                 // This is achieved by updateBuffer().
588                 buffer().updateBuffer();
589         }
590 }
591
592
593 bool InsetMathHull::numbered(row_type row) const
594 {
595         return !nonum_[row];
596 }
597
598
599 bool InsetMathHull::ams() const
600 {
601         return type_ == hullAlign
602                 || type_ == hullFlAlign
603                 || type_ == hullMultline
604                 || type_ == hullGather
605                 || type_ == hullAlignAt
606                 || type_ == hullXAlignAt
607                 || type_ == hullXXAlignAt;
608 }
609
610
611 Inset::DisplayType InsetMathHull::display() const
612 {
613         if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
614                 return Inline;
615         return AlignCenter;
616 }
617
618 bool InsetMathHull::numberedType() const
619 {
620         if (type_ == hullNone)
621                 return false;
622         if (type_ == hullSimple)
623                 return false;
624         if (type_ == hullXXAlignAt)
625                 return false;
626         if (type_ == hullRegexp)
627                 return false;
628         for (row_type row = 0; row < nrows(); ++row)
629                 if (!nonum_[row])
630                         return true;
631         return false;
632 }
633
634
635 void InsetMathHull::validate(LaTeXFeatures & features) const
636 {
637         if (ams())
638                 features.require("amsmath");
639
640         if (type_ == hullRegexp) {
641                 features.require("color");
642                 string frcol = lcolor.getLaTeXName(Color_regexpframe);
643                 string bgcol = "white";
644                 features.addPreambleSnippet(
645                         string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
646                         + frcol + string("}{")
647                         + bgcol + string("}{\\texttt{#1}}}"));
648         }
649
650         // Validation is necessary only if not using AMS math.
651         // To be safe, we will always run mathedvalidate.
652         //if (features.amsstyle)
653         //  return;
654
655         //features.binom      = true;
656
657         InsetMathGrid::validate(features);
658 }
659
660
661 void InsetMathHull::header_write(WriteStream & os) const
662 {
663         bool n = numberedType();
664
665         switch(type_) {
666         case hullNone:
667                 break;
668
669         case hullSimple:
670                 os << '$';
671                 if (cell(0).empty())
672                         os << ' ';
673                 break;
674
675         case hullEquation:
676                 if (n)
677                         os << "\\begin{equation" << star(n) << "}\n";
678                 else
679                         os << "\\[\n";
680                 break;
681
682         case hullEqnArray:
683         case hullAlign:
684         case hullFlAlign:
685         case hullGather:
686         case hullMultline:
687                 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
688                 break;
689
690         case hullAlignAt:
691         case hullXAlignAt:
692                 os << "\\begin{" << hullName(type_) << star(n) << '}'
693                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
694                 break;
695
696         case hullXXAlignAt:
697                 os << "\\begin{" << hullName(type_) << '}'
698                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
699                 break;
700
701         case hullRegexp:
702                 os << "\\regexp{{{";
703                 break;
704
705         default:
706                 os << "\\begin{unknown" << star(n) << '}';
707                 break;
708         }
709 }
710
711
712 void InsetMathHull::footer_write(WriteStream & os) const
713 {
714         bool n = numberedType();
715
716         switch(type_) {
717         case hullNone:
718                 os << "\n";
719                 break;
720
721         case hullSimple:
722                 os << '$';
723                 break;
724
725         case hullEquation:
726                 if (n)
727                         os << "\\end{equation" << star(n) << "}\n";
728                 else
729                         os << "\\]\n";
730                 break;
731
732         case hullEqnArray:
733         case hullAlign:
734         case hullFlAlign:
735         case hullAlignAt:
736         case hullXAlignAt:
737         case hullGather:
738         case hullMultline:
739                 os << "\\end{" << hullName(type_) << star(n) << "}\n";
740                 break;
741
742         case hullXXAlignAt:
743                 os << "\\end{" << hullName(type_) << "}\n";
744                 break;
745
746         case hullRegexp:
747                 os << "}}}";
748                 break;
749
750         default:
751                 os << "\\end{unknown" << star(n) << '}';
752                 break;
753         }
754 }
755
756
757 bool InsetMathHull::rowChangeOK() const
758 {
759         return
760                 type_ == hullEqnArray || type_ == hullAlign ||
761                 type_ == hullFlAlign || type_ == hullAlignAt ||
762                 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
763                 type_ == hullGather || type_ == hullMultline;
764 }
765
766
767 bool InsetMathHull::colChangeOK() const
768 {
769         return
770                 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
771                 type_ == hullXAlignAt || type_ == hullXXAlignAt;
772 }
773
774
775 void InsetMathHull::addRow(row_type row)
776 {
777         if (!rowChangeOK())
778                 return;
779
780         bool numbered = numberedType();
781         docstring lab;
782         if (type_ == hullMultline) {
783                 if (row + 1 == nrows())  {
784                         nonum_[row] = true;
785                         lab = label(row);
786                 } else
787                         numbered = false;
788         }
789
790         nonum_.insert(nonum_.begin() + row + 1, !numbered);
791         label_.insert(label_.begin() + row + 1, dummy_pointer);
792         if (!lab.empty())
793                 label(row + 1, lab);
794         InsetMathGrid::addRow(row);
795 }
796
797
798 void InsetMathHull::swapRow(row_type row)
799 {
800         if (nrows() <= 1)
801                 return;
802         if (row + 1 == nrows())
803                 --row;
804         // gcc implements the standard std::vector<bool> which is *not* a container:
805         //   http://www.gotw.ca/publications/N1185.pdf
806         // As a results, it doesn't like this:
807         //      swap(nonum_[row], nonum_[row + 1]);
808         // so we do it manually:
809         bool const b = nonum_[row];
810         nonum_[row] = nonum_[row + 1];
811         nonum_[row + 1] = b;
812         swap(label_[row], label_[row + 1]);
813         InsetMathGrid::swapRow(row);
814 }
815
816
817 void InsetMathHull::delRow(row_type row)
818 {
819         if (nrows() <= 1 || !rowChangeOK())
820                 return;
821         if (row + 1 == nrows() && type_ == hullMultline) {
822                 bool const b = nonum_[row - 1];
823                 nonum_[row - 1] = nonum_[row];
824                 nonum_[row] = b;
825                 swap(label_[row - 1], label_[row]);
826                 InsetMathGrid::delRow(row);
827                 return;
828         }
829         InsetMathGrid::delRow(row);
830         // The last dummy row has no number info nor a label.
831         // Test nrows() + 1 because we have already erased the row.
832         if (row == nrows() + 1)
833                 row--;
834         nonum_.erase(nonum_.begin() + row);
835         delete label_[row];
836         label_.erase(label_.begin() + row);
837 }
838
839
840 void InsetMathHull::addCol(col_type col)
841 {
842         if (!colChangeOK())
843                 return;
844         InsetMathGrid::addCol(col);
845 }
846
847
848 void InsetMathHull::delCol(col_type col)
849 {
850         if (ncols() <= 1 || !colChangeOK())
851                 return;
852         InsetMathGrid::delCol(col);
853 }
854
855
856 docstring InsetMathHull::nicelabel(row_type row) const
857 {
858         if (nonum_[row])
859                 return docstring();
860         if (!label_[row])
861                 return from_ascii("(#)");
862         return '(' + label_[row]->screenLabel() + from_ascii(", #)");
863 }
864
865
866 void InsetMathHull::glueall()
867 {
868         MathData ar;
869         for (idx_type i = 0; i < nargs(); ++i)
870                 ar.append(cell(i));
871         *this = InsetMathHull(buffer_, hullSimple);
872         cell(0) = ar;
873         setDefaults();
874 }
875
876
877 void InsetMathHull::splitTo2Cols()
878 {
879         LASSERT(ncols() == 1, /**/);
880         InsetMathGrid::addCol(1);
881         for (row_type row = 0; row < nrows(); ++row) {
882                 idx_type const i = 2 * row;
883                 pos_type pos = firstRelOp(cell(i));
884                 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
885                 cell(i).erase(pos, cell(i).size());
886         }
887 }
888
889
890 void InsetMathHull::splitTo3Cols()
891 {
892         LASSERT(ncols() < 3, /**/);
893         if (ncols() < 2)
894                 splitTo2Cols();
895         InsetMathGrid::addCol(2);
896         for (row_type row = 0; row < nrows(); ++row) {
897                 idx_type const i = 3 * row + 1;
898                 if (cell(i).size()) {
899                         cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
900                         cell(i).erase(1, cell(i).size());
901                 }
902         }
903 }
904
905
906 void InsetMathHull::changeCols(col_type cols)
907 {
908         if (ncols() == cols)
909                 return;
910         else if (ncols() < cols) {
911                 // split columns
912                 if (cols < 3)
913                         splitTo2Cols();
914                 else {
915                         splitTo3Cols();
916                         while (ncols() < cols)
917                                 InsetMathGrid::addCol(ncols());
918                 }
919                 return;
920         }
921
922         // combine columns
923         for (row_type row = 0; row < nrows(); ++row) {
924                 idx_type const i = row * ncols();
925                 for (col_type col = cols; col < ncols(); ++col) {
926                         cell(i + cols - 1).append(cell(i + col));
927                 }
928         }
929         // delete columns
930         while (ncols() > cols) {
931                 InsetMathGrid::delCol(ncols() - 1);
932         }
933 }
934
935
936 HullType InsetMathHull::getType() const
937 {
938         return type_;
939 }
940
941
942 void InsetMathHull::setType(HullType type)
943 {
944         type_ = type;
945         setDefaults();
946 }
947
948
949 void InsetMathHull::mutate(HullType newtype)
950 {
951         //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
952
953         // we try to move along the chain
954         // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
955         //                                     ^                                     |
956         //                                     +-------------------------------------+
957         // we use eqnarray as intermediate type for mutations that are not
958         // directly supported because it handles labels and numbering for
959         // "down mutation".
960
961         if (newtype == type_) {
962                 // done
963         }
964
965         else if (newtype < hullNone) {
966                 // unknown type
967                 dump();
968         }
969
970         else if (type_ == hullNone) {
971                 setType(hullSimple);
972                 numbered(0, false);
973                 mutate(newtype);
974         }
975
976         else if (type_ == hullSimple) {
977                 if (newtype == hullNone) {
978                         setType(hullNone);
979                         numbered(0, false);
980                 } else {
981                         setType(hullEquation);
982                         numbered(0, false);
983                         mutate(newtype);
984                 }
985         }
986
987         else if (type_ == hullEquation) {
988                 if (newtype < type_) {
989                         setType(hullSimple);
990                         numbered(0, false);
991                         mutate(newtype);
992                 } else if (newtype == hullEqnArray) {
993                         // split it "nicely" on the first relop
994                         splitTo3Cols();
995                         setType(hullEqnArray);
996                 } else if (newtype == hullMultline || newtype == hullGather) {
997                         setType(newtype);
998                 } else {
999                         // split it "nicely"
1000                         splitTo2Cols();
1001                         setType(hullAlign);
1002                         mutate(newtype);
1003                 }
1004         }
1005
1006         else if (type_ == hullEqnArray) {
1007                 if (newtype < type_) {
1008                         // set correct (no)numbering
1009                         nonum_[0] = true;
1010                         for (row_type row = 0; row < nrows(); ++row) {
1011                                 if (!nonum_[row]) {
1012                                         nonum_[0] = false;
1013                                         break;
1014                                 }
1015                         }
1016
1017                         // set first non-empty label
1018                         for (row_type row = 0; row < nrows(); ++row) {
1019                                 if (label_[row]) {
1020                                         label_[0] = label_[row];
1021                                         break;
1022                                 }
1023                         }
1024
1025                         glueall();
1026                         mutate(newtype);
1027                 } else { // align & Co.
1028                         changeCols(2);
1029                         setType(hullAlign);
1030                         mutate(newtype);
1031                 }
1032         }
1033
1034         else if (type_ ==  hullAlign || type_ == hullAlignAt ||
1035                  type_ == hullXAlignAt || type_ == hullFlAlign) {
1036                 if (newtype < hullAlign) {
1037                         changeCols(3);
1038                         setType(hullEqnArray);
1039                         mutate(newtype);
1040                 } else if (newtype == hullGather || newtype == hullMultline) {
1041                         changeCols(1);
1042                         setType(newtype);
1043                 } else if (newtype ==   hullXXAlignAt) {
1044                         for (row_type row = 0; row < nrows(); ++row)
1045                                 numbered(row, false);
1046                         setType(newtype);
1047                 } else {
1048                         setType(newtype);
1049                 }
1050         }
1051
1052         else if (type_ == hullXXAlignAt) {
1053                 for (row_type row = 0; row < nrows(); ++row)
1054                         numbered(row, false);
1055                 if (newtype < hullAlign) {
1056                         changeCols(3);
1057                         setType(hullEqnArray);
1058                         mutate(newtype);
1059                 } else if (newtype == hullGather || newtype == hullMultline) {
1060                         changeCols(1);
1061                         setType(newtype);
1062                 } else {
1063                         setType(newtype);
1064                 }
1065         }
1066
1067         else if (type_ == hullMultline || type_ == hullGather) {
1068                 if (newtype == hullGather || newtype == hullMultline)
1069                         setType(newtype);
1070                 else if (newtype == hullAlign || newtype == hullFlAlign  ||
1071                          newtype == hullAlignAt || newtype == hullXAlignAt) {
1072                         splitTo2Cols();
1073                         setType(newtype);
1074                 } else if (newtype ==   hullXXAlignAt) {
1075                         splitTo2Cols();
1076                         for (row_type row = 0; row < nrows(); ++row)
1077                                 numbered(row, false);
1078                         setType(newtype);
1079                 } else {
1080                         splitTo3Cols();
1081                         setType(hullEqnArray);
1082                         mutate(newtype);
1083                 }
1084         }
1085
1086         else {
1087                 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1088                        << "' to '" << to_utf8(hullName(newtype))
1089                        << "' not implemented" << endl;
1090         }
1091 }
1092
1093
1094 docstring InsetMathHull::eolString(row_type row, bool fragile) const
1095 {
1096         docstring res;
1097         if (numberedType()) {
1098                 if (label_[row] && !nonum_[row])
1099                         res += "\\label{" +
1100                             escape(label_[row]->getParam("name")) + '}';
1101                 if (nonum_[row] && (type_ != hullMultline))
1102                         res += "\\nonumber ";
1103         }
1104         return res + InsetMathGrid::eolString(row, fragile);
1105 }
1106
1107
1108 void InsetMathHull::write(WriteStream & os) const
1109 {
1110         ModeSpecifier specifier(os, MATH_MODE);
1111         header_write(os);
1112         InsetMathGrid::write(os);
1113         footer_write(os);
1114 }
1115
1116
1117 void InsetMathHull::normalize(NormalStream & os) const
1118 {
1119         os << "[formula " << hullName(type_) << ' ';
1120         InsetMathGrid::normalize(os);
1121         os << "] ";
1122 }
1123
1124
1125 void InsetMathHull::mathmlize(MathStream & os) const
1126 {
1127         InsetMathGrid::mathmlize(os);
1128 }
1129
1130
1131 void InsetMathHull::infoize(odocstream & os) const
1132 {
1133         os << "Type: " << hullName(type_);
1134 }
1135
1136
1137 void InsetMathHull::check() const
1138 {
1139         LASSERT(nonum_.size() == nrows(), /**/);
1140         LASSERT(label_.size() == nrows(), /**/);
1141 }
1142
1143
1144 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1145 {
1146         docstring dlang;
1147         docstring extra;
1148         idocstringstream iss(func.argument());
1149         iss >> dlang >> extra;
1150         if (extra.empty())
1151                 extra = from_ascii("noextra");
1152         string const lang = to_ascii(dlang);
1153
1154         // FIXME: temporarily disabled
1155         //if (cur.selection()) {
1156         //      MathData ar;
1157         //      selGet(cur.ar);
1158         //      lyxerr << "use selection: " << ar << endl;
1159         //      insert(pipeThroughExtern(lang, extra, ar));
1160         //      return;
1161         //}
1162
1163         MathData eq;
1164         eq.push_back(MathAtom(new InsetMathChar('=')));
1165
1166         // go to first item in line
1167         cur.idx() -= cur.idx() % ncols();
1168         cur.pos() = 0;
1169
1170         if (getType() == hullSimple) {
1171                 size_type pos = cur.cell().find_last(eq);
1172                 MathData ar;
1173                 if (cur.inMathed() && cur.selection()) {
1174                         asArray(grabAndEraseSelection(cur), ar);
1175                 } else if (pos == cur.cell().size()) {
1176                         ar = cur.cell();
1177                         lyxerr << "use whole cell: " << ar << endl;
1178                 } else {
1179                         ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1180                         lyxerr << "use partial cell form pos: " << pos << endl;
1181                 }
1182                 cur.cell().append(eq);
1183                 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1184                 cur.pos() = cur.lastpos();
1185                 return;
1186         }
1187
1188         if (getType() == hullEquation) {
1189                 lyxerr << "use equation inset" << endl;
1190                 mutate(hullEqnArray);
1191                 MathData & ar = cur.cell();
1192                 lyxerr << "use cell: " << ar << endl;
1193                 ++cur.idx();
1194                 cur.cell() = eq;
1195                 ++cur.idx();
1196                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1197                 // move to end of line
1198                 cur.pos() = cur.lastpos();
1199                 return;
1200         }
1201
1202         {
1203                 lyxerr << "use eqnarray" << endl;
1204                 cur.idx() += 2 - cur.idx() % ncols();
1205                 cur.pos() = 0;
1206                 MathData ar = cur.cell();
1207                 lyxerr << "use cell: " << ar << endl;
1208                 // FIXME: temporarily disabled
1209                 addRow(cur.row());
1210                 ++cur.idx();
1211                 ++cur.idx();
1212                 cur.cell() = eq;
1213                 ++cur.idx();
1214                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1215                 cur.pos() = cur.lastpos();
1216         }
1217 }
1218
1219
1220 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1221 {
1222         //lyxerr << "action: " << cmd.action << endl;
1223         switch (cmd.action) {
1224
1225         case LFUN_FINISHED_BACKWARD:
1226         case LFUN_FINISHED_FORWARD:
1227         case LFUN_FINISHED_RIGHT:
1228         case LFUN_FINISHED_LEFT:
1229                 //lyxerr << "action: " << cmd.action << endl;
1230                 InsetMathGrid::doDispatch(cur, cmd);
1231                 cur.undispatched();
1232                 break;
1233
1234         case LFUN_BREAK_PARAGRAPH:
1235                 // just swallow this
1236                 break;
1237
1238         case LFUN_NEWLINE_INSERT:
1239                 // some magic for the common case
1240                 if (type_ == hullSimple || type_ == hullEquation) {
1241                         cur.recordUndoInset();
1242                         bool const align =
1243                                 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1244                         mutate(align ? hullAlign : hullEqnArray);
1245                         cur.idx() = nrows() * ncols() - 1;
1246                         cur.pos() = cur.lastpos();
1247                 }
1248                 InsetMathGrid::doDispatch(cur, cmd);
1249                 break;
1250
1251         case LFUN_MATH_NUMBER_TOGGLE: {
1252                 //lyxerr << "toggling all numbers" << endl;
1253                 cur.recordUndoInset();
1254                 bool old = numberedType();
1255                 if (type_ == hullMultline)
1256                         numbered(nrows() - 1, !old);
1257                 else
1258                         for (row_type row = 0; row < nrows(); ++row)
1259                                 numbered(row, !old);
1260
1261                 cur.message(old ? _("No number") : _("Number"));
1262                 break;
1263         }
1264
1265         case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1266                 cur.recordUndoInset();
1267                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1268                 bool old = numbered(r);
1269                 cur.message(old ? _("No number") : _("Number"));
1270                 numbered(r, !old);
1271                 break;
1272         }
1273
1274         case LFUN_LABEL_INSERT: {
1275                 cur.recordUndoInset();
1276                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1277                 docstring old_label = label(r);
1278                 // FIXME refstyle
1279                 // Allow customization of this separator
1280                 docstring const default_label = from_ascii("eq:");
1281                 if (old_label.empty())
1282                         old_label = default_label;
1283
1284                 InsetCommandParams p(LABEL_CODE);
1285                 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1286                 string const data = InsetCommand::params2string("label", p);
1287
1288                 if (cmd.argument().empty())
1289                         cur.bv().showDialog("label", data);
1290                 else {
1291                         FuncRequest fr(LFUN_INSET_INSERT, data);
1292                         dispatch(cur, fr);
1293                 }
1294                 break;
1295         }
1296
1297         case LFUN_LABEL_COPY_AS_REF: {
1298                 row_type row;
1299                 if (cmd.argument().empty() && &cur.inset() == this)
1300                         // if there is no argument and we're inside math, we retrieve
1301                         // the row number from the cursor position.
1302                         row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1303                 else {
1304                         // if there is an argument, find the corresponding label, else
1305                         // check whether there is at least one label.
1306                         for (row = 0; row != nrows(); ++row)
1307                                 if (!nonum_[row] && label_[row]
1308                                           && (cmd.argument().empty() || label(row) == cmd.argument()))
1309                                         break;
1310                 }
1311
1312                 if (row == nrows())
1313                         break;
1314
1315                 InsetCommandParams p(REF_CODE, "ref");
1316                 p["reference"] = label(row);
1317                 cap::clearSelection();
1318                 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1319                 break;
1320         }
1321
1322         case LFUN_WORD_DELETE_FORWARD:
1323         case LFUN_CHAR_DELETE_FORWARD:
1324                 if (col(cur.idx()) + 1 == ncols()
1325                     && cur.pos() == cur.lastpos()
1326                     && !cur.selection()) {
1327                         if (!label(row(cur.idx())).empty()) {
1328                                 cur.recordUndoInset();
1329                                 label(row(cur.idx()), docstring());
1330                         } else if (numbered(row(cur.idx()))) {
1331                                 cur.recordUndoInset();
1332                                 numbered(row(cur.idx()), false);
1333                         } else {
1334                                 InsetMathGrid::doDispatch(cur, cmd);
1335                                 return;
1336                         }
1337                 } else {
1338                         InsetMathGrid::doDispatch(cur, cmd);
1339                         return;
1340                 }
1341                 break;
1342
1343         case LFUN_INSET_INSERT: {
1344                 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1345                 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1346                 string const name = cmd.getArg(0);
1347                 if (name == "label") {
1348                         InsetCommandParams p(LABEL_CODE);
1349                         InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1350                         docstring str = p["name"];
1351                         cur.recordUndoInset();
1352                         row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1353                         str = trim(str);
1354                         if (!str.empty())
1355                                 numbered(r, true);
1356                         docstring old = label(r);
1357                         if (str != old) {
1358                                 if (label_[r])
1359                                         // The label will take care of the reference update.
1360                                         label(r, str);
1361                                 else {
1362                                         label(r, str);
1363                                         // Newly created inset so initialize it.
1364                                         label_[r]->initView();
1365                                 }
1366                         }
1367                         break;
1368                 }
1369                 InsetMathGrid::doDispatch(cur, cmd);
1370                 return;
1371         }
1372
1373         case LFUN_MATH_EXTERN:
1374                 cur.recordUndoInset();
1375                 doExtern(cur, cmd);
1376                 break;
1377
1378         case LFUN_MATH_MUTATE: {
1379                 cur.recordUndoInset();
1380                 row_type row = cur.row();
1381                 col_type col = cur.col();
1382                 mutate(hullType(cmd.argument()));
1383                 cur.idx() = row * ncols() + col;
1384                 if (cur.idx() > cur.lastidx()) {
1385                         cur.idx() = cur.lastidx();
1386                         cur.pos() = cur.lastpos();
1387                 }
1388                 if (cur.pos() > cur.lastpos())
1389                         cur.pos() = cur.lastpos();
1390
1391                 // FIXME: find some more clever handling of the selection,
1392                 // i.e. preserve it.
1393                 cur.clearSelection();
1394                 //cur.dispatched(FINISHED);
1395                 break;
1396         }
1397
1398         case LFUN_MATH_DISPLAY: {
1399                 cur.recordUndoInset();
1400                 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1401                 cur.idx() = 0;
1402                 cur.pos() = cur.lastpos();
1403                 //cur.dispatched(FINISHED);
1404                 break;
1405         }
1406
1407         default:
1408                 InsetMathGrid::doDispatch(cur, cmd);
1409                 break;
1410         }
1411 }
1412
1413
1414 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1415                 FuncStatus & status) const
1416 {
1417         switch (cmd.action) {
1418         case LFUN_FINISHED_BACKWARD:
1419         case LFUN_FINISHED_FORWARD:
1420         case LFUN_FINISHED_RIGHT:
1421         case LFUN_FINISHED_LEFT:
1422         case LFUN_UP:
1423         case LFUN_DOWN:
1424         case LFUN_NEWLINE_INSERT:
1425         case LFUN_MATH_EXTERN:
1426         case LFUN_MATH_DISPLAY:
1427                 // we handle these
1428                 status.setEnabled(true);
1429                 return true;
1430
1431         case LFUN_MATH_MUTATE: {
1432                 HullType ht = hullType(cmd.argument());
1433                 status.setOnOff(type_ == ht);
1434                 status.setEnabled(true);
1435                 return true;
1436         }
1437
1438         case LFUN_MATH_NUMBER_TOGGLE:
1439                 // FIXME: what is the right test, this or the one of
1440                 // LABEL_INSERT?
1441                 status.setEnabled(display());
1442                 status.setOnOff(numberedType());
1443                 return true;
1444
1445         case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1446                 // FIXME: what is the right test, this or the one of
1447                 // LABEL_INSERT?
1448                 bool const enable = (type_ == hullMultline)
1449                         ? (nrows() - 1 == cur.row())
1450                         : display() != Inline && nrows() > 1;
1451                 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1452                 status.setEnabled(enable);
1453                 status.setOnOff(enable && numbered(r));
1454                 return true;
1455         }
1456
1457         case LFUN_LABEL_INSERT:
1458                 status.setEnabled(type_ != hullSimple);
1459                 return true;
1460
1461         case LFUN_LABEL_COPY_AS_REF: {
1462                 bool enabled = false;
1463                 row_type row;
1464                 if (cmd.argument().empty() && &cur.inset() == this) {
1465                         // if there is no argument and we're inside math, we retrieve
1466                         // the row number from the cursor position.
1467                         row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1468                         enabled = numberedType() && label_[row] && !nonum_[row];
1469                 } else {
1470                         // if there is an argument, find the corresponding label, else
1471                         // check whether there is at least one label.
1472                         for (row_type row = 0; row != nrows(); ++row) {
1473                                 if (!nonum_[row] && label_[row] && 
1474                                         (cmd.argument().empty() || label(row) == cmd.argument())) {
1475                                                 enabled = true;
1476                                                 break;
1477                                 }
1478                         }
1479                 }
1480                 status.setEnabled(enabled);
1481                 return true;
1482         }
1483
1484         case LFUN_INSET_INSERT:
1485                 if (cmd.getArg(0) == "label") {
1486                         status.setEnabled(type_ != hullSimple);
1487                         return true;
1488                 }
1489                 return InsetMathGrid::getStatus(cur, cmd, status);
1490
1491         case LFUN_INSET_MODIFY: {
1492                 istringstream is(to_utf8(cmd.argument()));
1493                 string s;
1494                 is >> s;
1495                 if (s != "tabular")
1496                         return InsetMathGrid::getStatus(cur, cmd, status);
1497                 is >> s;
1498                 if (!rowChangeOK()
1499                     && (s == "append-row"
1500                         || s == "delete-row"
1501                         || s == "copy-row")) {
1502                         status.message(bformat(
1503                                 from_utf8(N_("Can't change number of rows in '%1$s'")),
1504                                 hullName(type_)));
1505                         status.setEnabled(false);
1506                         return true;
1507                 }
1508                 if (!colChangeOK()
1509                     && (s == "append-column"
1510                         || s == "delete-column"
1511                         || s == "copy-column")) {
1512                         status.message(bformat(
1513                                 from_utf8(N_("Can't change number of columns in '%1$s'")),
1514                                 hullName(type_)));
1515                         status.setEnabled(false);
1516                         return true;
1517                 }
1518                 if ((type_ == hullSimple
1519                   || type_ == hullEquation
1520                   || type_ == hullNone) &&
1521                     (s == "add-hline-above" || s == "add-hline-below")) {
1522                         status.message(bformat(
1523                                 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1524                                 hullName(type_)));
1525                         status.setEnabled(false);
1526                         return true;
1527                 }
1528                 if (s == "add-vline-left" || s == "add-vline-right") {
1529                         status.message(bformat(
1530                                 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1531                                 hullName(type_)));
1532                         status.setEnabled(false);
1533                         return true;
1534                 }
1535                 if (s == "valign-top" || s == "valign-middle"
1536                  || s == "valign-bottom" || s == "align-left"
1537                  || s == "align-center" || s == "align-right") {
1538                         status.setEnabled(false);
1539                         return true;
1540                 }
1541                 return InsetMathGrid::getStatus(cur, cmd, status);
1542         }
1543
1544         default:
1545                 return InsetMathGrid::getStatus(cur, cmd, status);
1546         }
1547
1548         // This cannot really happen, but inserted to shut-up gcc
1549         return InsetMathGrid::getStatus(cur, cmd, status);
1550 }
1551
1552
1553 /////////////////////////////////////////////////////////////////////
1554
1555
1556
1557 // simply scrap this function if you want
1558 void InsetMathHull::mutateToText()
1559 {
1560 #if 0
1561         // translate to latex
1562         ostringstream os;
1563         latex(os, false, false);
1564         string str = os.str();
1565
1566         // insert this text
1567         Text * lt = view_->cursor().innerText();
1568         string::const_iterator cit = str.begin();
1569         string::const_iterator end = str.end();
1570         for (; cit != end; ++cit)
1571                 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1572
1573         // remove ourselves
1574         //dispatch(LFUN_ESCAPE);
1575 #endif
1576 }
1577
1578
1579 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1580         docstring const & font)
1581 {
1582         // this whole function is a hack and won't work for incremental font
1583         // changes...
1584         cur.recordUndo();
1585         if (cur.inset().asInsetMath()->name() == font)
1586                 cur.handleFont(to_utf8(font));
1587         else {
1588                 cur.handleNest(createInsetMath(font, cur.buffer()));
1589                 cur.insert(arg);
1590         }
1591 }
1592
1593
1594 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1595 {
1596         cur.recordUndo();
1597         Font font;
1598         bool b;
1599         font.fromString(to_utf8(arg), b);
1600         if (font.fontInfo().color() != Color_inherit) {
1601                 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1602                 cur.handleNest(at, 0);
1603         }
1604 }
1605
1606
1607 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1608 {
1609         cur.push(*this);
1610         bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1611                 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1612         enter_front ? idxFirst(cur) : idxLast(cur);
1613         // The inset formula dimension is not necessarily the same as the
1614         // one of the instant preview image, so we have to indicate to the
1615         // BufferView that a metrics update is needed.
1616         cur.updateFlags(Update::Force);
1617 }
1618
1619
1620 void InsetMathHull::revealCodes(Cursor & cur) const
1621 {
1622         if (!cur.inMathed())
1623                 return;
1624         odocstringstream os;
1625         cur.info(os);
1626         cur.message(os.str());
1627 /*
1628         // write something to the minibuffer
1629         // translate to latex
1630         cur.markInsert(bv);
1631         ostringstream os;
1632         write(os);
1633         string str = os.str();
1634         cur.markErase(bv);
1635         string::size_type pos = 0;
1636         string res;
1637         for (string::iterator it = str.begin(); it != str.end(); ++it) {
1638                 if (*it == '\n')
1639                         res += ' ';
1640                 else if (*it == '\0') {
1641                         res += "  -X-  ";
1642                         pos = it - str.begin();
1643                 }
1644                 else
1645                         res += *it;
1646         }
1647         if (pos > 30)
1648                 res = res.substr(pos - 30);
1649         if (res.size() > 60)
1650                 res = res.substr(0, 60);
1651         cur.message(res);
1652 */
1653 }
1654
1655
1656 /////////////////////////////////////////////////////////////////////
1657
1658
1659 #if 0
1660 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1661                                      bool, bool)
1662 {
1663         // FIXME: completely broken
1664         static InsetMathHull * lastformula = 0;
1665         static CursorBase current = DocIterator(ibegin(nucleus()));
1666         static MathData ar;
1667         static string laststr;
1668
1669         if (lastformula != this || laststr != str) {
1670                 //lyxerr << "reset lastformula to " << this << endl;
1671                 lastformula = this;
1672                 laststr = str;
1673                 current = ibegin(nucleus());
1674                 ar.clear();
1675                 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1676         } else {
1677                 increment(current);
1678         }
1679         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1680
1681         for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1682                 CursorSlice & top = it.back();
1683                 MathData const & a = top.asInsetMath()->cell(top.idx_);
1684                 if (a.matchpart(ar, top.pos_)) {
1685                         bv->cursor().setSelection(it, ar.size());
1686                         current = it;
1687                         top.pos_ += ar.size();
1688                         bv->update();
1689                         return true;
1690                 }
1691         }
1692
1693         //lyxerr << "not found!" << endl;
1694         lastformula = 0;
1695         return false;
1696 }
1697 #endif
1698
1699
1700 void InsetMathHull::write(ostream & os) const
1701 {
1702         odocstringstream oss;
1703         WriteStream wi(oss, false, false, WriteStream::wsDefault);
1704         oss << "Formula ";
1705         write(wi);
1706         os << to_utf8(oss.str());
1707 }
1708
1709
1710 void InsetMathHull::read(Lexer & lex)
1711 {
1712         MathAtom at;
1713         mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1714         operator=(*at->asHullInset());
1715 }
1716
1717
1718 bool InsetMathHull::readQuiet(Lexer & lex)
1719 {
1720         MathAtom at;
1721         bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1722         if (success)
1723                 operator=(*at->asHullInset());
1724         return success;
1725 }
1726
1727
1728 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1729 {
1730         if (0 && display()) {
1731                 Dimension dim;
1732                 TextMetricsInfo mi;
1733                 metricsT(mi, dim);
1734                 TextPainter tpain(dim.width(), dim.height());
1735                 drawT(tpain, 0, dim.ascent());
1736                 tpain.show(os, 3);
1737                 // reset metrics cache to "real" values
1738                 //metrics();
1739                 return tpain.textheight();
1740         } else {
1741                 odocstringstream oss;
1742                 Encoding const * const enc = encodings.fromLyXName("utf8");
1743                 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1744                 // Fix Bug #6139
1745                 if (type_ == hullRegexp)
1746                         write(wi);
1747                 else
1748                         wi << cell(0);
1749                 docstring const str = oss.str();
1750                 os << str;
1751                 return str.size();
1752         }
1753 }
1754
1755
1756 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1757 {
1758         MathStream ms(os);
1759         int res = 0;
1760         docstring name;
1761         if (getType() == hullSimple)
1762                 name = from_ascii("inlineequation");
1763         else
1764                 name = from_ascii("informalequation");
1765
1766         docstring bname = name;
1767         if (!label(0).empty())
1768                 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1769
1770         ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1771
1772         odocstringstream ls;
1773         if (runparams.flavor == OutputParams::XML) {
1774                 ms << MTag("alt role='tex' ");
1775                 // Workaround for db2latex: db2latex always includes equations with
1776                 // \ensuremath{} or \begin{display}\end{display}
1777                 // so we strip LyX' math environment
1778                 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1779                 InsetMathGrid::write(wi);
1780                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
1781                 ms << ETag("alt");
1782                 ms << MTag("math");
1783                 ms << ETag("alt");
1784                 ms << MTag("math");
1785                 InsetMathGrid::mathmlize(ms);
1786                 ms << ETag("math");
1787         } else {
1788                 ms << MTag("alt role='tex'");
1789                 res = latex(ls, runparams);
1790                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
1791                 ms << ETag("alt");
1792         }
1793
1794         ms << from_ascii("<graphic fileref=\"eqn/");
1795         if (!label(0).empty())
1796                 ms << sgml::cleanID(buffer(), runparams, label(0));
1797         else
1798                 ms << sgml::uniqueID(from_ascii("anon"));
1799
1800         if (runparams.flavor == OutputParams::XML)
1801                 ms << from_ascii("\"/>");
1802         else
1803                 ms << from_ascii("\">");
1804
1805         ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1806
1807         return ms.line() + res;
1808 }
1809
1810
1811 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const &) const
1812 {
1813         BufferParams::MathOutput mathtype = buffer().params().html_math_output;
1814         // FIXME Eventually we would like to do this inset by inset.
1815         switch (mathtype) {
1816         case BufferParams::MathML: {
1817                 if (getType() == hullSimple)
1818                         xs << html::StartTag("math", 
1819                               "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1820                 else 
1821                         xs << html::StartTag("math", 
1822                               "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1823                 MathStream ms(xs.os());
1824                 InsetMathGrid::mathmlize(ms);
1825                 xs << html::EndTag("math");
1826                 break;
1827         } 
1828         case BufferParams::HTML: {
1829                 string tag = (getType() == hullSimple) ? "span" : "div";
1830                 xs << html::StartTag(tag, "class='formula'", true);
1831                 HtmlStream ms(xs.os());
1832                 InsetMathGrid::htmlize(ms);
1833                 xs << html::EndTag(tag);
1834                 break;
1835         } 
1836         case BufferParams::Images: {
1837                 LYXERR0("Image output for math presently unsupported.");
1838                 break;
1839         } 
1840         case BufferParams::LaTeX: {
1841                 // FIXME Obviously, the only real question is how to wrap this.
1842                 LYXERR0("LaTeX output for math presently unsupported.");
1843         }
1844         } // end switch
1845         return docstring();
1846 }
1847
1848
1849 void InsetMathHull::tocString(odocstream & os) const
1850 {
1851         plaintext(os, OutputParams(0));
1852 }
1853
1854
1855 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1856 {
1857         return from_ascii("context-math");
1858 }
1859
1860
1861 } // namespace lyx