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