]> git.lyx.org Git - lyx.git/blob - src/mathed/math_hullinset.C
Change _() to return a docstring. Fixup callers with the help of lyx::to_utf8.
[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                         // FIXME UNICODE
1046                         cur.message(old ? lyx::to_utf8(_("No number")) : lyx::to_utf8(_("Number")));
1047                 }
1048                 break;
1049
1050         case LFUN_MATH_NONUMBER:
1051                 if (display()) {
1052                         recordUndoInset(cur);
1053                         row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1054                         bool old = numbered(r);
1055                         // FIXME UNICODE
1056                         cur.message(old ? lyx::to_utf8(_("No number")) : lyx::to_utf8(_("Number")));
1057                         numbered(r, !old);
1058                 }
1059                 break;
1060
1061         case LFUN_LABEL_INSERT: {
1062                 recordUndoInset(cur);
1063                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1064                 string old_label = label(r);
1065                 string const default_label =
1066                         (lyxrc.label_init_length >= 0) ? "eq:" : "";
1067                 if (old_label.empty())
1068                         old_label = default_label;
1069                 string const contents = cmd.argument().empty() ?
1070                         old_label : lyx::to_utf8(cmd.argument());
1071
1072                 InsetCommandParams p("label", contents);
1073                 string const data = InsetCommandMailer::params2string("label", p);
1074
1075                 if (cmd.argument().empty())
1076                         cur.bv().owner()->getDialogs().show("label", data, 0);
1077                 else {
1078                         FuncRequest fr(LFUN_INSET_INSERT, data);
1079                         dispatch(cur, fr);
1080                 }
1081                 break;
1082         }
1083
1084         case LFUN_INSET_INSERT: {
1085                 //lyxerr << "arg: " << lyx::to_utf8(cmd.argument()) << endl;
1086                 string const name = cmd.getArg(0);
1087                 if (name == "label") {
1088                         InsetCommandParams p;
1089                         InsetCommandMailer::string2params(name, lyx::to_utf8(cmd.argument()), p);
1090                         string str = p.getContents();
1091                         recordUndoInset(cur);
1092                         row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1093                         str = lyx::support::trim(str);
1094                         if (!str.empty())
1095                                 numbered(r, true);
1096                         string old = label(r);
1097                         if (str != old) {
1098                                 cur.bv().buffer()->changeRefsIfUnique(old, str);
1099                                 label(r, str);
1100                         }
1101                         break;
1102                 }
1103                 MathArray ar;
1104                 if (createMathInset_fromDialogStr(lyx::to_utf8(cmd.argument()), ar)) {
1105                         recordUndo(cur);
1106                         cur.insert(ar);
1107                 } else
1108                         cur.undispatched();
1109                 break;
1110         }
1111
1112         case LFUN_MATH_EXTERN:
1113                 recordUndoInset(cur);
1114                 doExtern(cur, cmd);
1115                 break;
1116
1117         case LFUN_MATH_MUTATE: {
1118                 recordUndoInset(cur);
1119                 row_type row = cur.row();
1120                 col_type col = cur.col();
1121                 mutate(hullType(lyx::to_utf8(cmd.argument())));
1122                 cur.idx() = row * ncols() + col;
1123                 if (cur.idx() > cur.lastidx()) {
1124                         cur.idx() = cur.lastidx();
1125                         cur.pos() = cur.lastpos();
1126                 }
1127                 if (cur.pos() > cur.lastpos())
1128                         cur.pos() = cur.lastpos();
1129                 //cur.dispatched(FINISHED);
1130                 break;
1131         }
1132
1133         case LFUN_MATH_DISPLAY: {
1134                 recordUndoInset(cur);
1135                 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1136                 cur.idx() = 0;
1137                 cur.pos() = cur.lastpos();
1138                 //cur.dispatched(FINISHED);
1139                 break;
1140         }
1141
1142         default:
1143                 MathGridInset::doDispatch(cur, cmd);
1144                 break;
1145         }
1146 }
1147
1148
1149 bool MathHullInset::getStatus(LCursor & cur, FuncRequest const & cmd,
1150                 FuncStatus & status) const
1151 {
1152         switch (cmd.action) {
1153         case LFUN_FINISHED_LEFT:
1154         case LFUN_FINISHED_RIGHT:
1155         case LFUN_FINISHED_UP:
1156         case LFUN_FINISHED_DOWN:
1157                 status.enabled(true);
1158                 return true;
1159         case LFUN_BREAK_LINE:
1160         case LFUN_MATH_NUMBER:
1161         case LFUN_MATH_NONUMBER:
1162         case LFUN_MATH_EXTERN:
1163         case LFUN_MATH_MUTATE:
1164         case LFUN_MATH_DISPLAY:
1165                 // we handle these
1166                 status.enabled(true);
1167                 return true;
1168         case LFUN_LABEL_INSERT:
1169                 status.enabled(type_ != hullSimple);
1170                 return true;
1171         case LFUN_INSET_INSERT: {
1172                 // Don't test createMathInset_fromDialogStr(), since
1173                 // getStatus is not called with a valid reference and the
1174                 // dialog would not be applyable.
1175                 string const name = cmd.getArg(0);
1176                 status.enabled(name == "ref" ||
1177                                (name == "label" && type_ != hullSimple));
1178                 break;
1179         }
1180         case LFUN_TABULAR_FEATURE: {
1181                 istringstream is(lyx::to_utf8(cmd.argument()));
1182                 string s;
1183                 is >> s;
1184                 if (!rowChangeOK()
1185                     && (s == "append-row"
1186                         || s == "delete-row"
1187                         || s == "copy-row")) {
1188                         status.message(bformat(
1189                                 N_("Can't change number of rows in '%1$s'"),
1190                                    hullName(type_)));
1191                         status.enabled(false);
1192                         return true;
1193                 }
1194                 if (!colChangeOK()
1195                     && (s == "append-column"
1196                         || s == "delete-column"
1197                         || s == "copy-column")) {
1198                         status.message(bformat(
1199                                 N_("Can't change number of columns in '%1$s'"),
1200                                    hullName(type_)));
1201                         status.enabled(false);
1202                         return true;
1203                 }
1204                 if ((type_ == hullSimple
1205                   || type_ == hullEquation
1206                   || type_ == hullNone) &&
1207                     (s == "add-hline-above" || s == "add-hline-below")) {
1208                         status.message(bformat(
1209                                 N_("Can't add horizontal grid lines in '%1$s'"),
1210                                    hullName(type_)));
1211                         status.enabled(false);
1212                         return true;
1213                 }
1214                 if (s == "add-vline-left" || s == "add-vline-right") {
1215                         status.message(bformat(
1216                                 N_("Can't add vertical grid lines in '%1$s'"),
1217                                    hullName(type_)));
1218                         status.enabled(false);
1219                         return true;
1220                 }
1221                 if (s == "valign-top" || s == "valign-middle"
1222                  || s == "valign-bottom" || s == "align-left"
1223                  || s == "align-center" || s == "align-right") {
1224                         status.enabled(false);
1225                         return true;
1226                 }
1227                 return MathGridInset::getStatus(cur, cmd, status);
1228         }
1229         default:
1230                 return MathGridInset::getStatus(cur, cmd, status);
1231         }
1232
1233         // This cannot really happen, but inserted to shut-up gcc
1234         return MathGridInset::getStatus(cur, cmd, status);
1235 }
1236
1237
1238 /////////////////////////////////////////////////////////////////////
1239
1240 #include "math_arrayinset.h"
1241 #include "math_deliminset.h"
1242 #include "math_factory.h"
1243 #include "math_parser.h"
1244 #include "math_spaceinset.h"
1245 #include "ref_inset.h"
1246
1247 #include "bufferview_funcs.h"
1248 #include "lyxtext.h"
1249
1250 #include "frontends/LyXView.h"
1251 #include "frontends/Dialogs.h"
1252
1253 #include "support/lyxlib.h"
1254
1255
1256 // simply scrap this function if you want
1257 void MathHullInset::mutateToText()
1258 {
1259 #if 0
1260         // translate to latex
1261         ostringstream os;
1262         latex(NULL, os, false, false);
1263         string str = os.str();
1264
1265         // insert this text
1266         LyXText * lt = view_->getLyXText();
1267         string::const_iterator cit = str.begin();
1268         string::const_iterator end = str.end();
1269         for (; cit != end; ++cit)
1270                 view_->owner()->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1271
1272         // remove ourselves
1273         //view_->owner()->dispatch(LFUN_ESCAPE);
1274 #endif
1275 }
1276
1277
1278 void MathHullInset::handleFont(LCursor & cur, string const & arg,
1279         string const & font)
1280 {
1281         // this whole function is a hack and won't work for incremental font
1282         // changes...
1283         recordUndo(cur);
1284         if (cur.inset().asMathInset()->name() == font)
1285                 cur.handleFont(font);
1286         else {
1287                 cur.handleNest(createMathInset(font));
1288                 cur.insert(arg);
1289         }
1290 }
1291
1292
1293 void MathHullInset::handleFont2(LCursor & cur, string const & arg)
1294 {
1295         recordUndo(cur);
1296         LyXFont font;
1297         bool b;
1298         bv_funcs::string2font(arg, font, b);
1299         if (font.color() != LColor::inherit) {
1300                 MathAtom at = MathAtom(new MathColorInset(true, font.color()));
1301                 cur.handleNest(at, 0);
1302         }
1303 }
1304
1305
1306 void MathHullInset::edit(LCursor & cur, bool left)
1307 {
1308         cur.push(*this);
1309         left ? idxFirst(cur) : idxLast(cur);
1310 }
1311
1312
1313 string const MathHullInset::editMessage() const
1314 {
1315         // FIXME UNICODE
1316         return lyx::to_utf8(_("Math editor mode"));
1317 }
1318
1319
1320 void MathHullInset::revealCodes(LCursor & cur) const
1321 {
1322         if (!cur.inMathed())
1323                 return;
1324         ostringstream os;
1325         cur.info(os);
1326         cur.message(os.str());
1327 /*
1328         // write something to the minibuffer
1329         // translate to latex
1330         cur.markInsert(bv);
1331         ostringstream os;
1332         write(NULL, os);
1333         string str = os.str();
1334         cur.markErase(bv);
1335         string::size_type pos = 0;
1336         string res;
1337         for (string::iterator it = str.begin(); it != str.end(); ++it) {
1338                 if (*it == '\n')
1339                         res += ' ';
1340                 else if (*it == '\0') {
1341                         res += "  -X-  ";
1342                         pos = it - str.begin();
1343                 }
1344                 else
1345                         res += *it;
1346         }
1347         if (pos > 30)
1348                 res = res.substr(pos - 30);
1349         if (res.size() > 60)
1350                 res = res.substr(0, 60);
1351         cur.message(res);
1352 */
1353 }
1354
1355
1356 InsetBase::Code MathHullInset::lyxCode() const
1357 {
1358         return MATH_CODE;
1359 }
1360
1361
1362 /////////////////////////////////////////////////////////////////////
1363
1364
1365 #if 0
1366 bool MathHullInset::searchForward(BufferView * bv, string const & str,
1367                                      bool, bool)
1368 {
1369 #ifdef WITH_WARNINGS
1370 #warning completely broken
1371 #endif
1372         static MathHullInset * lastformula = 0;
1373         static CursorBase current = DocIterator(ibegin(nucleus()));
1374         static MathArray ar;
1375         static string laststr;
1376
1377         if (lastformula != this || laststr != str) {
1378                 //lyxerr << "reset lastformula to " << this << endl;
1379                 lastformula = this;
1380                 laststr = str;
1381                 current = ibegin(nucleus());
1382                 ar.clear();
1383                 mathed_parse_cell(ar, str);
1384         } else {
1385                 increment(current);
1386         }
1387         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1388
1389         for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1390                 CursorSlice & top = it.back();
1391                 MathArray const & a = top.asMathInset()->cell(top.idx_);
1392                 if (a.matchpart(ar, top.pos_)) {
1393                         bv->cursor().setSelection(it, ar.size());
1394                         current = it;
1395                         top.pos_ += ar.size();
1396                         bv->update();
1397                         return true;
1398                 }
1399         }
1400
1401         //lyxerr << "not found!" << endl;
1402         lastformula = 0;
1403         return false;
1404 }
1405 #endif
1406
1407
1408 void MathHullInset::write(Buffer const &, std::ostream & os) const
1409 {
1410         WriteStream wi(os, false, false);
1411         os << "Formula ";
1412         write(wi);
1413 }
1414
1415
1416 void MathHullInset::read(Buffer const &, LyXLex & lex)
1417 {
1418         MathAtom at;
1419         mathed_parse_normal(at, lex);
1420         operator=(*at->asHullInset());
1421 }
1422
1423
1424 int MathHullInset::plaintext(Buffer const &, ostream & os,
1425                         OutputParams const &) const
1426 {
1427         if (0 && display()) {
1428                 Dimension dim;
1429                 TextMetricsInfo mi;
1430                 metricsT(mi, dim);
1431                 TextPainter tpain(dim.width(), dim.height());
1432                 drawT(tpain, 0, dim.ascent());
1433                 tpain.show(os, 3);
1434                 // reset metrics cache to "real" values
1435                 //metrics();
1436                 return tpain.textheight();
1437         } else {
1438                 WriteStream wi(os, false, true);
1439                 wi << cell(0);
1440                 return wi.line();
1441         }
1442 }
1443
1444
1445 int MathHullInset::docbook(Buffer const & buf, ostream & os,
1446                           OutputParams const & runparams) const
1447 {
1448         MathMLStream ms(os);
1449         int res = 0;
1450         string name;
1451         if (getType() == hullSimple)
1452                 name = "inlineequation";
1453         else
1454                 name = "informalequation";
1455
1456         string bname = name;
1457         if (!label(0).empty())
1458                 bname += " id=\"" + sgml::cleanID(buf, runparams, label(0)) + "\"";
1459         ms << MTag(bname.c_str());
1460
1461         ostringstream ls;
1462         if (runparams.flavor == OutputParams::XML) {
1463                 ms << MTag("alt role=\"tex\" ");
1464                 // Workaround for db2latex: db2latex always includes equations with
1465                 // \ensuremath{} or \begin{display}\end{display}
1466                 // so we strip LyX' math environment
1467                 WriteStream wi(ls, false, false);
1468                 MathGridInset::write(wi);
1469                 ms << subst(subst(ls.str(), "&", "&amp;"), "<", "&lt;");
1470                 ms << ETag("alt");
1471                 ms << MTag("math");
1472                 MathGridInset::mathmlize(ms);
1473                 ms << ETag("math");
1474         } else {
1475                 ms << MTag("alt role=\"tex\"");
1476                 res = latex(buf, ls, runparams);
1477                 ms << subst(subst(ls.str(), "&", "&amp;"), "<", "&lt;");
1478                 ms << ETag("alt");
1479         }
1480
1481         ms <<  "<graphic fileref=\"eqn/";
1482         if ( !label(0).empty())
1483                 ms << sgml::cleanID(buf, runparams, label(0));
1484         else
1485                 ms << sgml::uniqueID("anon");
1486
1487         if (runparams.flavor == OutputParams::XML)
1488                 ms << "\"/>";
1489         else
1490                 ms << "\">";
1491
1492         ms << ETag(name.c_str());
1493         return ms.line() + res;
1494 }
1495
1496
1497 int MathHullInset::textString(Buffer const & buf, ostream & os,
1498                        OutputParams const & op) const
1499 {
1500         return plaintext(buf, os, op);
1501 }