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