]> git.lyx.org Git - features.git/blob - src/mathed/InsetMathHull.cpp
InsetMathHull::addToToc(): Work around buffer reference in InsetMathHull. This inset...
[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 "InsetMathArray.h"
14 #include "InsetMathChar.h"
15 #include "InsetMathColor.h"
16 #include "MathData.h"
17 #include "InsetMathDelim.h"
18 #include "MathExtern.h"
19 #include "MathFactory.h"
20 #include "InsetMathHull.h"
21 #include "MathStream.h"
22 #include "MathParser.h"
23 #include "InsetMathSpace.h"
24 #include "MathStream.h"
25 #include "MathSupport.h"
26 #include "InsetMathRef.h"
27
28 #include "Buffer.h"
29 #include "BufferParams.h"
30 #include "BufferView.h"
31 #include "CutAndPaste.h"
32 #include "FuncStatus.h"
33 #include "LaTeXFeatures.h"
34 #include "Cursor.h"
35 #include "DispatchResult.h"
36 #include "FuncRequest.h"
37 #include "LyXRC.h"
38 #include "OutputParams.h"
39 #include "ParIterator.h"
40 #include "sgml.h"
41 #include "Text.h"
42 #include "TextPainter.h"
43 #include "TocBackend.h"
44
45 #include "insets/RenderPreview.h"
46 #include "insets/InsetLabel.h"
47
48 #include "graphics/PreviewImage.h"
49 #include "graphics/PreviewLoader.h"
50
51 #include "frontends/Painter.h"
52
53 #include "support/debug.h"
54 #include "support/gettext.h"
55 #include "support/lstrings.h"
56
57 #include <sstream>
58
59 using namespace std;
60 using namespace lyx::support;
61
62 namespace lyx {
63
64 using cap::grabAndEraseSelection;
65
66 namespace {
67
68         int getCols(HullType type)
69         {
70                 switch (type) {
71                         case hullEqnArray:
72                                 return 3;
73                         case hullAlign:
74                         case hullFlAlign:
75                         case hullAlignAt:
76                         case hullXAlignAt:
77                         case hullXXAlignAt:
78                                 return 2;
79                         default:
80                                 return 1;
81                 }
82         }
83
84
85         // returns position of first relation operator in the array
86         // used for "intelligent splitting"
87         size_t firstRelOp(MathData const & ar)
88         {
89                 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
90                         if ((*it)->isRelOp())
91                                 return it - ar.begin();
92                 return ar.size();
93         }
94
95
96         char const * star(bool numbered)
97         {
98                 return numbered ? "" : "*";
99         }
100
101
102 } // end anon namespace
103
104
105 HullType hullType(docstring const & s)
106 {
107         if (s == "none")      return hullNone;
108         if (s == "simple")    return hullSimple;
109         if (s == "equation")  return hullEquation;
110         if (s == "eqnarray")  return hullEqnArray;
111         if (s == "align")     return hullAlign;
112         if (s == "alignat")   return hullAlignAt;
113         if (s == "xalignat")  return hullXAlignAt;
114         if (s == "xxalignat") return hullXXAlignAt;
115         if (s == "multline")  return hullMultline;
116         if (s == "gather")    return hullGather;
117         if (s == "flalign")   return hullFlAlign;
118         lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
119         return HullType(-1);
120 }
121
122
123 docstring hullName(HullType type)
124 {
125         switch (type) {
126                 case hullNone:       return from_ascii("none");
127                 case hullSimple:     return from_ascii("simple");
128                 case hullEquation:   return from_ascii("equation");
129                 case hullEqnArray:   return from_ascii("eqnarray");
130                 case hullAlign:      return from_ascii("align");
131                 case hullAlignAt:    return from_ascii("alignat");
132                 case hullXAlignAt:   return from_ascii("xalignat");
133                 case hullXXAlignAt:  return from_ascii("xxalignat");
134                 case hullMultline:   return from_ascii("multline");
135                 case hullGather:     return from_ascii("gather");
136                 case hullFlAlign:    return from_ascii("flalign");
137                 default:
138                         lyxerr << "unknown hull type '" << type << "'" << endl;
139                         return from_ascii("none");
140         }
141 }
142
143
144 InsetMathHull::InsetMathHull()
145         : InsetMathGrid(1, 1), type_(hullNone), nonum_(1), label_(1),
146           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         initMath();
153         setDefaults();
154 }
155
156
157 InsetMathHull::InsetMathHull(HullType type)
158         : InsetMathGrid(getCols(type), 1), type_(type), nonum_(1), label_(1),
159           preview_(new RenderPreview(this))
160 {
161         initMath();
162         setDefaults();
163 }
164
165
166 InsetMathHull::InsetMathHull(InsetMathHull const & other)
167         : InsetMathGrid(other),
168           type_(other.type_), nonum_(other.nonum_), label_(other.label_),
169           preview_(new RenderPreview(*other.preview_, this))
170 {}
171
172
173 InsetMathHull::~InsetMathHull()
174 {}
175
176
177 Inset * InsetMathHull::clone() const
178 {
179         return new InsetMathHull(*this);
180 }
181
182
183 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
184 {
185         if (this == &other)
186                 return *this;
187         *static_cast<InsetMathGrid*>(this) = InsetMathGrid(other);
188         type_  = other.type_;
189         nonum_ = other.nonum_;
190         label_ = other.label_;
191         preview_.reset(new RenderPreview(*other.preview_, this));
192
193         return *this;
194 }
195
196
197 void InsetMathHull::addToToc(ParConstIterator const & pit) const
198 {
199         if (!buffer_) {
200                 //FIXME: buffer_ should be set at creation for this inset! Problem is
201                 // This inset is created at too many places (see Parser::parse1() in
202                 // MathParser.cpp).
203                 return;
204         }
205
206         vector<docstring> labels;
207         getLabelList(labels);
208         if (labels.empty())
209                 return;
210
211         Toc & toc = buffer().tocBackend().toc("equation");
212         toc.push_back(TocItem(pit, 0, labels[0]));
213 }
214
215
216 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
217 {
218         if (use_preview_) {
219                 edit(cur, true);
220                 return this;
221         }
222         return InsetMathNest::editXY(cur, x, y);
223 }
224
225
226 InsetMath::mode_type InsetMathHull::currentMode() const
227 {
228         if (type_ == hullNone)
229                 return UNDECIDED_MODE;
230         // definitely math mode ...
231         return MATH_MODE;
232 }
233
234
235 bool InsetMathHull::idxFirst(Cursor & cur) const
236 {
237         cur.idx() = 0;
238         cur.pos() = 0;
239         return true;
240 }
241
242
243 bool InsetMathHull::idxLast(Cursor & cur) const
244 {
245         cur.idx() = nargs() - 1;
246         cur.pos() = cur.lastpos();
247         return true;
248 }
249
250
251 char InsetMathHull::defaultColAlign(col_type col)
252 {
253         if (type_ == hullEqnArray)
254                 return "rcl"[col];
255         if (type_ == hullGather)
256                 return 'c';
257         if (type_ >= hullAlign)
258                 return "rl"[col & 1];
259         return 'c';
260 }
261
262
263 int InsetMathHull::defaultColSpace(col_type col)
264 {
265         if (type_ == hullAlign || type_ == hullAlignAt)
266                 return 0;
267         if (type_ == hullXAlignAt)
268                 return (col & 1) ? 20 : 0;
269         if (type_ == hullXXAlignAt || type_ == hullFlAlign)
270                 return (col & 1) ? 40 : 0;
271         return 0;
272 }
273
274
275 docstring InsetMathHull::standardFont() const
276 {
277         return from_ascii(type_ == hullNone ? "lyxnochange" : "mathnormal");
278 }
279
280
281 bool InsetMathHull::previewState(BufferView * bv) const
282 {
283         if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
284                 graphics::PreviewImage const * pimage =
285                         preview_->getPreviewImage(bv->buffer());
286                 return pimage && pimage->image();
287         }
288         return false;
289 }
290
291
292 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
293 {
294         if (previewState(mi.base.bv)) {
295                 preview_->metrics(mi, dim);
296                 // insert a one pixel gap in front of the formula
297                 dim.wid += 1;
298                 if (display())
299                         dim.des += displayMargin();
300                 // Cache the inset dimension. 
301                 setDimCache(mi, dim);
302                 return;
303         }
304
305         FontSetChanger dummy1(mi.base, standardFont());
306         StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
307
308         // let the cells adjust themselves
309         InsetMathGrid::metrics(mi, dim);
310
311         if (display()) {
312                 dim.asc += displayMargin();
313                 dim.des += displayMargin();
314         }
315
316         if (numberedType()) {
317                 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
318                 int l = 0;
319                 for (row_type row = 0; row < nrows(); ++row)
320                         l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
321
322                 if (l)
323                         dim.wid += 30 + l;
324         }
325
326         // make it at least as high as the current font
327         int asc = 0;
328         int des = 0;
329         math_font_max_dim(mi.base.font, asc, des);
330         dim.asc = max(dim.asc, asc);
331         dim.des = max(dim.des, des);
332         // Cache the inset dimension.
333         // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
334         setDimCache(mi, dim);
335 }
336
337
338 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
339 {
340         use_preview_ = previewState(pi.base.bv);
341         Dimension const dim = dimension(*pi.base.bv);
342
343         // background of mathed under focus is not painted because
344         // selection at the top level of nested inset is difficult to handle.
345         if (!editing(pi.base.bv))
346                 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
347                                 dim.asc + dim.des - 1, Color_mathbg);
348
349         if (use_preview_) {
350                 // one pixel gap in front
351                 preview_->draw(pi, x + 1, y);
352                 setPosCache(pi, x, y);
353                 return;
354         }
355
356         FontSetChanger dummy1(pi.base, standardFont());
357         StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
358         InsetMathGrid::draw(pi, x + 1, y);
359
360         if (numberedType()) {
361                 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
362                 for (row_type row = 0; row < nrows(); ++row) {
363                         int const yy = y + rowinfo_[row].offset_;
364                         FontSetChanger dummy(pi.base, from_ascii("mathrm"));
365                         docstring const nl = nicelabel(row);
366                         pi.draw(xx, yy, nl);
367                 }
368         }
369         setPosCache(pi, x, y);
370 }
371
372
373 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
374 {
375         if (display()) {
376                 InsetMathGrid::metricsT(mi, dim);
377         } else {
378                 odocstringstream os;
379                 WriteStream wi(os, false, true);
380                 write(wi);
381                 dim.wid = os.str().size();
382                 dim.asc = 1;
383                 dim.des = 0;
384         }
385 }
386
387
388 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
389 {
390         if (display()) {
391                 InsetMathGrid::drawT(pain, x, y);
392         } else {
393                 odocstringstream os;
394                 WriteStream wi(os, false, true);
395                 write(wi);
396                 pain.draw(x, y, os.str().c_str());
397         }
398 }
399
400
401 namespace {
402
403 docstring const latex_string(InsetMathHull const & inset)
404 {
405         odocstringstream ls;
406         WriteStream wi(ls, false, false);
407         inset.write(wi);
408         return ls.str();
409 }
410
411 } // namespace anon
412
413
414 void InsetMathHull::addPreview(graphics::PreviewLoader & ploader) const
415 {
416         if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
417                 docstring const snippet = latex_string(*this);
418                 preview_->addPreview(snippet, ploader);
419         }
420 }
421
422
423 bool InsetMathHull::notifyCursorLeaves(Cursor const & /*old*/, Cursor & cur)
424 {
425         if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
426                 Buffer const & buffer = cur.buffer();
427                 docstring const snippet = latex_string(*this);
428                 preview_->addPreview(snippet, buffer);
429                 preview_->startLoading(buffer);
430                 cur.updateFlags(Update::Force);
431         }
432         return false;
433 }
434
435
436 docstring InsetMathHull::label(row_type row) const
437 {
438         BOOST_ASSERT(row < nrows());
439         return label_[row];
440 }
441
442
443 void InsetMathHull::label(row_type row, docstring const & label)
444 {
445         //lyxerr << "setting label '" << label << "' for row " << row << endl;
446         label_[row] = label;
447 }
448
449
450 void InsetMathHull::numbered(row_type row, bool num)
451 {
452         nonum_[row] = !num;
453         if (nonum_[row])
454                 label_[row].clear();
455 }
456
457
458 bool InsetMathHull::numbered(row_type row) const
459 {
460         return !nonum_[row];
461 }
462
463
464 bool InsetMathHull::ams() const
465 {
466         return
467                 type_ == hullAlign ||
468                 type_ == hullFlAlign ||
469                 type_ == hullMultline ||
470                 type_ == hullGather ||
471                 type_ == hullAlignAt ||
472                 type_ == hullXAlignAt ||
473                 type_ == hullXXAlignAt;
474 }
475
476
477 Inset::DisplayType InsetMathHull::display() const
478 {
479         return (type_ != hullSimple && type_ != hullNone) ? AlignCenter : Inline;
480 }
481
482
483 void InsetMathHull::getLabelList(vector<docstring> & labels) const
484 {
485         for (row_type row = 0; row < nrows(); ++row)
486                 if (!label_[row].empty() && nonum_[row] != 1)
487                         labels.push_back(label_[row]);
488 }
489
490
491 bool InsetMathHull::numberedType() const
492 {
493         if (type_ == hullNone)
494                 return false;
495         if (type_ == hullSimple)
496                 return false;
497         if (type_ == hullXXAlignAt)
498                 return false;
499         for (row_type row = 0; row < nrows(); ++row)
500                 if (!nonum_[row])
501                         return true;
502         return false;
503 }
504
505
506 void InsetMathHull::validate(LaTeXFeatures & features) const
507 {
508         if (ams())
509                 features.require("amsmath");
510
511
512         // Validation is necessary only if not using AMS math.
513         // To be safe, we will always run mathedvalidate.
514         //if (features.amsstyle)
515         //  return;
516
517         features.require("boldsymbol");
518         //features.binom      = true;
519
520         InsetMathGrid::validate(features);
521 }
522
523
524 void InsetMathHull::header_write(WriteStream & os) const
525 {
526         bool n = numberedType();
527
528         switch(type_) {
529         case hullNone:
530                 break;
531
532         case hullSimple:
533                 os << '$';
534                 if (cell(0).empty())
535                         os << ' ';
536                 break;
537
538         case hullEquation:
539                 if (n)
540                         os << "\\begin{equation" << star(n) << "}\n";
541                 else
542                         os << "\\[\n";
543                 break;
544
545         case hullEqnArray:
546         case hullAlign:
547         case hullFlAlign:
548         case hullGather:
549         case hullMultline:
550                 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
551                 break;
552
553         case hullAlignAt:
554         case hullXAlignAt:
555                 os << "\\begin{" << hullName(type_) << star(n) << '}'
556                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
557                 break;
558
559         case hullXXAlignAt:
560                 os << "\\begin{" << hullName(type_) << '}'
561                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
562                 break;
563
564         default:
565                 os << "\\begin{unknown" << star(n) << '}';
566                 break;
567         }
568 }
569
570
571 void InsetMathHull::footer_write(WriteStream & os) const
572 {
573         bool n = numberedType();
574
575         switch(type_) {
576         case hullNone:
577                 os << "\n";
578                 break;
579
580         case hullSimple:
581                 os << '$';
582                 break;
583
584         case hullEquation:
585                 if (n)
586                         os << "\\end{equation" << star(n) << "}\n";
587                 else
588                         os << "\\]\n";
589                 break;
590
591         case hullEqnArray:
592         case hullAlign:
593         case hullFlAlign:
594         case hullAlignAt:
595         case hullXAlignAt:
596         case hullGather:
597         case hullMultline:
598                 os << "\\end{" << hullName(type_) << star(n) << "}\n";
599                 break;
600
601         case hullXXAlignAt:
602                 os << "\\end{" << hullName(type_) << "}\n";
603                 break;
604
605         default:
606                 os << "\\end{unknown" << star(n) << '}';
607                 break;
608         }
609 }
610
611
612 bool InsetMathHull::rowChangeOK() const
613 {
614         return
615                 type_ == hullEqnArray || type_ == hullAlign ||
616                 type_ == hullFlAlign || type_ == hullAlignAt ||
617                 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
618                 type_ == hullGather || type_ == hullMultline;
619 }
620
621
622 bool InsetMathHull::colChangeOK() const
623 {
624         return
625                 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
626                 type_ == hullXAlignAt || type_ == hullXXAlignAt;
627 }
628
629
630 void InsetMathHull::addRow(row_type row)
631 {
632         if (!rowChangeOK())
633                 return;
634         nonum_.insert(nonum_.begin() + row + 1, !numberedType());
635         label_.insert(label_.begin() + row + 1, docstring());
636         InsetMathGrid::addRow(row);
637 }
638
639
640 void InsetMathHull::swapRow(row_type row)
641 {
642         if (nrows() <= 1)
643                 return;
644         if (row + 1 == nrows())
645                 --row;
646         swap(nonum_[row], nonum_[row + 1]);
647         swap(label_[row], label_[row + 1]);
648         InsetMathGrid::swapRow(row);
649 }
650
651
652 void InsetMathHull::delRow(row_type row)
653 {
654         if (nrows() <= 1 || !rowChangeOK())
655                 return;
656         InsetMathGrid::delRow(row);
657         // The last dummy row has no number info nor a label.
658         // Test nrows() + 1 because we have already erased the row.
659         if (row == nrows() + 1)
660                 row--;
661         nonum_.erase(nonum_.begin() + row);
662         label_.erase(label_.begin() + row);
663 }
664
665
666 void InsetMathHull::addCol(col_type col)
667 {
668         if (!colChangeOK())
669                 return;
670         InsetMathGrid::addCol(col);
671 }
672
673
674 void InsetMathHull::delCol(col_type col)
675 {
676         if (ncols() <= 1 || !colChangeOK())
677                 return;
678         InsetMathGrid::delCol(col);
679 }
680
681
682 docstring InsetMathHull::nicelabel(row_type row) const
683 {
684         if (nonum_[row])
685                 return docstring();
686         if (label_[row].empty())
687                 return from_ascii("(#)");
688         return '(' + label_[row] + ')';
689 }
690
691
692 void InsetMathHull::glueall()
693 {
694         MathData ar;
695         for (idx_type i = 0; i < nargs(); ++i)
696                 ar.append(cell(i));
697         *this = InsetMathHull(hullSimple);
698         cell(0) = ar;
699         setDefaults();
700 }
701
702
703 void InsetMathHull::splitTo2Cols()
704 {
705         BOOST_ASSERT(ncols() == 1);
706         InsetMathGrid::addCol(1);
707         for (row_type row = 0; row < nrows(); ++row) {
708                 idx_type const i = 2 * row;
709                 pos_type pos = firstRelOp(cell(i));
710                 cell(i + 1) = MathData(cell(i).begin() + pos, cell(i).end());
711                 cell(i).erase(pos, cell(i).size());
712         }
713 }
714
715
716 void InsetMathHull::splitTo3Cols()
717 {
718         BOOST_ASSERT(ncols() < 3);
719         if (ncols() < 2)
720                 splitTo2Cols();
721         InsetMathGrid::addCol(2);
722         for (row_type row = 0; row < nrows(); ++row) {
723                 idx_type const i = 3 * row + 1;
724                 if (cell(i).size()) {
725                         cell(i + 1) = MathData(cell(i).begin() + 1, cell(i).end());
726                         cell(i).erase(1, cell(i).size());
727                 }
728         }
729 }
730
731
732 void InsetMathHull::changeCols(col_type cols)
733 {
734         if (ncols() == cols)
735                 return;
736         else if (ncols() < cols) {
737                 // split columns
738                 if (cols < 3)
739                         splitTo2Cols();
740                 else {
741                         splitTo3Cols();
742                         while (ncols() < cols)
743                                 InsetMathGrid::addCol(ncols());
744                 }
745                 return;
746         }
747
748         // combine columns
749         for (row_type row = 0; row < nrows(); ++row) {
750                 idx_type const i = row * ncols();
751                 for (col_type col = cols; col < ncols(); ++col) {
752                         cell(i + cols - 1).append(cell(i + col));
753                 }
754         }
755         // delete columns
756         while (ncols() > cols) {
757                 InsetMathGrid::delCol(ncols() - 1);
758         }
759 }
760
761
762 HullType InsetMathHull::getType() const
763 {
764         return type_;
765 }
766
767
768 void InsetMathHull::setType(HullType type)
769 {
770         type_ = type;
771         setDefaults();
772 }
773
774
775 void InsetMathHull::mutate(HullType newtype)
776 {
777         //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
778
779         // we try to move along the chain
780         // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
781         //                                     ^                                     |
782         //                                     +-------------------------------------+
783         // we use eqnarray as intermediate type for mutations that are not
784         // directly supported because it handles labels and numbering for
785         // "down mutation".
786
787         if (newtype == type_) {
788                 // done
789         }
790
791         else if (newtype < hullNone) {
792                 // unknown type
793                 dump();
794         }
795
796         else if (type_ == hullNone) {
797                 setType(hullSimple);
798                 numbered(0, false);
799                 mutate(newtype);
800         }
801
802         else if (type_ == hullSimple) {
803                 if (newtype == hullNone) {
804                         setType(hullNone);
805                         numbered(0, false);
806                 } else {
807                         setType(hullEquation);
808                         numbered(0, false);
809                         mutate(newtype);
810                 }
811         }
812
813         else if (type_ == hullEquation) {
814                 if (newtype < type_) {
815                         setType(hullSimple);
816                         numbered(0, false);
817                         mutate(newtype);
818                 } else if (newtype == hullEqnArray) {
819                         // split it "nicely" on the first relop
820                         splitTo3Cols();
821                         setType(hullEqnArray);
822                 } else if (newtype == hullMultline || newtype == hullGather) {
823                         setType(newtype);
824                 } else {
825                         // split it "nicely"
826                         splitTo2Cols();
827                         setType(hullAlign);
828                         mutate(newtype);
829                 }
830         }
831
832         else if (type_ == hullEqnArray) {
833                 if (newtype < type_) {
834                         // set correct (no)numbering
835                         bool allnonum = true;
836                         for (row_type row = 0; row < nrows(); ++row)
837                                 if (!nonum_[row])
838                                         allnonum = false;
839
840                         // set first non-empty label
841                         docstring label;
842                         for (row_type row = 0; row < nrows(); ++row) {
843                                 if (!label_[row].empty()) {
844                                         label = label_[row];
845                                         break;
846                                 }
847                         }
848
849                         glueall();
850                         nonum_[0] = allnonum;
851                         label_[0] = label;
852                         mutate(newtype);
853                 } else { // align & Co.
854                         changeCols(2);
855                         setType(hullAlign);
856                         mutate(newtype);
857                 }
858         }
859
860         else if (type_ ==  hullAlign || type_ == hullAlignAt ||
861                  type_ == hullXAlignAt || type_ == hullFlAlign) {
862                 if (newtype < hullAlign) {
863                         changeCols(3);
864                         setType(hullEqnArray);
865                         mutate(newtype);
866                 } else if (newtype == hullGather || newtype == hullMultline) {
867                         changeCols(1);
868                         setType(newtype);
869                 } else if (newtype ==   hullXXAlignAt) {
870                         for (row_type row = 0; row < nrows(); ++row)
871                                 numbered(row, false);
872                         setType(newtype);
873                 } else {
874                         setType(newtype);
875                 }
876         }
877
878         else if (type_ == hullXXAlignAt) {
879                 for (row_type row = 0; row < nrows(); ++row)
880                         numbered(row, false);
881                 if (newtype < hullAlign) {
882                         changeCols(3);
883                         setType(hullEqnArray);
884                         mutate(newtype);
885                 } else if (newtype == hullGather || newtype == hullMultline) {
886                         changeCols(1);
887                         setType(newtype);
888                 } else {
889                         setType(newtype);
890                 }
891         }
892
893         else if (type_ == hullMultline || type_ == hullGather) {
894                 if (newtype == hullGather || newtype == hullMultline)
895                         setType(newtype);
896                 else if (newtype == hullAlign || newtype == hullFlAlign  ||
897                          newtype == hullAlignAt || newtype == hullXAlignAt) {
898                         splitTo2Cols();
899                         setType(newtype);
900                 } else if (newtype ==   hullXXAlignAt) {
901                         splitTo2Cols();
902                         for (row_type row = 0; row < nrows(); ++row)
903                                 numbered(row, false);
904                         setType(newtype);
905                 } else {
906                         splitTo3Cols();
907                         setType(hullEqnArray);
908                         mutate(newtype);
909                 }
910         }
911
912         else {
913                 lyxerr << "mutation from '" << to_utf8(hullName(type_))
914                        << "' to '" << to_utf8(hullName(newtype))
915                        << "' not implemented" << endl;
916         }
917 }
918
919
920 docstring InsetMathHull::eolString(row_type row, bool emptyline, bool fragile) const
921 {
922         docstring res;
923         if (numberedType()) {
924                 if (!label_[row].empty() && !nonum_[row])
925                         res += "\\label{" + label_[row] + '}';
926                 if (nonum_[row] && (type_ != hullMultline))
927                         res += "\\nonumber ";
928         }
929         return res + InsetMathGrid::eolString(row, emptyline, fragile);
930 }
931
932
933 void InsetMathHull::write(WriteStream & os) const
934 {
935         header_write(os);
936         InsetMathGrid::write(os);
937         footer_write(os);
938 }
939
940
941 void InsetMathHull::normalize(NormalStream & os) const
942 {
943         os << "[formula " << hullName(type_) << ' ';
944         InsetMathGrid::normalize(os);
945         os << "] ";
946 }
947
948
949 void InsetMathHull::mathmlize(MathStream & os) const
950 {
951         InsetMathGrid::mathmlize(os);
952 }
953
954
955 void InsetMathHull::infoize(odocstream & os) const
956 {
957         os << "Type: " << hullName(type_);
958 }
959
960
961 void InsetMathHull::check() const
962 {
963         BOOST_ASSERT(nonum_.size() == nrows());
964         BOOST_ASSERT(label_.size() == nrows());
965 }
966
967
968 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
969 {
970         docstring dlang;
971         docstring extra;
972         idocstringstream iss(func.argument());
973         iss >> dlang >> extra;
974         if (extra.empty())
975                 extra = from_ascii("noextra");
976         string const lang = to_ascii(dlang);
977
978         // FIXME: temporarily disabled
979         //if (cur.selection()) {
980         //      MathData ar;
981         //      selGet(cur.ar);
982         //      lyxerr << "use selection: " << ar << endl;
983         //      insert(pipeThroughExtern(lang, extra, ar));
984         //      return;
985         //}
986
987         MathData eq;
988         eq.push_back(MathAtom(new InsetMathChar('=')));
989
990         // go to first item in line
991         cur.idx() -= cur.idx() % ncols();
992         cur.pos() = 0;
993
994         if (getType() == hullSimple) {
995                 size_type pos = cur.cell().find_last(eq);
996                 MathData ar;
997                 if (cur.inMathed() && cur.selection()) {
998                         asArray(grabAndEraseSelection(cur), ar);
999                 } else if (pos == cur.cell().size()) {
1000                         ar = cur.cell();
1001                         lyxerr << "use whole cell: " << ar << endl;
1002                 } else {
1003                         ar = MathData(cur.cell().begin() + pos + 1, cur.cell().end());
1004                         lyxerr << "use partial cell form pos: " << pos << endl;
1005                 }
1006                 cur.cell().append(eq);
1007                 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1008                 cur.pos() = cur.lastpos();
1009                 return;
1010         }
1011
1012         if (getType() == hullEquation) {
1013                 lyxerr << "use equation inset" << endl;
1014                 mutate(hullEqnArray);
1015                 MathData & ar = cur.cell();
1016                 lyxerr << "use cell: " << ar << endl;
1017                 ++cur.idx();
1018                 cur.cell() = eq;
1019                 ++cur.idx();
1020                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1021                 // move to end of line
1022                 cur.pos() = cur.lastpos();
1023                 return;
1024         }
1025
1026         {
1027                 lyxerr << "use eqnarray" << endl;
1028                 cur.idx() += 2 - cur.idx() % ncols();
1029                 cur.pos() = 0;
1030                 MathData ar = cur.cell();
1031                 lyxerr << "use cell: " << ar << endl;
1032                 // FIXME: temporarily disabled
1033                 addRow(cur.row());
1034                 ++cur.idx();
1035                 ++cur.idx();
1036                 cur.cell() = eq;
1037                 ++cur.idx();
1038                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1039                 cur.pos() = cur.lastpos();
1040         }
1041 }
1042
1043
1044 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1045 {
1046         //lyxerr << "action: " << cmd.action << endl;
1047         switch (cmd.action) {
1048
1049         case LFUN_FINISHED_BACKWARD:
1050         case LFUN_FINISHED_FORWARD:
1051         case LFUN_FINISHED_RIGHT:
1052         case LFUN_FINISHED_LEFT:
1053                 //lyxerr << "action: " << cmd.action << endl;
1054                 InsetMathGrid::doDispatch(cur, cmd);
1055                 cur.undispatched();
1056                 break;
1057
1058         case LFUN_BREAK_PARAGRAPH:
1059                 // just swallow this
1060                 break;
1061
1062         case LFUN_NEW_LINE:
1063                 // some magic for the common case
1064                 if (type_ == hullSimple || type_ == hullEquation) {
1065                         cur.recordUndoInset();
1066                         bool const align =
1067                                 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1068                         mutate(align ? hullAlign : hullEqnArray);
1069                         cur.idx() = nrows() * ncols() - 1;
1070                         cur.pos() = cur.lastpos();
1071                 }
1072                 InsetMathGrid::doDispatch(cur, cmd);
1073                 break;
1074
1075         case LFUN_MATH_NUMBER_TOGGLE: {
1076                 //lyxerr << "toggling all numbers" << endl;
1077                 cur.recordUndoInset();
1078                 bool old = numberedType();
1079                 if (type_ == hullMultline)
1080                         numbered(nrows() - 1, !old);
1081                 else
1082                         for (row_type row = 0; row < nrows(); ++row)
1083                                 numbered(row, !old);
1084                 
1085                 cur.message(old ? _("No number") : _("Number"));
1086                 break;
1087         }
1088
1089         case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1090                 cur.recordUndoInset();
1091                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1092                 bool old = numbered(r);
1093                 cur.message(old ? _("No number") : _("Number"));
1094                 numbered(r, !old);
1095                 break;
1096         }
1097
1098         case LFUN_LABEL_INSERT: {
1099                 cur.recordUndoInset();
1100                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1101                 docstring old_label = label(r);
1102                 docstring const default_label = from_ascii(
1103                         (lyxrc.label_init_length >= 0) ? "eq:" : "");
1104                 if (old_label.empty())
1105                         old_label = default_label;
1106
1107                 InsetCommandParams p(LABEL_CODE);
1108                 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1109                 string const data = InsetCommandMailer::params2string("label", p);
1110
1111                 if (cmd.argument().empty())
1112                         cur.bv().showDialog("label", data);
1113                 else {
1114                         FuncRequest fr(LFUN_INSET_INSERT, data);
1115                         dispatch(cur, fr);
1116                 }
1117                 break;
1118         }
1119
1120         case LFUN_INSET_INSERT: {
1121                 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1122                 string const name = cmd.getArg(0);
1123                 if (name == "label") {
1124                         InsetCommandParams p(LABEL_CODE);
1125                         InsetCommandMailer::string2params(name, to_utf8(cmd.argument()), p);
1126                         docstring str = p["name"];
1127                         cur.recordUndoInset();
1128                         row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1129                         str = trim(str);
1130                         if (!str.empty())
1131                                 numbered(r, true);
1132                         docstring old = label(r);
1133                         if (str != old) {
1134                                 cur.bv().buffer().changeRefsIfUnique(old, str,
1135                                                         REF_CODE);
1136                                 label(r, str);
1137                         }
1138                         break;
1139                 }
1140                 InsetMathGrid::doDispatch(cur, cmd);
1141                 return;
1142         }
1143
1144         case LFUN_MATH_EXTERN:
1145                 cur.recordUndoInset();
1146                 doExtern(cur, cmd);
1147                 break;
1148
1149         case LFUN_MATH_MUTATE: {
1150                 cur.recordUndoInset();
1151                 row_type row = cur.row();
1152                 col_type col = cur.col();
1153                 mutate(hullType(cmd.argument()));
1154                 cur.idx() = row * ncols() + col;
1155                 if (cur.idx() > cur.lastidx()) {
1156                         cur.idx() = cur.lastidx();
1157                         cur.pos() = cur.lastpos();
1158                 }
1159                 if (cur.pos() > cur.lastpos())
1160                         cur.pos() = cur.lastpos();
1161                 
1162                 // FIXME: find some more clever handling of the selection,
1163                 // i.e. preserve it.
1164                 cur.clearSelection();
1165                 //cur.dispatched(FINISHED);
1166                 break;
1167         }
1168
1169         case LFUN_MATH_DISPLAY: {
1170                 cur.recordUndoInset();
1171                 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1172                 cur.idx() = 0;
1173                 cur.pos() = cur.lastpos();
1174                 //cur.dispatched(FINISHED);
1175                 break;
1176         }
1177
1178         default:
1179                 InsetMathGrid::doDispatch(cur, cmd);
1180                 break;
1181         }
1182 }
1183
1184
1185 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1186                 FuncStatus & status) const
1187 {
1188         switch (cmd.action) {
1189         case LFUN_FINISHED_BACKWARD:
1190         case LFUN_FINISHED_FORWARD:
1191         case LFUN_FINISHED_RIGHT:
1192         case LFUN_FINISHED_LEFT:
1193         case LFUN_UP:
1194         case LFUN_DOWN:
1195         case LFUN_NEW_LINE:
1196         case LFUN_MATH_EXTERN:
1197         case LFUN_MATH_MUTATE:
1198         case LFUN_MATH_DISPLAY:
1199                 // we handle these
1200                 status.enabled(true);
1201                 return true;
1202         case LFUN_MATH_NUMBER_TOGGLE:
1203                 // FIXME: what is the right test, this or the one of
1204                 // LABEL_INSERT?
1205                 status.enabled(display());
1206                 status.setOnOff(numberedType());
1207                 return true;
1208         case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1209                 // FIXME: what is the right test, this or the one of
1210                 // LABEL_INSERT?
1211                 status.enabled(display());
1212                 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1213                 status.setOnOff(numbered(r));
1214                 return true;
1215         }
1216         case LFUN_LABEL_INSERT:
1217                 status.enabled(type_ != hullSimple);
1218                 return true;
1219         case LFUN_INSET_INSERT:
1220                 if (cmd.getArg(0) == "label") {
1221                         status.enabled(type_ != hullSimple);
1222                         return true;
1223                 }
1224                 return InsetMathGrid::getStatus(cur, cmd, status);
1225         case LFUN_TABULAR_FEATURE: {
1226                 istringstream is(to_utf8(cmd.argument()));
1227                 string s;
1228                 is >> s;
1229                 if (!rowChangeOK()
1230                     && (s == "append-row"
1231                         || s == "delete-row"
1232                         || s == "copy-row")) {
1233                         status.message(bformat(
1234                                 from_utf8(N_("Can't change number of rows in '%1$s'")),
1235                                 hullName(type_)));
1236                         status.enabled(false);
1237                         return true;
1238                 }
1239                 if (!colChangeOK()
1240                     && (s == "append-column"
1241                         || s == "delete-column"
1242                         || s == "copy-column")) {
1243                         status.message(bformat(
1244                                 from_utf8(N_("Can't change number of columns in '%1$s'")),
1245                                 hullName(type_)));
1246                         status.enabled(false);
1247                         return true;
1248                 }
1249                 if ((type_ == hullSimple
1250                   || type_ == hullEquation
1251                   || type_ == hullNone) &&
1252                     (s == "add-hline-above" || s == "add-hline-below")) {
1253                         status.message(bformat(
1254                                 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1255                                 hullName(type_)));
1256                         status.enabled(false);
1257                         return true;
1258                 }
1259                 if (s == "add-vline-left" || s == "add-vline-right") {
1260                         status.message(bformat(
1261                                 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1262                                 hullName(type_)));
1263                         status.enabled(false);
1264                         return true;
1265                 }
1266                 if (s == "valign-top" || s == "valign-middle"
1267                  || s == "valign-bottom" || s == "align-left"
1268                  || s == "align-center" || s == "align-right") {
1269                         status.enabled(false);
1270                         return true;
1271                 }
1272                 return InsetMathGrid::getStatus(cur, cmd, status);
1273         }
1274         default:
1275                 return InsetMathGrid::getStatus(cur, cmd, status);
1276         }
1277
1278         // This cannot really happen, but inserted to shut-up gcc
1279         return InsetMathGrid::getStatus(cur, cmd, status);
1280 }
1281
1282
1283 /////////////////////////////////////////////////////////////////////
1284
1285
1286
1287 // simply scrap this function if you want
1288 void InsetMathHull::mutateToText()
1289 {
1290 #if 0
1291         // translate to latex
1292         ostringstream os;
1293         latex(NULL, os, false, false);
1294         string str = os.str();
1295
1296         // insert this text
1297         Text * lt = view_->cursor().innerText();
1298         string::const_iterator cit = str.begin();
1299         string::const_iterator end = str.end();
1300         for (; cit != end; ++cit)
1301                 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1302
1303         // remove ourselves
1304         //dispatch(LFUN_ESCAPE);
1305 #endif
1306 }
1307
1308
1309 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1310         docstring const & font)
1311 {
1312         // this whole function is a hack and won't work for incremental font
1313         // changes...
1314         cur.recordUndo();
1315         if (cur.inset().asInsetMath()->name() == font)
1316                 cur.handleFont(to_utf8(font));
1317         else {
1318                 cur.handleNest(createInsetMath(font));
1319                 cur.insert(arg);
1320         }
1321 }
1322
1323
1324 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1325 {
1326         cur.recordUndo();
1327         Font font;
1328         bool b;
1329         font.fromString(to_utf8(arg), b);
1330         if (font.fontInfo().color() != Color_inherit) {
1331                 MathAtom at = MathAtom(new InsetMathColor(true, font.fontInfo().color()));
1332                 cur.handleNest(at, 0);
1333         }
1334 }
1335
1336
1337 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1338 {
1339         cur.push(*this);
1340         bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT || 
1341                 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1342         enter_front ? idxFirst(cur) : idxLast(cur);
1343         // The inset formula dimension is not necessarily the same as the
1344         // one of the instant preview image, so we have to indicate to the
1345         // BufferView that a metrics update is needed.
1346         cur.updateFlags(Update::Force);
1347 }
1348
1349
1350 docstring InsetMathHull::editMessage() const
1351 {
1352         return _("Math editor mode");
1353 }
1354
1355
1356 void InsetMathHull::revealCodes(Cursor & cur) const
1357 {
1358         if (!cur.inMathed())
1359                 return;
1360         odocstringstream os;
1361         cur.info(os);
1362         cur.message(os.str());
1363 /*
1364         // write something to the minibuffer
1365         // translate to latex
1366         cur.markInsert(bv);
1367         ostringstream os;
1368         write(NULL, os);
1369         string str = os.str();
1370         cur.markErase(bv);
1371         string::size_type pos = 0;
1372         string res;
1373         for (string::iterator it = str.begin(); it != str.end(); ++it) {
1374                 if (*it == '\n')
1375                         res += ' ';
1376                 else if (*it == '\0') {
1377                         res += "  -X-  ";
1378                         pos = it - str.begin();
1379                 }
1380                 else
1381                         res += *it;
1382         }
1383         if (pos > 30)
1384                 res = res.substr(pos - 30);
1385         if (res.size() > 60)
1386                 res = res.substr(0, 60);
1387         cur.message(res);
1388 */
1389 }
1390
1391
1392 InsetCode InsetMathHull::lyxCode() const
1393 {
1394         return MATH_CODE;
1395 }
1396
1397
1398 /////////////////////////////////////////////////////////////////////
1399
1400
1401 #if 0
1402 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1403                                      bool, bool)
1404 {
1405         // FIXME: completely broken
1406         static InsetMathHull * lastformula = 0;
1407         static CursorBase current = DocIterator(ibegin(nucleus()));
1408         static MathData ar;
1409         static string laststr;
1410
1411         if (lastformula != this || laststr != str) {
1412                 //lyxerr << "reset lastformula to " << this << endl;
1413                 lastformula = this;
1414                 laststr = str;
1415                 current = ibegin(nucleus());
1416                 ar.clear();
1417                 mathed_parse_cell(ar, str);
1418         } else {
1419                 increment(current);
1420         }
1421         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1422
1423         for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1424                 CursorSlice & top = it.back();
1425                 MathData const & a = top.asInsetMath()->cell(top.idx_);
1426                 if (a.matchpart(ar, top.pos_)) {
1427                         bv->cursor().setSelection(it, ar.size());
1428                         current = it;
1429                         top.pos_ += ar.size();
1430                         bv->update();
1431                         return true;
1432                 }
1433         }
1434
1435         //lyxerr << "not found!" << endl;
1436         lastformula = 0;
1437         return false;
1438 }
1439 #endif
1440
1441
1442 void InsetMathHull::write(ostream & os) const
1443 {
1444         odocstringstream oss;
1445         WriteStream wi(oss, false, false);
1446         oss << "Formula ";
1447         write(wi);
1448         os << to_utf8(oss.str());
1449 }
1450
1451
1452 void InsetMathHull::read(Lexer & lex)
1453 {
1454         MathAtom at;
1455         mathed_parse_normal(at, lex);
1456         operator=(*at->asHullInset());
1457 }
1458
1459
1460 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1461 {
1462         if (0 && display()) {
1463                 Dimension dim;
1464                 TextMetricsInfo mi;
1465                 metricsT(mi, dim);
1466                 TextPainter tpain(dim.width(), dim.height());
1467                 drawT(tpain, 0, dim.ascent());
1468                 tpain.show(os, 3);
1469                 // reset metrics cache to "real" values
1470                 //metrics();
1471                 return tpain.textheight();
1472         } else {
1473                 odocstringstream oss;
1474                 WriteStream wi(oss, false, true);
1475                 wi << cell(0);
1476
1477                 docstring const str = oss.str();
1478                 os << str;
1479                 return str.size();
1480         }
1481 }
1482
1483
1484 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1485 {
1486         MathStream ms(os);
1487         int res = 0;
1488         docstring name;
1489         if (getType() == hullSimple)
1490                 name = from_ascii("inlineequation");
1491         else
1492                 name = from_ascii("informalequation");
1493
1494         docstring bname = name;
1495         if (!label(0).empty())
1496                 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1497
1498         ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1499
1500         odocstringstream ls;
1501         if (runparams.flavor == OutputParams::XML) {
1502                 ms << MTag("alt role='tex' ");
1503                 // Workaround for db2latex: db2latex always includes equations with
1504                 // \ensuremath{} or \begin{display}\end{display}
1505                 // so we strip LyX' math environment
1506                 WriteStream wi(ls, false, false);
1507                 InsetMathGrid::write(wi);
1508                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
1509                 ms << ETag("alt");
1510                 ms << MTag("math");
1511                 ms << ETag("alt");
1512                 ms << MTag("math");
1513                 InsetMathGrid::mathmlize(ms);
1514                 ms << ETag("math");
1515         } else {
1516                 ms << MTag("alt role='tex'");
1517                 res = latex(ls, runparams);
1518                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
1519                 ms << ETag("alt");
1520         }
1521
1522         ms << from_ascii("<graphic fileref=\"eqn/");
1523         if (!label(0).empty())
1524                 ms << sgml::cleanID(buffer(), runparams, label(0));
1525         else
1526                 ms << sgml::uniqueID(from_ascii("anon"));
1527
1528         if (runparams.flavor == OutputParams::XML)
1529                 ms << from_ascii("\"/>");
1530         else
1531                 ms << from_ascii("\">");
1532
1533         ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1534
1535         return ms.line() + res;
1536 }
1537
1538
1539 void InsetMathHull::textString(odocstream & os) const
1540 {
1541         plaintext(os, OutputParams(0));
1542 }
1543
1544
1545 } // namespace lyx