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