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