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