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