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