]> git.lyx.org Git - features.git/blob - src/mathed/InsetMathHull.C
Output docbook as utf8. Probably quite a bit more work needed, but then help form...
[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 "graphics/PreviewImage.h"
54 #include "graphics/PreviewLoader.h"
55
56 #include "support/lyxlib.h"
57 #include "support/lstrings.h"
58
59 #include <boost/bind.hpp>
60
61 #include <sstream>
62
63 using lyx::docstring;
64 using lyx::odocstream;
65 using lyx::odocstringstream;
66
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                         docstring const nl = nicelabel(row);
354                         pi.draw(xx, yy, nl);
355                 }
356         }
357         setPosCache(pi, x, y);
358 }
359
360
361 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
362 {
363         if (display()) {
364                 InsetMathGrid::metricsT(mi, dim);
365         } else {
366                 odocstringstream os;
367                 WriteStream wi(os, false, true);
368                 write(wi);
369                 dim.wid = os.str().size();
370                 dim.asc = 1;
371                 dim.des = 0;
372         }
373 }
374
375
376 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
377 {
378         if (display()) {
379                 InsetMathGrid::drawT(pain, x, y);
380         } else {
381                 odocstringstream os;
382                 WriteStream wi(os, false, true);
383                 write(wi);
384                 pain.draw(x, y, os.str().c_str());
385         }
386 }
387
388
389 namespace {
390
391 docstring const latex_string(InsetMathHull const & inset)
392 {
393         odocstringstream ls;
394         WriteStream wi(ls, false, false);
395         inset.write(wi);
396         return ls.str();
397 }
398
399 } // namespace anon
400
401
402 void InsetMathHull::addPreview(lyx::graphics::PreviewLoader & ploader) const
403 {
404         if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
405                 docstring const snippet = latex_string(*this);
406                 preview_->addPreview(snippet, ploader);
407         }
408 }
409
410
411 bool InsetMathHull::notifyCursorLeaves(LCursor & cur)
412 {
413         if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
414                 Buffer const & buffer = cur.buffer();
415                 docstring const snippet = latex_string(*this);
416                 preview_->addPreview(snippet, buffer);
417                 preview_->startLoading(buffer);
418         }
419         return false;
420 }
421
422
423 string InsetMathHull::label(row_type row) const
424 {
425         BOOST_ASSERT(row < nrows());
426         return label_[row];
427 }
428
429
430 void InsetMathHull::label(row_type row, string const & label)
431 {
432         //lyxerr << "setting label '" << label << "' for row " << row << endl;
433         label_[row] = label;
434 }
435
436
437 void InsetMathHull::numbered(row_type row, bool num)
438 {
439         nonum_[row] = !num;
440 }
441
442
443 bool InsetMathHull::numbered(row_type row) const
444 {
445         return !nonum_[row];
446 }
447
448
449 bool InsetMathHull::ams() const
450 {
451         return
452                 type_ == hullAlign ||
453                 type_ == hullFlAlign ||
454                 type_ == hullMultline ||
455                 type_ == hullGather ||
456                 type_ == hullAlignAt ||
457                 type_ == hullXAlignAt ||
458                 type_ == hullXXAlignAt;
459 }
460
461
462 bool InsetMathHull::display() const
463 {
464         return type_ != hullSimple && type_ != hullNone;
465 }
466
467
468 void InsetMathHull::getLabelList(Buffer const &, vector<docstring> & labels) const
469 {
470         for (row_type row = 0; row < nrows(); ++row)
471                 if (!label_[row].empty() && nonum_[row] != 1)
472                         // FIXME UNICODE
473                         labels.push_back(lyx::from_utf8(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         switch(type_) {
515         case hullNone:
516                 break;
517
518         case hullSimple:
519                 os << '$';
520                 if (cell(0).empty())
521                         os << ' ';
522                 break;
523
524         case hullEquation:
525                 if (n)
526                         os << "\\begin{equation" << star(n) << "}\n";
527                 else
528                         os << "\\[\n";
529                 break;
530
531         case hullEqnArray:
532         case hullAlign:
533         case hullFlAlign:
534         case hullGather:
535         case hullMultline:
536                 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
537                 break;
538
539         case hullAlignAt:
540         case hullXAlignAt:
541                 os << "\\begin{" << hullName(type_) << star(n) << '}'
542                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
543                 break;
544
545         case hullXXAlignAt:
546                 os << "\\begin{" << hullName(type_) << '}'
547                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
548                 break;
549
550         default:
551                 os << "\\begin{unknown" << star(n) << '}';
552                 break;
553         }
554 }
555
556
557 void InsetMathHull::footer_write(WriteStream & os) const
558 {
559         bool n = numberedType();
560
561         switch(type_) {
562         case hullNone:
563                 os << "\n";
564                 break;
565
566         case hullSimple:
567                 os << '$';
568                 break;
569
570         case hullEquation:
571                 if (n)
572                         os << "\\end{equation" << star(n) << "}\n";
573                 else
574                         os << "\\]\n";
575                 break;
576
577         case hullEqnArray:
578         case hullAlign:
579         case hullFlAlign:
580         case hullAlignAt:
581         case hullXAlignAt:
582         case hullGather:
583         case hullMultline:
584                 os << "\\end{" << hullName(type_) << star(n) << "}\n";
585                 break;
586
587         case hullXXAlignAt:
588                 os << "\\end{" << hullName(type_) << "}\n";
589                 break;
590
591         default:
592                 os << "\\end{unknown" << star(n) << '}';
593                 break;
594         }
595 }
596
597
598 bool InsetMathHull::rowChangeOK() const
599 {
600         return
601                 type_ == hullEqnArray || type_ == hullAlign ||
602                 type_ == hullFlAlign || type_ == hullAlignAt ||
603                 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
604                 type_ == hullGather || type_ == hullMultline;
605 }
606
607
608 bool InsetMathHull::colChangeOK() const
609 {
610         return
611                 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
612                 type_ == hullXAlignAt || type_ == hullXXAlignAt;
613 }
614
615
616 void InsetMathHull::addRow(row_type row)
617 {
618         if (!rowChangeOK())
619                 return;
620         nonum_.insert(nonum_.begin() + row + 1, !numberedType());
621         label_.insert(label_.begin() + row + 1, string());
622         InsetMathGrid::addRow(row);
623 }
624
625
626 void InsetMathHull::swapRow(row_type row)
627 {
628         if (nrows() <= 1)
629                 return;
630         if (row + 1 == nrows())
631                 --row;
632         swap(nonum_[row], nonum_[row + 1]);
633         swap(label_[row], label_[row + 1]);
634         InsetMathGrid::swapRow(row);
635 }
636
637
638 void InsetMathHull::delRow(row_type row)
639 {
640         if (nrows() <= 1 || !rowChangeOK())
641                 return;
642         InsetMathGrid::delRow(row);
643         // The last dummy row has no number info nor a label.
644         // Test nrows() + 1 because we have already erased the row.
645         if (row == nrows() + 1)
646                 row--;
647         nonum_.erase(nonum_.begin() + row);
648         label_.erase(label_.begin() + row);
649 }
650
651
652 void InsetMathHull::addCol(col_type col)
653 {
654         if (!colChangeOK())
655                 return;
656         InsetMathGrid::addCol(col);
657 }
658
659
660 void InsetMathHull::delCol(col_type col)
661 {
662         if (ncols() <= 1 || !colChangeOK())
663                 return;
664         InsetMathGrid::delCol(col);
665 }
666
667
668 docstring InsetMathHull::nicelabel(row_type row) const
669 {
670         if (nonum_[row])
671                 return docstring();
672         if (label_[row].empty())
673                 return lyx::from_ascii("(#)");
674         // FIXME UNICODE
675         return lyx::from_utf8('(' + label_[row] + ')');
676 }
677
678
679 void InsetMathHull::glueall()
680 {
681         MathArray ar;
682         for (idx_type i = 0; i < nargs(); ++i)
683                 ar.append(cell(i));
684         *this = InsetMathHull(hullSimple);
685         cell(0) = ar;
686         setDefaults();
687 }
688
689
690 void InsetMathHull::splitTo2Cols()
691 {
692         BOOST_ASSERT(ncols() == 1);
693         InsetMathGrid::addCol(1);
694         for (row_type row = 0; row < nrows(); ++row) {
695                 idx_type const i = 2 * row;
696                 pos_type pos = firstRelOp(cell(i));
697                 cell(i + 1) = MathArray(cell(i).begin() + pos, cell(i).end());
698                 cell(i).erase(pos, cell(i).size());
699         }
700 }
701
702
703 void InsetMathHull::splitTo3Cols()
704 {
705         BOOST_ASSERT(ncols() < 3);
706         if (ncols() < 2)
707                 splitTo2Cols();
708         InsetMathGrid::addCol(1);
709         for (row_type row = 0; row < nrows(); ++row) {
710                 idx_type const i = 3 * row + 1;
711                 if (cell(i).size()) {
712                         cell(i + 1) = MathArray(cell(i).begin() + 1, cell(i).end());
713                         cell(i).erase(1, cell(i).size());
714                 }
715         }
716 }
717
718
719 void InsetMathHull::changeCols(col_type cols)
720 {
721         if (ncols() == cols)
722                 return;
723         else if (ncols() < cols) {
724                 // split columns
725                 if (cols < 3)
726                         splitTo2Cols();
727                 else {
728                         splitTo3Cols();
729                         while (ncols() < cols)
730                                 InsetMathGrid::addCol(ncols() - 1);
731                 }
732                 return;
733         }
734
735         // combine columns
736         for (row_type row = 0; row < nrows(); ++row) {
737                 idx_type const i = row * ncols();
738                 for (col_type col = cols; col < ncols(); ++col) {
739                         cell(i + cols - 1).append(cell(i + col));
740                 }
741         }
742         // delete columns
743         while (ncols() > cols) {
744                 InsetMathGrid::delCol(ncols() - 1);
745         }
746 }
747
748
749 HullType InsetMathHull::getType() const
750 {
751         return type_;
752 }
753
754
755 void InsetMathHull::setType(HullType type)
756 {
757         type_ = type;
758         setDefaults();
759 }
760
761
762 void InsetMathHull::mutate(HullType newtype)
763 {
764         //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
765
766         // we try to move along the chain
767         // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
768         //                                     ^                                     |
769         //                                     +-------------------------------------+
770         // we use eqnarray as intermediate type for mutations that are not
771         // directly supported because it handles labels and numbering for
772         // "down mutation".
773
774         if (newtype == type_) {
775                 // done
776         }
777
778         else if (newtype < hullNone) {
779                 // unknown type
780                 dump();
781         }
782
783         else if (type_ == hullNone) {
784                 setType(hullSimple);
785                 numbered(0, false);
786                 mutate(newtype);
787         }
788
789         else if (type_ == hullSimple) {
790                 if (newtype == hullNone) {
791                         setType(hullNone);
792                         numbered(0, false);
793                 } else {
794                         setType(hullEquation);
795                         numbered(0, false);
796                         mutate(newtype);
797                 }
798         }
799
800         else if (type_ == hullEquation) {
801                 if (newtype < type_) {
802                         setType(hullSimple);
803                         numbered(0, false);
804                         mutate(newtype);
805                 } else if (newtype == hullEqnArray) {
806                         // split it "nicely" on the first relop
807                         splitTo3Cols();
808                         setType(hullEqnArray);
809                 } else if (newtype == hullMultline || newtype == hullGather) {
810                         setType(newtype);
811                 } else {
812                         // split it "nicely"
813                         splitTo2Cols();
814                         setType(hullAlign);
815                         mutate(newtype);
816                 }
817         }
818
819         else if (type_ == hullEqnArray) {
820                 if (newtype < type_) {
821                         // set correct (no)numbering
822                         bool allnonum = true;
823                         for (row_type row = 0; row < nrows(); ++row)
824                                 if (!nonum_[row])
825                                         allnonum = false;
826
827                         // set first non-empty label
828                         string label;
829                         for (row_type row = 0; row < nrows(); ++row) {
830                                 if (!label_[row].empty()) {
831                                         label = label_[row];
832                                         break;
833                                 }
834                         }
835
836                         glueall();
837                         nonum_[0] = allnonum;
838                         label_[0] = label;
839                         mutate(newtype);
840                 } else { // align & Co.
841                         changeCols(2);
842                         setType(hullAlign);
843                         mutate(newtype);
844                 }
845         }
846
847         else if (type_ ==  hullAlign || type_ == hullAlignAt ||
848                  type_ == hullXAlignAt || type_ == hullFlAlign) {
849                 if (newtype < hullAlign) {
850                         changeCols(3);
851                         setType(hullEqnArray);
852                         mutate(newtype);
853                 } else if (newtype == hullGather || newtype == hullMultline) {
854                         changeCols(1);
855                         setType(newtype);
856                 } else if (newtype ==   hullXXAlignAt) {
857                         for (row_type row = 0; row < nrows(); ++row)
858                                 numbered(row, false);
859                         setType(newtype);
860                 } else {
861                         setType(newtype);
862                 }
863         }
864
865         else if (type_ == hullXXAlignAt) {
866                 for (row_type row = 0; row < nrows(); ++row)
867                         numbered(row, false);
868                 if (newtype < hullAlign) {
869                         changeCols(3);
870                         setType(hullEqnArray);
871                         mutate(newtype);
872                 } else if (newtype == hullGather || newtype == hullMultline) {
873                         changeCols(1);
874                         setType(newtype);
875                 } else {
876                         setType(newtype);
877                 }
878         }
879
880         else if (type_ == hullMultline || type_ == hullGather) {
881                 if (newtype == hullGather || newtype == hullMultline)
882                         setType(newtype);
883                 else if (newtype == hullAlign || newtype == hullFlAlign  ||
884                          newtype == hullAlignAt || newtype == hullXAlignAt) {
885                         splitTo2Cols();
886                         setType(newtype);
887                 } else if (newtype ==   hullXXAlignAt) {
888                         splitTo2Cols();
889                         for (row_type row = 0; row < nrows(); ++row)
890                                 numbered(row, false);
891                         setType(newtype);
892                 } else {
893                         splitTo3Cols();
894                         setType(hullEqnArray);
895                         mutate(newtype);
896                 }
897         }
898
899         else {
900                 lyxerr << "mutation from '" << hullName(type_)
901                        << "' to '" << hullName(newtype)
902                        << "' not implemented" << endl;
903         }
904 }
905
906
907 string InsetMathHull::eolString(row_type row, bool emptyline, bool fragile) const
908 {
909         string res;
910         if (numberedType()) {
911                 if (!label_[row].empty() && !nonum_[row])
912                         res += "\\label{" + label_[row] + '}';
913                 if (nonum_[row] && (type_ != hullMultline))
914                         res += "\\nonumber ";
915         }
916         return res + InsetMathGrid::eolString(row, emptyline, fragile);
917 }
918
919
920 void InsetMathHull::write(WriteStream & os) const
921 {
922         header_write(os);
923         InsetMathGrid::write(os);
924         footer_write(os);
925 }
926
927
928 void InsetMathHull::normalize(NormalStream & os) const
929 {
930         os << "[formula " << hullName(type_) << ' ';
931         InsetMathGrid::normalize(os);
932         os << "] ";
933 }
934
935
936 void InsetMathHull::mathmlize(MathMLStream & os) const
937 {
938         InsetMathGrid::mathmlize(os);
939 }
940
941
942 void InsetMathHull::infoize(ostream & os) const
943 {
944         os << "Type: " << hullName(type_);
945 }
946
947
948 void InsetMathHull::check() const
949 {
950         BOOST_ASSERT(nonum_.size() == nrows());
951         BOOST_ASSERT(label_.size() == nrows());
952 }
953
954
955 void InsetMathHull::doExtern(LCursor & cur, FuncRequest & func)
956 {
957         docstring dlang;
958         docstring extra;
959         lyx::idocstringstream iss(func.argument());
960         iss >> dlang >> extra;
961         if (extra.empty())
962                 extra = lyx::from_ascii("noextra");
963         string const lang = lyx::to_ascii(dlang);
964
965 #ifdef WITH_WARNINGS
966 #warning temporarily disabled
967         //if (cur.selection()) {
968         //      MathArray ar;
969         //      selGet(cur.ar);
970         //      lyxerr << "use selection: " << ar << endl;
971         //      insert(pipeThroughExtern(lang, extra, ar));
972         //      return;
973         //}
974 #endif
975
976         MathArray eq;
977         eq.push_back(MathAtom(new InsetMathChar('=')));
978
979         // go to first item in line
980         cur.idx() -= cur.idx() % ncols();
981         cur.pos() = 0;
982
983         if (getType() == hullSimple) {
984                 size_type pos = cur.cell().find_last(eq);
985                 MathArray ar;
986                 if (cur.inMathed() && cur.selection()) {
987                         // FIXME UNICODE
988                         asArray(lyx::from_utf8(grabAndEraseSelection(cur)), ar);
989                 } else if (pos == cur.cell().size()) {
990                         ar = cur.cell();
991                         lyxerr << "use whole cell: " << ar << endl;
992                 } else {
993                         ar = MathArray(cur.cell().begin() + pos + 1, cur.cell().end());
994                         lyxerr << "use partial cell form pos: " << pos << endl;
995                 }
996                 cur.cell().append(eq);
997                 cur.cell().append(pipeThroughExtern(lang, extra, ar));
998                 cur.pos() = cur.lastpos();
999                 return;
1000         }
1001
1002         if (getType() == hullEquation) {
1003                 lyxerr << "use equation inset" << endl;
1004                 mutate(hullEqnArray);
1005                 MathArray & ar = cur.cell();
1006                 lyxerr << "use cell: " << ar << endl;
1007                 ++cur.idx();
1008                 cur.cell() = eq;
1009                 ++cur.idx();
1010                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1011                 // move to end of line
1012                 cur.pos() = cur.lastpos();
1013                 return;
1014         }
1015
1016         {
1017                 lyxerr << "use eqnarray" << endl;
1018                 cur.idx() += 2 - cur.idx() % ncols();
1019                 cur.pos() = 0;
1020                 MathArray ar = cur.cell();
1021                 lyxerr << "use cell: " << ar << endl;
1022 #ifdef WITH_WARNINGS
1023 #warning temporarily disabled
1024 #endif
1025                 addRow(cur.row());
1026                 ++cur.idx();
1027                 ++cur.idx();
1028                 cur.cell() = eq;
1029                 ++cur.idx();
1030                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1031                 cur.pos() = cur.lastpos();
1032         }
1033 }
1034
1035
1036 void InsetMathHull::doDispatch(LCursor & cur, FuncRequest & cmd)
1037 {
1038         //lyxerr << "action: " << cmd.action << endl;
1039         switch (cmd.action) {
1040
1041         case LFUN_FINISHED_LEFT:
1042         case LFUN_FINISHED_RIGHT:
1043         case LFUN_FINISHED_UP:
1044         case LFUN_FINISHED_DOWN:
1045                 //lyxerr << "action: " << cmd.action << endl;
1046                 InsetMathGrid::doDispatch(cur, cmd);
1047                 notifyCursorLeaves(cur);
1048                 cur.undispatched();
1049                 break;
1050
1051         case LFUN_BREAK_PARAGRAPH:
1052                 // just swallow this
1053                 break;
1054
1055         case LFUN_BREAK_LINE:
1056                 // some magic for the common case
1057                 if (type_ == hullSimple || type_ == hullEquation) {
1058                         recordUndoInset(cur);
1059                         bool const align =
1060                                 cur.bv().buffer()->params().use_amsmath == BufferParams::AMS_ON;
1061                         mutate(align ? hullAlign : hullEqnArray);
1062                         cur.idx() = 0;
1063                         cur.pos() = cur.lastpos();
1064                 }
1065                 InsetMathGrid::doDispatch(cur, cmd);
1066                 break;
1067
1068         case LFUN_MATH_NUMBER:
1069                 //lyxerr << "toggling all numbers" << endl;
1070                 if (display()) {
1071                         recordUndoInset(cur);
1072                         bool old = numberedType();
1073                         if (type_ == hullMultline)
1074                                 numbered(nrows() - 1, !old);
1075                         else
1076                                 for (row_type row = 0; row < nrows(); ++row)
1077                                         numbered(row, !old);
1078
1079                         cur.message(old ? _("No number") : _("Number"));
1080                 }
1081                 break;
1082
1083         case LFUN_MATH_NONUMBER:
1084                 if (display()) {
1085                         recordUndoInset(cur);
1086                         row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1087                         bool old = numbered(r);
1088                         cur.message(old ? _("No number") : _("Number"));
1089                         numbered(r, !old);
1090                 }
1091                 break;
1092
1093         case LFUN_LABEL_INSERT: {
1094                 recordUndoInset(cur);
1095                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1096                 docstring old_label = lyx::from_utf8(label(r));
1097                 docstring const default_label = lyx::from_ascii(
1098                         (lyxrc.label_init_length >= 0) ? "eq:" : "");
1099                 if (old_label.empty())
1100                         old_label = default_label;
1101
1102                 InsetCommandParams p("label");
1103                 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1104                 string const data = InsetCommandMailer::params2string("label", p);
1105
1106                 if (cmd.argument().empty())
1107                         cur.bv().showInsetDialog("label", data, 0);
1108                 else {
1109                         FuncRequest fr(LFUN_INSET_INSERT, data);
1110                         dispatch(cur, fr);
1111                 }
1112                 break;
1113         }
1114
1115         case LFUN_INSET_INSERT: {
1116                 //lyxerr << "arg: " << lyx::to_utf8(cmd.argument()) << endl;
1117                 string const name = cmd.getArg(0);
1118                 if (name == "label") {
1119                         InsetCommandParams p("label");
1120                         InsetCommandMailer::string2params(name, lyx::to_utf8(cmd.argument()), p);
1121                         string str = p.getContents();
1122                         recordUndoInset(cur);
1123                         row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1124                         str = lyx::support::trim(str);
1125                         if (!str.empty())
1126                                 numbered(r, true);
1127                         string old = label(r);
1128                         if (str != old) {
1129                                 cur.bv().buffer()->changeRefsIfUnique(old, str,
1130                                                         InsetBase::REF_CODE);
1131                                 label(r, str);
1132                         }
1133                         break;
1134                 }
1135                 InsetMathGrid::doDispatch(cur, cmd);
1136                 return;
1137         }
1138
1139         case LFUN_MATH_EXTERN:
1140                 recordUndoInset(cur);
1141                 doExtern(cur, cmd);
1142                 break;
1143
1144         case LFUN_MATH_MUTATE: {
1145                 recordUndoInset(cur);
1146                 row_type row = cur.row();
1147                 col_type col = cur.col();
1148                 mutate(hullType(lyx::to_utf8(cmd.argument())));
1149                 cur.idx() = row * ncols() + col;
1150                 if (cur.idx() > cur.lastidx()) {
1151                         cur.idx() = cur.lastidx();
1152                         cur.pos() = cur.lastpos();
1153                 }
1154                 if (cur.pos() > cur.lastpos())
1155                         cur.pos() = cur.lastpos();
1156                 //cur.dispatched(FINISHED);
1157                 break;
1158         }
1159
1160         case LFUN_MATH_DISPLAY: {
1161                 recordUndoInset(cur);
1162                 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1163                 cur.idx() = 0;
1164                 cur.pos() = cur.lastpos();
1165                 //cur.dispatched(FINISHED);
1166                 break;
1167         }
1168
1169         default:
1170                 InsetMathGrid::doDispatch(cur, cmd);
1171                 break;
1172         }
1173 }
1174
1175
1176 bool InsetMathHull::getStatus(LCursor & cur, FuncRequest const & cmd,
1177                 FuncStatus & status) const
1178 {
1179         switch (cmd.action) {
1180         case LFUN_FINISHED_LEFT:
1181         case LFUN_FINISHED_RIGHT:
1182         case LFUN_FINISHED_UP:
1183         case LFUN_FINISHED_DOWN:
1184                 status.enabled(true);
1185                 return true;
1186         case LFUN_BREAK_LINE:
1187         case LFUN_MATH_NUMBER:
1188         case LFUN_MATH_NONUMBER:
1189         case LFUN_MATH_EXTERN:
1190         case LFUN_MATH_MUTATE:
1191         case LFUN_MATH_DISPLAY:
1192                 // we handle these
1193                 status.enabled(true);
1194                 return true;
1195         case LFUN_LABEL_INSERT:
1196                 status.enabled(type_ != hullSimple);
1197                 return true;
1198         case LFUN_INSET_INSERT:
1199                 if (cmd.getArg(0) == "label") {
1200                         status.enabled(type_ != hullSimple);
1201                         return true;
1202                 }
1203                 return InsetMathGrid::getStatus(cur, cmd, status);
1204         case LFUN_TABULAR_FEATURE: {
1205                 istringstream is(lyx::to_utf8(cmd.argument()));
1206                 string s;
1207                 is >> s;
1208                 if (!rowChangeOK()
1209                     && (s == "append-row"
1210                         || s == "delete-row"
1211                         || s == "copy-row")) {
1212                         status.message(bformat(
1213                                 lyx::from_utf8(N_("Can't change number of rows in '%1$s'")),
1214                                 lyx::from_utf8(hullName(type_))));
1215                         status.enabled(false);
1216                         return true;
1217                 }
1218                 if (!colChangeOK()
1219                     && (s == "append-column"
1220                         || s == "delete-column"
1221                         || s == "copy-column")) {
1222                         status.message(bformat(
1223                                 lyx::from_utf8(N_("Can't change number of columns in '%1$s'")),
1224                                 lyx::from_utf8(hullName(type_))));
1225                         status.enabled(false);
1226                         return true;
1227                 }
1228                 if ((type_ == hullSimple
1229                   || type_ == hullEquation
1230                   || type_ == hullNone) &&
1231                     (s == "add-hline-above" || s == "add-hline-below")) {
1232                         status.message(bformat(
1233                                 lyx::from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1234                                 lyx::from_utf8(hullName(type_))));
1235                         status.enabled(false);
1236                         return true;
1237                 }
1238                 if (s == "add-vline-left" || s == "add-vline-right") {
1239                         status.message(bformat(
1240                                 lyx::from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1241                                 lyx::from_utf8(hullName(type_))));
1242                         status.enabled(false);
1243                         return true;
1244                 }
1245                 if (s == "valign-top" || s == "valign-middle"
1246                  || s == "valign-bottom" || s == "align-left"
1247                  || s == "align-center" || s == "align-right") {
1248                         status.enabled(false);
1249                         return true;
1250                 }
1251                 return InsetMathGrid::getStatus(cur, cmd, status);
1252         }
1253         default:
1254                 return InsetMathGrid::getStatus(cur, cmd, status);
1255         }
1256
1257         // This cannot really happen, but inserted to shut-up gcc
1258         return InsetMathGrid::getStatus(cur, cmd, status);
1259 }
1260
1261
1262 /////////////////////////////////////////////////////////////////////
1263
1264
1265
1266 // simply scrap this function if you want
1267 void InsetMathHull::mutateToText()
1268 {
1269 #if 0
1270         // translate to latex
1271         ostringstream os;
1272         latex(NULL, os, false, false);
1273         string str = os.str();
1274
1275         // insert this text
1276         LyXText * lt = view_->getLyXText();
1277         string::const_iterator cit = str.begin();
1278         string::const_iterator end = str.end();
1279         for (; cit != end; ++cit)
1280                 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1281
1282         // remove ourselves
1283         //lyx::dispatch(LFUN_ESCAPE);
1284 #endif
1285 }
1286
1287
1288 void InsetMathHull::handleFont(LCursor & cur, string const & arg,
1289         string const & font)
1290 {
1291         // this whole function is a hack and won't work for incremental font
1292         // changes...
1293         recordUndo(cur);
1294         if (cur.inset().asInsetMath()->name() == font)
1295                 cur.handleFont(font);
1296         else {
1297                 cur.handleNest(createInsetMath(font));
1298                 cur.insert(arg);
1299         }
1300 }
1301
1302
1303 void InsetMathHull::handleFont2(LCursor & cur, string const & arg)
1304 {
1305         recordUndo(cur);
1306         LyXFont font;
1307         bool b;
1308         bv_funcs::string2font(arg, font, b);
1309         if (font.color() != LColor::inherit) {
1310                 MathAtom at = MathAtom(new InsetMathColor(true, font.color()));
1311                 cur.handleNest(at, 0);
1312         }
1313 }
1314
1315
1316 void InsetMathHull::edit(LCursor & cur, bool left)
1317 {
1318         cur.push(*this);
1319         left ? idxFirst(cur) : idxLast(cur);
1320 }
1321
1322
1323 docstring const InsetMathHull::editMessage() const
1324 {
1325         return _("Math editor mode");
1326 }
1327
1328
1329 void InsetMathHull::revealCodes(LCursor & cur) const
1330 {
1331         if (!cur.inMathed())
1332                 return;
1333         ostringstream os;
1334         cur.info(os);
1335         cur.message(lyx::from_utf8(os.str()));
1336 /*
1337         // write something to the minibuffer
1338         // translate to latex
1339         cur.markInsert(bv);
1340         ostringstream os;
1341         write(NULL, os);
1342         string str = os.str();
1343         cur.markErase(bv);
1344         string::size_type pos = 0;
1345         string res;
1346         for (string::iterator it = str.begin(); it != str.end(); ++it) {
1347                 if (*it == '\n')
1348                         res += ' ';
1349                 else if (*it == '\0') {
1350                         res += "  -X-  ";
1351                         pos = it - str.begin();
1352                 }
1353                 else
1354                         res += *it;
1355         }
1356         if (pos > 30)
1357                 res = res.substr(pos - 30);
1358         if (res.size() > 60)
1359                 res = res.substr(0, 60);
1360         cur.message(res);
1361 */
1362 }
1363
1364
1365 InsetBase::Code InsetMathHull::lyxCode() const
1366 {
1367         return MATH_CODE;
1368 }
1369
1370
1371 /////////////////////////////////////////////////////////////////////
1372
1373
1374 #if 0
1375 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1376                                      bool, bool)
1377 {
1378 #ifdef WITH_WARNINGS
1379 #warning completely broken
1380 #endif
1381         static InsetMathHull * lastformula = 0;
1382         static CursorBase current = DocIterator(ibegin(nucleus()));
1383         static MathArray ar;
1384         static string laststr;
1385
1386         if (lastformula != this || laststr != str) {
1387                 //lyxerr << "reset lastformula to " << this << endl;
1388                 lastformula = this;
1389                 laststr = str;
1390                 current = ibegin(nucleus());
1391                 ar.clear();
1392                 mathed_parse_cell(ar, str);
1393         } else {
1394                 increment(current);
1395         }
1396         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1397
1398         for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1399                 CursorSlice & top = it.back();
1400                 MathArray const & a = top.asInsetMath()->cell(top.idx_);
1401                 if (a.matchpart(ar, top.pos_)) {
1402                         bv->cursor().setSelection(it, ar.size());
1403                         current = it;
1404                         top.pos_ += ar.size();
1405                         bv->update();
1406                         return true;
1407                 }
1408         }
1409
1410         //lyxerr << "not found!" << endl;
1411         lastformula = 0;
1412         return false;
1413 }
1414 #endif
1415
1416
1417 void InsetMathHull::write(Buffer const &, std::ostream & os) const
1418 {
1419         odocstringstream oss;
1420         WriteStream wi(oss, false, false);
1421         oss << "Formula ";
1422         write(wi);
1423         os << lyx::to_utf8(oss.str());
1424 }
1425
1426
1427 void InsetMathHull::read(Buffer const &, LyXLex & lex)
1428 {
1429         MathAtom at;
1430         mathed_parse_normal(at, lex);
1431         operator=(*at->asHullInset());
1432 }
1433
1434
1435 int InsetMathHull::plaintext(Buffer const &, odocstream & os,
1436                         OutputParams const &) const
1437 {
1438         if (0 && display()) {
1439                 Dimension dim;
1440                 TextMetricsInfo mi;
1441                 metricsT(mi, dim);
1442                 TextPainter tpain(dim.width(), dim.height());
1443                 drawT(tpain, 0, dim.ascent());
1444                 tpain.show(os, 3);
1445                 // reset metrics cache to "real" values
1446                 //metrics();
1447                 return tpain.textheight();
1448         } else {
1449                 WriteStream wi(os, false, true);
1450                 wi << cell(0);
1451                 return wi.line();
1452         }
1453 }
1454
1455
1456 int InsetMathHull::docbook(Buffer const & buf, odocstream & os,
1457                           OutputParams const & runparams) const
1458 {
1459         MathMLStream ms(os);
1460         int res = 0;
1461         string name;
1462         if (getType() == hullSimple)
1463                 name = "inlineequation";
1464         else
1465                 name = "informalequation";
1466
1467         string bname = name;
1468         if (!label(0).empty())
1469                 bname += " id=\"" + sgml::cleanID(buf, runparams, label(0)) + "\"";
1470         ms << MTag(bname.c_str());
1471
1472         odocstringstream ls;
1473         if (runparams.flavor == OutputParams::XML) {
1474                 ms << MTag("alt role=\"tex\" ");
1475                 // Workaround for db2latex: db2latex always includes equations with
1476                 // \ensuremath{} or \begin{display}\end{display}
1477                 // so we strip LyX' math environment
1478                 WriteStream wi(ls, false, false);
1479                 InsetMathGrid::write(wi);
1480                 ms << subst(subst(lyx::to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;");
1481                 ms << ETag("alt");
1482                 ms << MTag("math");
1483                 InsetMathGrid::mathmlize(ms);
1484                 ms << ETag("math");
1485         } else {
1486                 ms << MTag("alt role=\"tex\"");
1487                 res = latex(buf, ls, runparams);
1488                 ms << subst(subst(lyx::to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;");
1489                 ms << ETag("alt");
1490         }
1491
1492         ms <<  "<graphic fileref=\"eqn/";
1493         if ( !label(0).empty())
1494                 ms << sgml::cleanID(buf, runparams, label(0));
1495         else
1496                 ms << sgml::uniqueID("anon");
1497
1498         if (runparams.flavor == OutputParams::XML)
1499                 ms << "\"/>";
1500         else
1501                 ms << "\">";
1502
1503         ms << ETag(name.c_str());
1504         return ms.line() + res;
1505 }
1506
1507
1508 int InsetMathHull::textString(Buffer const & buf, odocstream & os,
1509                        OutputParams const & op) const
1510 {
1511         return plaintext(buf, os, op);
1512 }