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