]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathHull.cpp
BufferParams.cpp: change the package loading to:
[lyx.git] / src / mathed / InsetMathHull.cpp
1 /**
2  * \file InsetMathHull.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetMathArray.h"
14 #include "InsetMathChar.h"
15 #include "InsetMathColor.h"
16 #include "MathData.h"
17 #include "InsetMathDelim.h"
18 #include "MathExtern.h"
19 #include "MathFactory.h"
20 #include "InsetMathHull.h"
21 #include "MathStream.h"
22 #include "MathParser.h"
23 #include "InsetMathSpace.h"
24 #include "MathStream.h"
25 #include "MathSupport.h"
26 #include "InsetMathRef.h"
27
28 #include "bufferview_funcs.h"
29 #include "Text.h"
30
31 #include "Buffer.h"
32 #include "BufferParams.h"
33 #include "BufferView.h"
34 #include "CutAndPaste.h"
35 #include "FuncStatus.h"
36 #include "Color.h"
37 #include "LaTeXFeatures.h"
38 #include "Cursor.h"
39 #include "debug.h"
40 #include "DispatchResult.h"
41 #include "FuncRequest.h"
42 #include "gettext.h"
43 #include "LyXRC.h"
44 #include "OutputParams.h"
45 #include "sgml.h"
46 #include "TextPainter.h"
47 #include "Undo.h"
48
49 #include "insets/RenderPreview.h"
50 #include "insets/InsetLabel.h"
51
52 #include "graphics/PreviewImage.h"
53 #include "graphics/PreviewLoader.h"
54
55 #include "frontends/Painter.h"
56
57 #include "support/lyxlib.h"
58 #include "support/lstrings.h"
59
60 #include <boost/bind.hpp>
61
62 #include <sstream>
63
64
65 namespace lyx {
66
67 using cap::grabAndEraseSelection;
68 using support::bformat;
69 using support::subst;
70
71 using std::endl;
72 using std::max;
73 using std::ostream;
74 using std::istringstream;
75 using std::ostringstream;
76 using std::swap;
77 using std::vector;
78
79
80 namespace {
81
82         int getCols(HullType type)
83         {
84                 switch (type) {
85                         case hullEqnArray:
86                                 return 3;
87                         case hullAlign:
88                         case hullFlAlign:
89                         case hullAlignAt:
90                         case hullXAlignAt:
91                         case hullXXAlignAt:
92                                 return 2;
93                         default:
94                                 return 1;
95                 }
96         }
97
98
99         // returns position of first relation operator in the array
100         // used for "intelligent splitting"
101         size_t firstRelOp(MathData const & ar)
102         {
103                 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
104                         if ((*it)->isRelOp())
105                                 return it - ar.begin();
106                 return ar.size();
107         }
108
109
110         char const * star(bool numbered)
111         {
112                 return numbered ? "" : "*";
113         }
114
115
116 } // end anon namespace
117
118
119 HullType hullType(docstring const & s)
120 {
121         if (s == "none")      return hullNone;
122         if (s == "simple")    return hullSimple;
123         if (s == "equation")  return hullEquation;
124         if (s == "eqnarray")  return hullEqnArray;
125         if (s == "align")     return hullAlign;
126         if (s == "alignat")   return hullAlignAt;
127         if (s == "xalignat")  return hullXAlignAt;
128         if (s == "xxalignat") return hullXXAlignAt;
129         if (s == "multline")  return hullMultline;
130         if (s == "gather")    return hullGather;
131         if (s == "flalign")   return hullFlAlign;
132         lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
133         return HullType(-1);
134 }
135
136
137 docstring hullName(HullType type)
138 {
139         switch (type) {
140                 case hullNone:       return from_ascii("none");
141                 case hullSimple:     return from_ascii("simple");
142                 case hullEquation:   return from_ascii("equation");
143                 case hullEqnArray:   return from_ascii("eqnarray");
144                 case hullAlign:      return from_ascii("align");
145                 case hullAlignAt:    return from_ascii("alignat");
146                 case hullXAlignAt:   return from_ascii("xalignat");
147                 case hullXXAlignAt:  return from_ascii("xxalignat");
148                 case hullMultline:   return from_ascii("multline");
149                 case hullGather:     return from_ascii("gather");
150                 case hullFlAlign:    return from_ascii("flalign");
151                 default:
152                         lyxerr << "unknown hull type '" << type << "'" << endl;
153                         return from_ascii("none");
154         }
155 }
156
157
158 InsetMathHull::InsetMathHull()
159         : InsetMathGrid(1, 1), type_(hullNone), nonum_(1), label_(1),
160           preview_(new RenderPreview(this))
161 {
162         //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
163         //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
164         //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
165         //lyxerr << "sizeof Font: " << sizeof(Font) << endl;
166         initMath();
167         setDefaults();
168 }
169
170
171 InsetMathHull::InsetMathHull(HullType type)
172         : InsetMathGrid(getCols(type), 1), type_(type), nonum_(1), label_(1),
173           preview_(new RenderPreview(this))
174 {
175         initMath();
176         setDefaults();
177 }
178
179
180 InsetMathHull::InsetMathHull(InsetMathHull const & other)
181         : InsetMathGrid(other),
182           type_(other.type_), nonum_(other.nonum_), label_(other.label_),
183           preview_(new RenderPreview(*other.preview_, this))
184 {}
185
186
187 InsetMathHull::~InsetMathHull()
188 {}
189
190
191 Inset * InsetMathHull::clone() const
192 {
193         return new InsetMathHull(*this);
194 }
195
196
197 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
198 {
199         if (this == &other)
200                 return *this;
201         *static_cast<InsetMathGrid*>(this) = InsetMathGrid(other);
202         type_  = other.type_;
203         nonum_ = other.nonum_;
204         label_ = other.label_;
205         preview_.reset(new RenderPreview(*other.preview_, this));
206
207         return *this;
208 }
209
210
211 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
212 {
213         if (use_preview_) {
214                 edit(cur, true);
215                 return this;
216         }
217         return InsetMathNest::editXY(cur, x, y);
218 }
219
220
221 InsetMath::mode_type InsetMathHull::currentMode() const
222 {
223         if (type_ == hullNone)
224                 return UNDECIDED_MODE;
225         // definitely math mode ...
226         return MATH_MODE;
227 }
228
229
230 bool InsetMathHull::idxFirst(Cursor & cur) const
231 {
232         cur.idx() = 0;
233         cur.pos() = 0;
234         return true;
235 }
236
237
238 bool InsetMathHull::idxLast(Cursor & cur) const
239 {
240         cur.idx() = nargs() - 1;
241         cur.pos() = cur.lastpos();
242         return true;
243 }
244
245
246 char InsetMathHull::defaultColAlign(col_type col)
247 {
248         if (type_ == hullEqnArray)
249                 return "rcl"[col];
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 & 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(Buffer const &, 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(1);
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() - 1);
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         std::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_LEFT:
1043         case LFUN_FINISHED_RIGHT:
1044                 //lyxerr << "action: " << cmd.action << endl;
1045                 InsetMathGrid::doDispatch(cur, cmd);
1046                 notifyCursorLeaves(cur);
1047                 cur.undispatched();
1048                 break;
1049
1050         case LFUN_BREAK_PARAGRAPH:
1051                 // just swallow this
1052                 break;
1053
1054         case LFUN_BREAK_LINE:
1055                 // some magic for the common case
1056                 if (type_ == hullSimple || type_ == hullEquation) {
1057                         recordUndoInset(cur);
1058                         bool const align =
1059                                 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1060                         mutate(align ? hullAlign : hullEqnArray);
1061                         cur.idx() = 0;
1062                         cur.pos() = cur.lastpos();
1063                 }
1064                 InsetMathGrid::doDispatch(cur, cmd);
1065                 break;
1066
1067         case LFUN_MATH_NUMBER:
1068                 //lyxerr << "toggling all numbers" << endl;
1069                 if (display()) {
1070                         recordUndoInset(cur);
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                 }
1080                 break;
1081
1082         case LFUN_MATH_NONUMBER:
1083                 if (display()) {
1084                         recordUndoInset(cur);
1085                         row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1086                         bool old = numbered(r);
1087                         cur.message(old ? _("No number") : _("Number"));
1088                         numbered(r, !old);
1089                 }
1090                 break;
1091
1092         case LFUN_LABEL_INSERT: {
1093                 recordUndoInset(cur);
1094                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1095                 docstring old_label = label(r);
1096                 docstring const default_label = from_ascii(
1097                         (lyxrc.label_init_length >= 0) ? "eq:" : "");
1098                 if (old_label.empty())
1099                         old_label = default_label;
1100
1101                 InsetCommandParams p("label");
1102                 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1103                 std::string const data = InsetCommandMailer::params2string("label", p);
1104
1105                 if (cmd.argument().empty())
1106                         cur.bv().showInsetDialog("label", data, 0);
1107                 else {
1108                         FuncRequest fr(LFUN_INSET_INSERT, data);
1109                         dispatch(cur, fr);
1110                 }
1111                 break;
1112         }
1113
1114         case LFUN_INSET_INSERT: {
1115                 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1116                 std::string const name = cmd.getArg(0);
1117                 if (name == "label") {
1118                         InsetCommandParams p("label");
1119                         InsetCommandMailer::string2params(name, to_utf8(cmd.argument()), p);
1120                         docstring str = p["name"];
1121                         recordUndoInset(cur);
1122                         row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1123                         str = support::trim(str);
1124                         if (!str.empty())
1125                                 numbered(r, true);
1126                         docstring old = label(r);
1127                         if (str != old) {
1128                                 cur.bv().buffer().changeRefsIfUnique(old, str,
1129                                                         Inset::REF_CODE);
1130                                 label(r, str);
1131                         }
1132                         break;
1133                 }
1134                 InsetMathGrid::doDispatch(cur, cmd);
1135                 return;
1136         }
1137
1138         case LFUN_MATH_EXTERN:
1139                 recordUndoInset(cur);
1140                 doExtern(cur, cmd);
1141                 break;
1142
1143         case LFUN_MATH_MUTATE: {
1144                 recordUndoInset(cur);
1145                 row_type row = cur.row();
1146                 col_type col = cur.col();
1147                 mutate(hullType(cmd.argument()));
1148                 cur.idx() = row * ncols() + col;
1149                 if (cur.idx() > cur.lastidx()) {
1150                         cur.idx() = cur.lastidx();
1151                         cur.pos() = cur.lastpos();
1152                 }
1153                 if (cur.pos() > cur.lastpos())
1154                         cur.pos() = cur.lastpos();
1155                 //cur.dispatched(FINISHED);
1156                 break;
1157         }
1158
1159         case LFUN_MATH_DISPLAY: {
1160                 recordUndoInset(cur);
1161                 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1162                 cur.idx() = 0;
1163                 cur.pos() = cur.lastpos();
1164                 //cur.dispatched(FINISHED);
1165                 break;
1166         }
1167
1168         default:
1169                 InsetMathGrid::doDispatch(cur, cmd);
1170                 break;
1171         }
1172 }
1173
1174
1175 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1176                 FuncStatus & status) const
1177 {
1178         switch (cmd.action) {
1179         case LFUN_FINISHED_LEFT:
1180         case LFUN_FINISHED_RIGHT:
1181         case LFUN_UP:
1182         case LFUN_DOWN:
1183                 status.enabled(true);
1184                 return true;
1185         case LFUN_BREAK_LINE:
1186         case LFUN_MATH_NUMBER:
1187         case LFUN_MATH_NONUMBER:
1188         case LFUN_MATH_EXTERN:
1189         case LFUN_MATH_MUTATE:
1190         case LFUN_MATH_DISPLAY:
1191                 // we handle these
1192                 status.enabled(true);
1193                 return true;
1194         case LFUN_LABEL_INSERT:
1195                 status.enabled(type_ != hullSimple);
1196                 return true;
1197         case LFUN_INSET_INSERT:
1198                 if (cmd.getArg(0) == "label") {
1199                         status.enabled(type_ != hullSimple);
1200                         return true;
1201                 }
1202                 return InsetMathGrid::getStatus(cur, cmd, status);
1203         case LFUN_TABULAR_FEATURE: {
1204                 istringstream is(to_utf8(cmd.argument()));
1205                 std::string s;
1206                 is >> s;
1207                 if (!rowChangeOK()
1208                     && (s == "append-row"
1209                         || s == "delete-row"
1210                         || s == "copy-row")) {
1211                         status.message(bformat(
1212                                 from_utf8(N_("Can't change number of rows in '%1$s'")),
1213                                 hullName(type_)));
1214                         status.enabled(false);
1215                         return true;
1216                 }
1217                 if (!colChangeOK()
1218                     && (s == "append-column"
1219                         || s == "delete-column"
1220                         || s == "copy-column")) {
1221                         status.message(bformat(
1222                                 from_utf8(N_("Can't change number of columns in '%1$s'")),
1223                                 hullName(type_)));
1224                         status.enabled(false);
1225                         return true;
1226                 }
1227                 if ((type_ == hullSimple
1228                   || type_ == hullEquation
1229                   || type_ == hullNone) &&
1230                     (s == "add-hline-above" || s == "add-hline-below")) {
1231                         status.message(bformat(
1232                                 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1233                                 hullName(type_)));
1234                         status.enabled(false);
1235                         return true;
1236                 }
1237                 if (s == "add-vline-left" || s == "add-vline-right") {
1238                         status.message(bformat(
1239                                 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1240                                 hullName(type_)));
1241                         status.enabled(false);
1242                         return true;
1243                 }
1244                 if (s == "valign-top" || s == "valign-middle"
1245                  || s == "valign-bottom" || s == "align-left"
1246                  || s == "align-center" || s == "align-right") {
1247                         status.enabled(false);
1248                         return true;
1249                 }
1250                 return InsetMathGrid::getStatus(cur, cmd, status);
1251         }
1252         default:
1253                 return InsetMathGrid::getStatus(cur, cmd, status);
1254         }
1255
1256         // This cannot really happen, but inserted to shut-up gcc
1257         return InsetMathGrid::getStatus(cur, cmd, status);
1258 }
1259
1260
1261 /////////////////////////////////////////////////////////////////////
1262
1263
1264
1265 // simply scrap this function if you want
1266 void InsetMathHull::mutateToText()
1267 {
1268 #if 0
1269         // translate to latex
1270         ostringstream os;
1271         latex(NULL, os, false, false);
1272         string str = os.str();
1273
1274         // insert this text
1275         Text * lt = view_->cursor().innerText();
1276         string::const_iterator cit = str.begin();
1277         string::const_iterator end = str.end();
1278         for (; cit != end; ++cit)
1279                 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1280
1281         // remove ourselves
1282         //dispatch(LFUN_ESCAPE);
1283 #endif
1284 }
1285
1286
1287 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1288         docstring const & font)
1289 {
1290         // this whole function is a hack and won't work for incremental font
1291         // changes...
1292         recordUndo(cur);
1293         if (cur.inset().asInsetMath()->name() == font)
1294                 cur.handleFont(to_utf8(font));
1295         else {
1296                 cur.handleNest(createInsetMath(font));
1297                 cur.insert(arg);
1298         }
1299 }
1300
1301
1302 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1303 {
1304         recordUndo(cur);
1305         Font font;
1306         bool b;
1307         bv_funcs::string2font(to_utf8(arg), font, b);
1308         if (font.color() != Color::inherit) {
1309                 MathAtom at = MathAtom(new InsetMathColor(true, font.color()));
1310                 cur.handleNest(at, 0);
1311         }
1312 }
1313
1314
1315 void InsetMathHull::edit(Cursor & cur, bool left)
1316 {
1317         cur.push(*this);
1318         left ? idxFirst(cur) : idxLast(cur);
1319         // The inset formula dimension is not necessarily the same as the
1320         // one of the instant preview image, so we have to indicate to the
1321         // BufferView that a metrics update is needed.
1322         cur.updateFlags(Update::Force);
1323 }
1324
1325
1326 docstring const InsetMathHull::editMessage() const
1327 {
1328         return _("Math editor mode");
1329 }
1330
1331
1332 void InsetMathHull::revealCodes(Cursor & cur) const
1333 {
1334         if (!cur.inMathed())
1335                 return;
1336         odocstringstream os;
1337         cur.info(os);
1338         cur.message(os.str());
1339 /*
1340         // write something to the minibuffer
1341         // translate to latex
1342         cur.markInsert(bv);
1343         ostringstream os;
1344         write(NULL, os);
1345         string str = os.str();
1346         cur.markErase(bv);
1347         string::size_type pos = 0;
1348         string res;
1349         for (string::iterator it = str.begin(); it != str.end(); ++it) {
1350                 if (*it == '\n')
1351                         res += ' ';
1352                 else if (*it == '\0') {
1353                         res += "  -X-  ";
1354                         pos = it - str.begin();
1355                 }
1356                 else
1357                         res += *it;
1358         }
1359         if (pos > 30)
1360                 res = res.substr(pos - 30);
1361         if (res.size() > 60)
1362                 res = res.substr(0, 60);
1363         cur.message(res);
1364 */
1365 }
1366
1367
1368 Inset::Code InsetMathHull::lyxCode() const
1369 {
1370         return MATH_CODE;
1371 }
1372
1373
1374 /////////////////////////////////////////////////////////////////////
1375
1376
1377 #if 0
1378 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1379                                      bool, bool)
1380 {
1381         // FIXME: completely broken
1382         static InsetMathHull * lastformula = 0;
1383         static CursorBase current = DocIterator(ibegin(nucleus()));
1384         static MathData ar;
1385         static string laststr;
1386
1387         if (lastformula != this || laststr != str) {
1388                 //lyxerr << "reset lastformula to " << this << endl;
1389                 lastformula = this;
1390                 laststr = str;
1391                 current = ibegin(nucleus());
1392                 ar.clear();
1393                 mathed_parse_cell(ar, str);
1394         } else {
1395                 increment(current);
1396         }
1397         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1398
1399         for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1400                 CursorSlice & top = it.back();
1401                 MathData const & a = top.asInsetMath()->cell(top.idx_);
1402                 if (a.matchpart(ar, top.pos_)) {
1403                         bv->cursor().setSelection(it, ar.size());
1404                         current = it;
1405                         top.pos_ += ar.size();
1406                         bv->update();
1407                         return true;
1408                 }
1409         }
1410
1411         //lyxerr << "not found!" << endl;
1412         lastformula = 0;
1413         return false;
1414 }
1415 #endif
1416
1417
1418 void InsetMathHull::write(Buffer const &, std::ostream & os) const
1419 {
1420         odocstringstream oss;
1421         WriteStream wi(oss, false, false);
1422         oss << "Formula ";
1423         write(wi);
1424         os << to_utf8(oss.str());
1425 }
1426
1427
1428 void InsetMathHull::read(Buffer const &, Lexer & lex)
1429 {
1430         MathAtom at;
1431         mathed_parse_normal(at, lex);
1432         operator=(*at->asHullInset());
1433 }
1434
1435
1436 int InsetMathHull::plaintext(Buffer const &, odocstream & os,
1437                              OutputParams const &) const
1438 {
1439         if (0 && display()) {
1440                 Dimension dim;
1441                 TextMetricsInfo mi;
1442                 metricsT(mi, dim);
1443                 TextPainter tpain(dim.width(), dim.height());
1444                 drawT(tpain, 0, dim.ascent());
1445                 tpain.show(os, 3);
1446                 // reset metrics cache to "real" values
1447                 //metrics();
1448                 return tpain.textheight();
1449         } else {
1450                 odocstringstream oss;
1451                 WriteStream wi(oss, false, true);
1452                 wi << cell(0);
1453
1454                 docstring const str = oss.str();
1455                 os << str;
1456                 return str.size();
1457         }
1458 }
1459
1460
1461 int InsetMathHull::docbook(Buffer const & buf, odocstream & os,
1462                            OutputParams const & runparams) const
1463 {
1464         MathStream ms(os);
1465         int res = 0;
1466         docstring name;
1467         if (getType() == hullSimple)
1468                 name = from_ascii("inlineequation");
1469         else
1470                 name = from_ascii("informalequation");
1471
1472         docstring bname = name;
1473         if (!label(0).empty())
1474                 bname += " id='" + sgml::cleanID(buf, runparams, label(0)) + "'";
1475         ms << MTag(bname);
1476
1477         odocstringstream ls;
1478         if (runparams.flavor == OutputParams::XML) {
1479                 ms << MTag(from_ascii("alt role='tex' "));
1480                 // Workaround for db2latex: db2latex always includes equations with
1481                 // \ensuremath{} or \begin{display}\end{display}
1482                 // so we strip LyX' math environment
1483                 WriteStream wi(ls, false, false);
1484                 InsetMathGrid::write(wi);
1485                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
1486                 ms << ETag(from_ascii("alt"));
1487                 ms << MTag(from_ascii("math"));
1488                 ms << ETag(from_ascii("alt"));
1489                 ms << MTag(from_ascii("math"));
1490                 InsetMathGrid::mathmlize(ms);
1491                 ms << ETag(from_ascii("math"));
1492         } else {
1493                 ms << MTag(from_ascii("alt role='tex'"));
1494                 res = latex(buf, ls, runparams);
1495                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
1496                 ms << ETag(from_ascii("alt"));
1497         }
1498
1499         ms << from_ascii("<graphic fileref=\"eqn/");
1500         if (!label(0).empty())
1501                 ms << sgml::cleanID(buf, runparams, label(0));
1502         else
1503                 ms << sgml::uniqueID(from_ascii("anon"));
1504
1505         if (runparams.flavor == OutputParams::XML)
1506                 ms << from_ascii("\"/>");
1507         else
1508                 ms << from_ascii("\">");
1509
1510         ms << ETag(name);
1511         return ms.line() + res;
1512 }
1513
1514
1515 void InsetMathHull::textString(Buffer const & buf, odocstream & os) const
1516 {
1517         plaintext(buf, os, OutputParams(0));
1518 }
1519
1520
1521 } // namespace lyx