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