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