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