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