]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathHull.cpp
Matrix output via HTML. I have to say, this one took some work.
[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 (features.runparams().isLaTeX()) {
638                 if (ams())
639                         features.require("amsmath");
640         
641                 if (type_ == hullRegexp) {
642                         features.require("color");
643                         string frcol = lcolor.getLaTeXName(Color_regexpframe);
644                         string bgcol = "white";
645                         features.addPreambleSnippet(
646                                 string("\\newcommand{\\regexp}[1]{\\fcolorbox{")
647                                 + frcol + string("}{")
648                                 + bgcol + string("}{\\texttt{#1}}}"));
649                 }
650         
651                 // Validation is necessary only if not using AMS math.
652                 // To be safe, we will always run mathedvalidate.
653                 //if (features.amsstyle)
654                 //  return;
655         
656                 //features.binom      = true;
657         } else if (features.runparams().math_flavor == OutputParams::MathAsHTML) {
658                 // it would be better to do this elsewhere, but we can't validate in
659                 // InsetMathMatrix and we have no way, outside MathExtern, to know if
660                 // we even have any matrices.
661                                 features.addPreambleSnippet("<style type=\"text/css\">\n"
662                                         "table.matrix{display: inline-block; vertical-align: middle; text-align:center;}\n"
663                                         "table.matrix td{padding: 0.25px;}\n"
664                                         "td.ldelim{width: 0.5ex; border: thin solid black; border-right: none;}\n"
665                                         "td.rdelim{width: 0.5ex; border: thin solid black; border-left: none;}\n"
666                                         "</style>");
667         }
668         InsetMathGrid::validate(features);
669 }
670
671
672 void InsetMathHull::header_write(WriteStream & os) const
673 {
674         bool n = numberedType();
675
676         switch(type_) {
677         case hullNone:
678                 break;
679
680         case hullSimple:
681                 os << '$';
682                 if (cell(0).empty())
683                         os << ' ';
684                 break;
685
686         case hullEquation:
687                 if (n)
688                         os << "\\begin{equation" << star(n) << "}\n";
689                 else
690                         os << "\\[\n";
691                 break;
692
693         case hullEqnArray:
694         case hullAlign:
695         case hullFlAlign:
696         case hullGather:
697         case hullMultline:
698                 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
699                 break;
700
701         case hullAlignAt:
702         case hullXAlignAt:
703                 os << "\\begin{" << hullName(type_) << star(n) << '}'
704                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
705                 break;
706
707         case hullXXAlignAt:
708                 os << "\\begin{" << hullName(type_) << '}'
709                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
710                 break;
711
712         case hullRegexp:
713                 os << "\\regexp{{{";
714                 break;
715
716         default:
717                 os << "\\begin{unknown" << star(n) << '}';
718                 break;
719         }
720 }
721
722
723 void InsetMathHull::footer_write(WriteStream & os) const
724 {
725         bool n = numberedType();
726
727         switch(type_) {
728         case hullNone:
729                 os << "\n";
730                 break;
731
732         case hullSimple:
733                 os << '$';
734                 break;
735
736         case hullEquation:
737                 if (n)
738                         os << "\\end{equation" << star(n) << "}\n";
739                 else
740                         os << "\\]\n";
741                 break;
742
743         case hullEqnArray:
744         case hullAlign:
745         case hullFlAlign:
746         case hullAlignAt:
747         case hullXAlignAt:
748         case hullGather:
749         case hullMultline:
750                 os << "\\end{" << hullName(type_) << star(n) << "}\n";
751                 break;
752
753         case hullXXAlignAt:
754                 os << "\\end{" << hullName(type_) << "}\n";
755                 break;
756
757         case hullRegexp:
758                 os << "}}}";
759                 break;
760
761         default:
762                 os << "\\end{unknown" << star(n) << '}';
763                 break;
764         }
765 }
766
767
768 bool InsetMathHull::rowChangeOK() const
769 {
770         return
771                 type_ == hullEqnArray || type_ == hullAlign ||
772                 type_ == hullFlAlign || type_ == hullAlignAt ||
773                 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
774                 type_ == hullGather || type_ == hullMultline;
775 }
776
777
778 bool InsetMathHull::colChangeOK() const
779 {
780         return
781                 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
782                 type_ == hullXAlignAt || type_ == hullXXAlignAt;
783 }
784
785
786 void InsetMathHull::addRow(row_type row)
787 {
788         if (!rowChangeOK())
789                 return;
790
791         bool numbered = numberedType();
792         docstring lab;
793         if (type_ == hullMultline) {
794                 if (row + 1 == nrows())  {
795                         nonum_[row] = true;
796                         lab = label(row);
797                 } else
798                         numbered = false;
799         }
800
801         nonum_.insert(nonum_.begin() + row + 1, !numbered);
802         label_.insert(label_.begin() + row + 1, dummy_pointer);
803         if (!lab.empty())
804                 label(row + 1, lab);
805         InsetMathGrid::addRow(row);
806 }
807
808
809 void InsetMathHull::swapRow(row_type row)
810 {
811         if (nrows() <= 1)
812                 return;
813         if (row + 1 == nrows())
814                 --row;
815         // gcc implements the standard std::vector<bool> which is *not* a container:
816         //   http://www.gotw.ca/publications/N1185.pdf
817         // As a results, it doesn't like this:
818         //      swap(nonum_[row], nonum_[row + 1]);
819         // so we do it manually:
820         bool const b = nonum_[row];
821         nonum_[row] = nonum_[row + 1];
822         nonum_[row + 1] = b;
823         swap(label_[row], label_[row + 1]);
824         InsetMathGrid::swapRow(row);
825 }
826
827
828 void InsetMathHull::delRow(row_type row)
829 {
830         if (nrows() <= 1 || !rowChangeOK())
831                 return;
832         if (row + 1 == nrows() && type_ == hullMultline) {
833                 bool const b = nonum_[row - 1];
834                 nonum_[row - 1] = nonum_[row];
835                 nonum_[row] = b;
836                 swap(label_[row - 1], label_[row]);
837                 InsetMathGrid::delRow(row);
838                 return;
839         }
840         InsetMathGrid::delRow(row);
841         // The last dummy row has no number info nor a label.
842         // Test nrows() + 1 because we have already erased the row.
843         if (row == nrows() + 1)
844                 row--;
845         nonum_.erase(nonum_.begin() + row);
846         delete label_[row];
847         label_.erase(label_.begin() + row);
848 }
849
850
851 void InsetMathHull::addCol(col_type col)
852 {
853         if (!colChangeOK())
854                 return;
855         InsetMathGrid::addCol(col);
856 }
857
858
859 void InsetMathHull::delCol(col_type col)
860 {
861         if (ncols() <= 1 || !colChangeOK())
862                 return;
863         InsetMathGrid::delCol(col);
864 }
865
866
867 docstring InsetMathHull::nicelabel(row_type row) const
868 {
869         if (nonum_[row])
870                 return docstring();
871         if (!label_[row])
872                 return from_ascii("(#)");
873         return '(' + label_[row]->screenLabel() + from_ascii(", #)");
874 }
875
876
877 void InsetMathHull::glueall()
878 {
879         MathData ar;
880         for (idx_type i = 0; i < nargs(); ++i)
881                 ar.append(cell(i));
882         *this = InsetMathHull(buffer_, hullSimple);
883         cell(0) = ar;
884         setDefaults();
885 }
886
887
888 void InsetMathHull::splitTo2Cols()
889 {
890         LASSERT(ncols() == 1, /**/);
891         InsetMathGrid::addCol(1);
892         for (row_type row = 0; row < nrows(); ++row) {
893                 idx_type const i = 2 * row;
894                 pos_type pos = firstRelOp(cell(i));
895                 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
896                 cell(i).erase(pos, cell(i).size());
897         }
898 }
899
900
901 void InsetMathHull::splitTo3Cols()
902 {
903         LASSERT(ncols() < 3, /**/);
904         if (ncols() < 2)
905                 splitTo2Cols();
906         InsetMathGrid::addCol(2);
907         for (row_type row = 0; row < nrows(); ++row) {
908                 idx_type const i = 3 * row + 1;
909                 if (cell(i).size()) {
910                         cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
911                         cell(i).erase(1, cell(i).size());
912                 }
913         }
914 }
915
916
917 void InsetMathHull::changeCols(col_type cols)
918 {
919         if (ncols() == cols)
920                 return;
921         else if (ncols() < cols) {
922                 // split columns
923                 if (cols < 3)
924                         splitTo2Cols();
925                 else {
926                         splitTo3Cols();
927                         while (ncols() < cols)
928                                 InsetMathGrid::addCol(ncols());
929                 }
930                 return;
931         }
932
933         // combine columns
934         for (row_type row = 0; row < nrows(); ++row) {
935                 idx_type const i = row * ncols();
936                 for (col_type col = cols; col < ncols(); ++col) {
937                         cell(i + cols - 1).append(cell(i + col));
938                 }
939         }
940         // delete columns
941         while (ncols() > cols) {
942                 InsetMathGrid::delCol(ncols() - 1);
943         }
944 }
945
946
947 HullType InsetMathHull::getType() const
948 {
949         return type_;
950 }
951
952
953 void InsetMathHull::setType(HullType type)
954 {
955         type_ = type;
956         setDefaults();
957 }
958
959
960 void InsetMathHull::mutate(HullType newtype)
961 {
962         //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
963
964         // we try to move along the chain
965         // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
966         //                                     ^                                     |
967         //                                     +-------------------------------------+
968         // we use eqnarray as intermediate type for mutations that are not
969         // directly supported because it handles labels and numbering for
970         // "down mutation".
971
972         if (newtype == type_) {
973                 // done
974         }
975
976         else if (newtype < hullNone) {
977                 // unknown type
978                 dump();
979         }
980
981         else if (type_ == hullNone) {
982                 setType(hullSimple);
983                 numbered(0, false);
984                 mutate(newtype);
985         }
986
987         else if (type_ == hullSimple) {
988                 if (newtype == hullNone) {
989                         setType(hullNone);
990                         numbered(0, false);
991                 } else {
992                         setType(hullEquation);
993                         numbered(0, false);
994                         mutate(newtype);
995                 }
996         }
997
998         else if (type_ == hullEquation) {
999                 if (newtype < type_) {
1000                         setType(hullSimple);
1001                         numbered(0, false);
1002                         mutate(newtype);
1003                 } else if (newtype == hullEqnArray) {
1004                         // split it "nicely" on the first relop
1005                         splitTo3Cols();
1006                         setType(hullEqnArray);
1007                 } else if (newtype == hullMultline || newtype == hullGather) {
1008                         setType(newtype);
1009                 } else {
1010                         // split it "nicely"
1011                         splitTo2Cols();
1012                         setType(hullAlign);
1013                         mutate(newtype);
1014                 }
1015         }
1016
1017         else if (type_ == hullEqnArray) {
1018                 if (newtype < type_) {
1019                         // set correct (no)numbering
1020                         nonum_[0] = true;
1021                         for (row_type row = 0; row < nrows(); ++row) {
1022                                 if (!nonum_[row]) {
1023                                         nonum_[0] = false;
1024                                         break;
1025                                 }
1026                         }
1027
1028                         // set first non-empty label
1029                         for (row_type row = 0; row < nrows(); ++row) {
1030                                 if (label_[row]) {
1031                                         label_[0] = label_[row];
1032                                         break;
1033                                 }
1034                         }
1035
1036                         glueall();
1037                         mutate(newtype);
1038                 } else { // align & Co.
1039                         changeCols(2);
1040                         setType(hullAlign);
1041                         mutate(newtype);
1042                 }
1043         }
1044
1045         else if (type_ ==  hullAlign || type_ == hullAlignAt ||
1046                  type_ == hullXAlignAt || type_ == hullFlAlign) {
1047                 if (newtype < hullAlign) {
1048                         changeCols(3);
1049                         setType(hullEqnArray);
1050                         mutate(newtype);
1051                 } else if (newtype == hullGather || newtype == hullMultline) {
1052                         changeCols(1);
1053                         setType(newtype);
1054                 } else if (newtype ==   hullXXAlignAt) {
1055                         for (row_type row = 0; row < nrows(); ++row)
1056                                 numbered(row, false);
1057                         setType(newtype);
1058                 } else {
1059                         setType(newtype);
1060                 }
1061         }
1062
1063         else if (type_ == hullXXAlignAt) {
1064                 for (row_type row = 0; row < nrows(); ++row)
1065                         numbered(row, false);
1066                 if (newtype < hullAlign) {
1067                         changeCols(3);
1068                         setType(hullEqnArray);
1069                         mutate(newtype);
1070                 } else if (newtype == hullGather || newtype == hullMultline) {
1071                         changeCols(1);
1072                         setType(newtype);
1073                 } else {
1074                         setType(newtype);
1075                 }
1076         }
1077
1078         else if (type_ == hullMultline || type_ == hullGather) {
1079                 if (newtype == hullGather || newtype == hullMultline)
1080                         setType(newtype);
1081                 else if (newtype == hullAlign || newtype == hullFlAlign  ||
1082                          newtype == hullAlignAt || newtype == hullXAlignAt) {
1083                         splitTo2Cols();
1084                         setType(newtype);
1085                 } else if (newtype ==   hullXXAlignAt) {
1086                         splitTo2Cols();
1087                         for (row_type row = 0; row < nrows(); ++row)
1088                                 numbered(row, false);
1089                         setType(newtype);
1090                 } else {
1091                         splitTo3Cols();
1092                         setType(hullEqnArray);
1093                         mutate(newtype);
1094                 }
1095         }
1096
1097         else {
1098                 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1099                        << "' to '" << to_utf8(hullName(newtype))
1100                        << "' not implemented" << endl;
1101         }
1102 }
1103
1104
1105 docstring InsetMathHull::eolString(row_type row, bool fragile) const
1106 {
1107         docstring res;
1108         if (numberedType()) {
1109                 if (label_[row] && !nonum_[row])
1110                         res += "\\label{" +
1111                             escape(label_[row]->getParam("name")) + '}';
1112                 if (nonum_[row] && (type_ != hullMultline))
1113                         res += "\\nonumber ";
1114         }
1115         return res + InsetMathGrid::eolString(row, fragile);
1116 }
1117
1118
1119 void InsetMathHull::write(WriteStream & os) const
1120 {
1121         ModeSpecifier specifier(os, MATH_MODE);
1122         header_write(os);
1123         InsetMathGrid::write(os);
1124         footer_write(os);
1125 }
1126
1127
1128 void InsetMathHull::normalize(NormalStream & os) const
1129 {
1130         os << "[formula " << hullName(type_) << ' ';
1131         InsetMathGrid::normalize(os);
1132         os << "] ";
1133 }
1134
1135
1136 void InsetMathHull::mathmlize(MathStream & os) const
1137 {
1138         InsetMathGrid::mathmlize(os);
1139 }
1140
1141
1142 void InsetMathHull::infoize(odocstream & os) const
1143 {
1144         os << "Type: " << hullName(type_);
1145 }
1146
1147
1148 void InsetMathHull::check() const
1149 {
1150         LASSERT(nonum_.size() == nrows(), /**/);
1151         LASSERT(label_.size() == nrows(), /**/);
1152 }
1153
1154
1155 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1156 {
1157         docstring dlang;
1158         docstring extra;
1159         idocstringstream iss(func.argument());
1160         iss >> dlang >> extra;
1161         if (extra.empty())
1162                 extra = from_ascii("noextra");
1163         string const lang = to_ascii(dlang);
1164
1165         // FIXME: temporarily disabled
1166         //if (cur.selection()) {
1167         //      MathData ar;
1168         //      selGet(cur.ar);
1169         //      lyxerr << "use selection: " << ar << endl;
1170         //      insert(pipeThroughExtern(lang, extra, ar));
1171         //      return;
1172         //}
1173
1174         MathData eq;
1175         eq.push_back(MathAtom(new InsetMathChar('=')));
1176
1177         // go to first item in line
1178         cur.idx() -= cur.idx() % ncols();
1179         cur.pos() = 0;
1180
1181         if (getType() == hullSimple) {
1182                 size_type pos = cur.cell().find_last(eq);
1183                 MathData ar;
1184                 if (cur.inMathed() && cur.selection()) {
1185                         asArray(grabAndEraseSelection(cur), ar);
1186                 } else if (pos == cur.cell().size()) {
1187                         ar = cur.cell();
1188                         lyxerr << "use whole cell: " << ar << endl;
1189                 } else {
1190                         ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1191                         lyxerr << "use partial cell form pos: " << pos << endl;
1192                 }
1193                 cur.cell().append(eq);
1194                 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1195                 cur.pos() = cur.lastpos();
1196                 return;
1197         }
1198
1199         if (getType() == hullEquation) {
1200                 lyxerr << "use equation inset" << endl;
1201                 mutate(hullEqnArray);
1202                 MathData & ar = cur.cell();
1203                 lyxerr << "use cell: " << ar << endl;
1204                 ++cur.idx();
1205                 cur.cell() = eq;
1206                 ++cur.idx();
1207                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1208                 // move to end of line
1209                 cur.pos() = cur.lastpos();
1210                 return;
1211         }
1212
1213         {
1214                 lyxerr << "use eqnarray" << endl;
1215                 cur.idx() += 2 - cur.idx() % ncols();
1216                 cur.pos() = 0;
1217                 MathData ar = cur.cell();
1218                 lyxerr << "use cell: " << ar << endl;
1219                 // FIXME: temporarily disabled
1220                 addRow(cur.row());
1221                 ++cur.idx();
1222                 ++cur.idx();
1223                 cur.cell() = eq;
1224                 ++cur.idx();
1225                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1226                 cur.pos() = cur.lastpos();
1227         }
1228 }
1229
1230
1231 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1232 {
1233         //lyxerr << "action: " << cmd.action << endl;
1234         switch (cmd.action) {
1235
1236         case LFUN_FINISHED_BACKWARD:
1237         case LFUN_FINISHED_FORWARD:
1238         case LFUN_FINISHED_RIGHT:
1239         case LFUN_FINISHED_LEFT:
1240                 //lyxerr << "action: " << cmd.action << endl;
1241                 InsetMathGrid::doDispatch(cur, cmd);
1242                 cur.undispatched();
1243                 break;
1244
1245         case LFUN_BREAK_PARAGRAPH:
1246                 // just swallow this
1247                 break;
1248
1249         case LFUN_NEWLINE_INSERT:
1250                 // some magic for the common case
1251                 if (type_ == hullSimple || type_ == hullEquation) {
1252                         cur.recordUndoInset();
1253                         bool const align =
1254                                 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1255                         mutate(align ? hullAlign : hullEqnArray);
1256                         cur.idx() = nrows() * ncols() - 1;
1257                         cur.pos() = cur.lastpos();
1258                 }
1259                 InsetMathGrid::doDispatch(cur, cmd);
1260                 break;
1261
1262         case LFUN_MATH_NUMBER_TOGGLE: {
1263                 //lyxerr << "toggling all numbers" << endl;
1264                 cur.recordUndoInset();
1265                 bool old = numberedType();
1266                 if (type_ == hullMultline)
1267                         numbered(nrows() - 1, !old);
1268                 else
1269                         for (row_type row = 0; row < nrows(); ++row)
1270                                 numbered(row, !old);
1271
1272                 cur.message(old ? _("No number") : _("Number"));
1273                 break;
1274         }
1275
1276         case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1277                 cur.recordUndoInset();
1278                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1279                 bool old = numbered(r);
1280                 cur.message(old ? _("No number") : _("Number"));
1281                 numbered(r, !old);
1282                 break;
1283         }
1284
1285         case LFUN_LABEL_INSERT: {
1286                 cur.recordUndoInset();
1287                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1288                 docstring old_label = label(r);
1289                 // FIXME refstyle
1290                 // Allow customization of this separator
1291                 docstring const default_label = from_ascii("eq:");
1292                 if (old_label.empty())
1293                         old_label = default_label;
1294
1295                 InsetCommandParams p(LABEL_CODE);
1296                 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1297                 string const data = InsetCommand::params2string("label", p);
1298
1299                 if (cmd.argument().empty())
1300                         cur.bv().showDialog("label", data);
1301                 else {
1302                         FuncRequest fr(LFUN_INSET_INSERT, data);
1303                         dispatch(cur, fr);
1304                 }
1305                 break;
1306         }
1307
1308         case LFUN_LABEL_COPY_AS_REF: {
1309                 row_type row;
1310                 if (cmd.argument().empty() && &cur.inset() == this)
1311                         // if there is no argument and we're inside math, we retrieve
1312                         // the row number from the cursor position.
1313                         row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1314                 else {
1315                         // if there is an argument, find the corresponding label, else
1316                         // check whether there is at least one label.
1317                         for (row = 0; row != nrows(); ++row)
1318                                 if (!nonum_[row] && label_[row]
1319                                           && (cmd.argument().empty() || label(row) == cmd.argument()))
1320                                         break;
1321                 }
1322
1323                 if (row == nrows())
1324                         break;
1325
1326                 InsetCommandParams p(REF_CODE, "ref");
1327                 p["reference"] = label(row);
1328                 cap::clearSelection();
1329                 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1330                 break;
1331         }
1332
1333         case LFUN_WORD_DELETE_FORWARD:
1334         case LFUN_CHAR_DELETE_FORWARD:
1335                 if (col(cur.idx()) + 1 == ncols()
1336                     && cur.pos() == cur.lastpos()
1337                     && !cur.selection()) {
1338                         if (!label(row(cur.idx())).empty()) {
1339                                 cur.recordUndoInset();
1340                                 label(row(cur.idx()), docstring());
1341                         } else if (numbered(row(cur.idx()))) {
1342                                 cur.recordUndoInset();
1343                                 numbered(row(cur.idx()), false);
1344                         } else {
1345                                 InsetMathGrid::doDispatch(cur, cmd);
1346                                 return;
1347                         }
1348                 } else {
1349                         InsetMathGrid::doDispatch(cur, cmd);
1350                         return;
1351                 }
1352                 break;
1353
1354         case LFUN_INSET_INSERT: {
1355                 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1356                 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1357                 string const name = cmd.getArg(0);
1358                 if (name == "label") {
1359                         InsetCommandParams p(LABEL_CODE);
1360                         InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1361                         docstring str = p["name"];
1362                         cur.recordUndoInset();
1363                         row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1364                         str = trim(str);
1365                         if (!str.empty())
1366                                 numbered(r, true);
1367                         docstring old = label(r);
1368                         if (str != old) {
1369                                 if (label_[r])
1370                                         // The label will take care of the reference update.
1371                                         label(r, str);
1372                                 else {
1373                                         label(r, str);
1374                                         // Newly created inset so initialize it.
1375                                         label_[r]->initView();
1376                                 }
1377                         }
1378                         break;
1379                 }
1380                 InsetMathGrid::doDispatch(cur, cmd);
1381                 return;
1382         }
1383
1384         case LFUN_MATH_EXTERN:
1385                 cur.recordUndoInset();
1386                 doExtern(cur, cmd);
1387                 break;
1388
1389         case LFUN_MATH_MUTATE: {
1390                 cur.recordUndoInset();
1391                 row_type row = cur.row();
1392                 col_type col = cur.col();
1393                 mutate(hullType(cmd.argument()));
1394                 cur.idx() = row * ncols() + col;
1395                 if (cur.idx() > cur.lastidx()) {
1396                         cur.idx() = cur.lastidx();
1397                         cur.pos() = cur.lastpos();
1398                 }
1399                 if (cur.pos() > cur.lastpos())
1400                         cur.pos() = cur.lastpos();
1401
1402                 // FIXME: find some more clever handling of the selection,
1403                 // i.e. preserve it.
1404                 cur.clearSelection();
1405                 //cur.dispatched(FINISHED);
1406                 break;
1407         }
1408
1409         case LFUN_MATH_DISPLAY: {
1410                 cur.recordUndoInset();
1411                 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1412                 cur.idx() = 0;
1413                 cur.pos() = cur.lastpos();
1414                 //cur.dispatched(FINISHED);
1415                 break;
1416         }
1417
1418         default:
1419                 InsetMathGrid::doDispatch(cur, cmd);
1420                 break;
1421         }
1422 }
1423
1424
1425 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1426                 FuncStatus & status) const
1427 {
1428         switch (cmd.action) {
1429         case LFUN_FINISHED_BACKWARD:
1430         case LFUN_FINISHED_FORWARD:
1431         case LFUN_FINISHED_RIGHT:
1432         case LFUN_FINISHED_LEFT:
1433         case LFUN_UP:
1434         case LFUN_DOWN:
1435         case LFUN_NEWLINE_INSERT:
1436         case LFUN_MATH_EXTERN:
1437         case LFUN_MATH_DISPLAY:
1438                 // we handle these
1439                 status.setEnabled(true);
1440                 return true;
1441
1442         case LFUN_MATH_MUTATE: {
1443                 HullType ht = hullType(cmd.argument());
1444                 status.setOnOff(type_ == ht);
1445                 status.setEnabled(true);
1446                 return true;
1447         }
1448
1449         case LFUN_MATH_NUMBER_TOGGLE:
1450                 // FIXME: what is the right test, this or the one of
1451                 // LABEL_INSERT?
1452                 status.setEnabled(display());
1453                 status.setOnOff(numberedType());
1454                 return true;
1455
1456         case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1457                 // FIXME: what is the right test, this or the one of
1458                 // LABEL_INSERT?
1459                 bool const enable = (type_ == hullMultline)
1460                         ? (nrows() - 1 == cur.row())
1461                         : display() != Inline && nrows() > 1;
1462                 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1463                 status.setEnabled(enable);
1464                 status.setOnOff(enable && numbered(r));
1465                 return true;
1466         }
1467
1468         case LFUN_LABEL_INSERT:
1469                 status.setEnabled(type_ != hullSimple);
1470                 return true;
1471
1472         case LFUN_LABEL_COPY_AS_REF: {
1473                 bool enabled = false;
1474                 row_type row;
1475                 if (cmd.argument().empty() && &cur.inset() == this) {
1476                         // if there is no argument and we're inside math, we retrieve
1477                         // the row number from the cursor position.
1478                         row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1479                         enabled = numberedType() && label_[row] && !nonum_[row];
1480                 } else {
1481                         // if there is an argument, find the corresponding label, else
1482                         // check whether there is at least one label.
1483                         for (row_type row = 0; row != nrows(); ++row) {
1484                                 if (!nonum_[row] && label_[row] && 
1485                                         (cmd.argument().empty() || label(row) == cmd.argument())) {
1486                                                 enabled = true;
1487                                                 break;
1488                                 }
1489                         }
1490                 }
1491                 status.setEnabled(enabled);
1492                 return true;
1493         }
1494
1495         case LFUN_INSET_INSERT:
1496                 if (cmd.getArg(0) == "label") {
1497                         status.setEnabled(type_ != hullSimple);
1498                         return true;
1499                 }
1500                 return InsetMathGrid::getStatus(cur, cmd, status);
1501
1502         case LFUN_INSET_MODIFY: {
1503                 istringstream is(to_utf8(cmd.argument()));
1504                 string s;
1505                 is >> s;
1506                 if (s != "tabular")
1507                         return InsetMathGrid::getStatus(cur, cmd, status);
1508                 is >> s;
1509                 if (!rowChangeOK()
1510                     && (s == "append-row"
1511                         || s == "delete-row"
1512                         || s == "copy-row")) {
1513                         status.message(bformat(
1514                                 from_utf8(N_("Can't change number of rows in '%1$s'")),
1515                                 hullName(type_)));
1516                         status.setEnabled(false);
1517                         return true;
1518                 }
1519                 if (!colChangeOK()
1520                     && (s == "append-column"
1521                         || s == "delete-column"
1522                         || s == "copy-column")) {
1523                         status.message(bformat(
1524                                 from_utf8(N_("Can't change number of columns in '%1$s'")),
1525                                 hullName(type_)));
1526                         status.setEnabled(false);
1527                         return true;
1528                 }
1529                 if ((type_ == hullSimple
1530                   || type_ == hullEquation
1531                   || type_ == hullNone) &&
1532                     (s == "add-hline-above" || s == "add-hline-below")) {
1533                         status.message(bformat(
1534                                 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1535                                 hullName(type_)));
1536                         status.setEnabled(false);
1537                         return true;
1538                 }
1539                 if (s == "add-vline-left" || s == "add-vline-right") {
1540                         status.message(bformat(
1541                                 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1542                                 hullName(type_)));
1543                         status.setEnabled(false);
1544                         return true;
1545                 }
1546                 if (s == "valign-top" || s == "valign-middle"
1547                  || s == "valign-bottom" || s == "align-left"
1548                  || s == "align-center" || s == "align-right") {
1549                         status.setEnabled(false);
1550                         return true;
1551                 }
1552                 return InsetMathGrid::getStatus(cur, cmd, status);
1553         }
1554
1555         default:
1556                 return InsetMathGrid::getStatus(cur, cmd, status);
1557         }
1558
1559         // This cannot really happen, but inserted to shut-up gcc
1560         return InsetMathGrid::getStatus(cur, cmd, status);
1561 }
1562
1563
1564 /////////////////////////////////////////////////////////////////////
1565
1566
1567
1568 // simply scrap this function if you want
1569 void InsetMathHull::mutateToText()
1570 {
1571 #if 0
1572         // translate to latex
1573         ostringstream os;
1574         latex(os, false, false);
1575         string str = os.str();
1576
1577         // insert this text
1578         Text * lt = view_->cursor().innerText();
1579         string::const_iterator cit = str.begin();
1580         string::const_iterator end = str.end();
1581         for (; cit != end; ++cit)
1582                 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1583
1584         // remove ourselves
1585         //dispatch(LFUN_ESCAPE);
1586 #endif
1587 }
1588
1589
1590 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1591         docstring const & font)
1592 {
1593         // this whole function is a hack and won't work for incremental font
1594         // changes...
1595         cur.recordUndo();
1596         if (cur.inset().asInsetMath()->name() == font)
1597                 cur.handleFont(to_utf8(font));
1598         else {
1599                 cur.handleNest(createInsetMath(font, cur.buffer()));
1600                 cur.insert(arg);
1601         }
1602 }
1603
1604
1605 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1606 {
1607         cur.recordUndo();
1608         Font font;
1609         bool b;
1610         font.fromString(to_utf8(arg), b);
1611         if (font.fontInfo().color() != Color_inherit) {
1612                 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1613                 cur.handleNest(at, 0);
1614         }
1615 }
1616
1617
1618 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1619 {
1620         cur.push(*this);
1621         bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1622                 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1623         enter_front ? idxFirst(cur) : idxLast(cur);
1624         // The inset formula dimension is not necessarily the same as the
1625         // one of the instant preview image, so we have to indicate to the
1626         // BufferView that a metrics update is needed.
1627         cur.updateFlags(Update::Force);
1628 }
1629
1630
1631 void InsetMathHull::revealCodes(Cursor & cur) const
1632 {
1633         if (!cur.inMathed())
1634                 return;
1635         odocstringstream os;
1636         cur.info(os);
1637         cur.message(os.str());
1638 /*
1639         // write something to the minibuffer
1640         // translate to latex
1641         cur.markInsert(bv);
1642         ostringstream os;
1643         write(os);
1644         string str = os.str();
1645         cur.markErase(bv);
1646         string::size_type pos = 0;
1647         string res;
1648         for (string::iterator it = str.begin(); it != str.end(); ++it) {
1649                 if (*it == '\n')
1650                         res += ' ';
1651                 else if (*it == '\0') {
1652                         res += "  -X-  ";
1653                         pos = it - str.begin();
1654                 }
1655                 else
1656                         res += *it;
1657         }
1658         if (pos > 30)
1659                 res = res.substr(pos - 30);
1660         if (res.size() > 60)
1661                 res = res.substr(0, 60);
1662         cur.message(res);
1663 */
1664 }
1665
1666
1667 /////////////////////////////////////////////////////////////////////
1668
1669
1670 #if 0
1671 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1672                                      bool, bool)
1673 {
1674         // FIXME: completely broken
1675         static InsetMathHull * lastformula = 0;
1676         static CursorBase current = DocIterator(ibegin(nucleus()));
1677         static MathData ar;
1678         static string laststr;
1679
1680         if (lastformula != this || laststr != str) {
1681                 //lyxerr << "reset lastformula to " << this << endl;
1682                 lastformula = this;
1683                 laststr = str;
1684                 current = ibegin(nucleus());
1685                 ar.clear();
1686                 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1687         } else {
1688                 increment(current);
1689         }
1690         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1691
1692         for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1693                 CursorSlice & top = it.back();
1694                 MathData const & a = top.asInsetMath()->cell(top.idx_);
1695                 if (a.matchpart(ar, top.pos_)) {
1696                         bv->cursor().setSelection(it, ar.size());
1697                         current = it;
1698                         top.pos_ += ar.size();
1699                         bv->update();
1700                         return true;
1701                 }
1702         }
1703
1704         //lyxerr << "not found!" << endl;
1705         lastformula = 0;
1706         return false;
1707 }
1708 #endif
1709
1710
1711 void InsetMathHull::write(ostream & os) const
1712 {
1713         odocstringstream oss;
1714         WriteStream wi(oss, false, false, WriteStream::wsDefault);
1715         oss << "Formula ";
1716         write(wi);
1717         os << to_utf8(oss.str());
1718 }
1719
1720
1721 void InsetMathHull::read(Lexer & lex)
1722 {
1723         MathAtom at;
1724         mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1725         operator=(*at->asHullInset());
1726 }
1727
1728
1729 bool InsetMathHull::readQuiet(Lexer & lex)
1730 {
1731         MathAtom at;
1732         bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1733         if (success)
1734                 operator=(*at->asHullInset());
1735         return success;
1736 }
1737
1738
1739 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1740 {
1741         if (0 && display()) {
1742                 Dimension dim;
1743                 TextMetricsInfo mi;
1744                 metricsT(mi, dim);
1745                 TextPainter tpain(dim.width(), dim.height());
1746                 drawT(tpain, 0, dim.ascent());
1747                 tpain.show(os, 3);
1748                 // reset metrics cache to "real" values
1749                 //metrics();
1750                 return tpain.textheight();
1751         } else {
1752                 odocstringstream oss;
1753                 Encoding const * const enc = encodings.fromLyXName("utf8");
1754                 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1755                 // Fix Bug #6139
1756                 if (type_ == hullRegexp)
1757                         write(wi);
1758                 else
1759                         wi << cell(0);
1760                 docstring const str = oss.str();
1761                 os << str;
1762                 return str.size();
1763         }
1764 }
1765
1766
1767 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1768 {
1769         MathStream ms(os);
1770         int res = 0;
1771         docstring name;
1772         if (getType() == hullSimple)
1773                 name = from_ascii("inlineequation");
1774         else
1775                 name = from_ascii("informalequation");
1776
1777         docstring bname = name;
1778         if (!label(0).empty())
1779                 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1780
1781         ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1782
1783         odocstringstream ls;
1784         if (runparams.flavor == OutputParams::XML) {
1785                 ms << MTag("alt role='tex' ");
1786                 // Workaround for db2latex: db2latex always includes equations with
1787                 // \ensuremath{} or \begin{display}\end{display}
1788                 // so we strip LyX' math environment
1789                 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1790                 InsetMathGrid::write(wi);
1791                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
1792                 ms << ETag("alt");
1793                 ms << MTag("math");
1794                 ms << ETag("alt");
1795                 ms << MTag("math");
1796                 InsetMathGrid::mathmlize(ms);
1797                 ms << ETag("math");
1798         } else {
1799                 ms << MTag("alt role='tex'");
1800                 res = latex(ls, runparams);
1801                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
1802                 ms << ETag("alt");
1803         }
1804
1805         ms << from_ascii("<graphic fileref=\"eqn/");
1806         if (!label(0).empty())
1807                 ms << sgml::cleanID(buffer(), runparams, label(0));
1808         else
1809                 ms << sgml::uniqueID(from_ascii("anon"));
1810
1811         if (runparams.flavor == OutputParams::XML)
1812                 ms << from_ascii("\"/>");
1813         else
1814                 ms << from_ascii("\">");
1815
1816         ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1817
1818         return ms.line() + res;
1819 }
1820
1821
1822 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const &) const
1823 {
1824         BufferParams::MathOutput mathtype = buffer().params().html_math_output;
1825         // FIXME Eventually we would like to do this inset by inset.
1826         switch (mathtype) {
1827         case BufferParams::MathML: {
1828                 if (getType() == hullSimple)
1829                         xs << html::StartTag("math", 
1830                               "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1831                 else 
1832                         xs << html::StartTag("math", 
1833                               "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1834                 MathStream ms(xs.os());
1835                 InsetMathGrid::mathmlize(ms);
1836                 xs << html::EndTag("math");
1837                 break;
1838         } 
1839         case BufferParams::HTML: {
1840                 string tag = (getType() == hullSimple) ? "span" : "div";
1841                 xs << html::StartTag(tag, "class='formula'", true);
1842                 HtmlStream ms(xs.os());
1843                 InsetMathGrid::htmlize(ms);
1844                 xs << html::EndTag(tag);
1845                 break;
1846         } 
1847         case BufferParams::Images: {
1848                 LYXERR0("Image output for math presently unsupported.");
1849                 break;
1850         } 
1851         case BufferParams::LaTeX: {
1852                 // FIXME Obviously, the only real question is how to wrap this.
1853                 LYXERR0("LaTeX output for math presently unsupported.");
1854         }
1855         } // end switch
1856         return docstring();
1857 }
1858
1859
1860 void InsetMathHull::tocString(odocstream & os) const
1861 {
1862         plaintext(os, OutputParams(0));
1863 }
1864
1865
1866 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1867 {
1868         return from_ascii("context-math");
1869 }
1870
1871
1872 } // namespace lyx