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