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