]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathHull.C
fix reading UTF8 encoded symbol file
[lyx.git] / src / mathed / InsetMathHull.C
1 /**
2  * \file InsetMathHull.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetMathArray.h"
14 #include "InsetMathChar.h"
15 #include "InsetMathColor.h"
16 #include "MathData.h"
17 #include "InsetMathDelim.h"
18 #include "MathExtern.h"
19 #include "MathFactory.h"
20 #include "InsetMathHull.h"
21 #include "MathStream.h"
22 #include "MathParser.h"
23 #include "InsetMathSpace.h"
24 #include "MathStream.h"
25 #include "MathSupport.h"
26 #include "InsetMathRef.h"
27
28 #include "bufferview_funcs.h"
29 #include "lyxtext.h"
30
31 #include "buffer.h"
32 #include "bufferparams.h"
33 #include "BufferView.h"
34 #include "CutAndPaste.h"
35 #include "FuncStatus.h"
36 #include "LColor.h"
37 #include "LaTeXFeatures.h"
38 #include "cursor.h"
39 #include "debug.h"
40 #include "dispatchresult.h"
41 #include "funcrequest.h"
42 #include "gettext.h"
43 #include "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
64 namespace lyx {
65
66 using cap::grabAndEraseSelection;
67 using support::bformat;
68 using support::subst;
69
70 using std::endl;
71 using std::max;
72 using std::ostream;
73 using std::auto_ptr;
74 using std::istringstream;
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(docstring 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 '" << to_utf8(s) << "'" << endl;
134         return HullType(-1);
135 }
136
137
138 docstring hullName(HullType type)
139 {
140         switch (type) {
141                 case hullNone:       return from_ascii("none");
142                 case hullSimple:     return from_ascii("simple");
143                 case hullEquation:   return from_ascii("equation");
144                 case hullEqnArray:   return from_ascii("eqnarray");
145                 case hullAlign:      return from_ascii("align");
146                 case hullAlignAt:    return from_ascii("alignat");
147                 case hullXAlignAt:   return from_ascii("xalignat");
148                 case hullXXAlignAt:  return from_ascii("xxalignat");
149                 case hullMultline:   return from_ascii("multline");
150                 case hullGather:     return from_ascii("gather");
151                 case hullFlAlign:    return from_ascii("flalign");
152                 default:
153                         lyxerr << "unknown hull type '" << type << "'" << endl;
154                         return from_ascii("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 docstring InsetMathHull::standardFont() const
270 {
271         return from_ascii(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                 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, from_ascii("mathbf"));
311                 int l = 0;
312                 for (row_type row = 0; row < nrows(); ++row)
313                         l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
314
315                 if (l)
316                         dim.wid += 30 + l;
317         }
318
319         // make it at least as high as the current font
320         int asc = 0;
321         int des = 0;
322         math_font_max_dim(mi.base.font, asc, des);
323         dim.asc = max(dim.asc, asc);
324         dim.des = max(dim.des, des);
325
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, from_ascii("mathrm"));
350                         docstring const nl = nicelabel(row);
351                         pi.draw(xx, yy, nl);
352                 }
353         }
354         setPosCache(pi, x, y);
355 }
356
357
358 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
359 {
360         if (display()) {
361                 InsetMathGrid::metricsT(mi, dim);
362         } else {
363                 odocstringstream os;
364                 WriteStream wi(os, false, true);
365                 write(wi);
366                 dim.wid = os.str().size();
367                 dim.asc = 1;
368                 dim.des = 0;
369         }
370 }
371
372
373 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
374 {
375         if (display()) {
376                 InsetMathGrid::drawT(pain, x, y);
377         } else {
378                 odocstringstream os;
379                 WriteStream wi(os, false, true);
380                 write(wi);
381                 pain.draw(x, y, os.str().c_str());
382         }
383 }
384
385
386 namespace {
387
388 docstring const latex_string(InsetMathHull const & inset)
389 {
390         odocstringstream ls;
391         WriteStream wi(ls, false, false);
392         inset.write(wi);
393         return ls.str();
394 }
395
396 } // namespace anon
397
398
399 void InsetMathHull::addPreview(graphics::PreviewLoader & ploader) const
400 {
401         if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
402                 docstring const snippet = latex_string(*this);
403                 preview_->addPreview(snippet, ploader);
404         }
405 }
406
407
408 bool InsetMathHull::notifyCursorLeaves(LCursor & cur)
409 {
410         if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
411                 Buffer const & buffer = cur.buffer();
412                 docstring const snippet = latex_string(*this);
413                 preview_->addPreview(snippet, buffer);
414                 preview_->startLoading(buffer);
415         }
416         return false;
417 }
418
419
420 docstring InsetMathHull::label(row_type row) const
421 {
422         BOOST_ASSERT(row < nrows());
423         return label_[row];
424 }
425
426
427 void InsetMathHull::label(row_type row, docstring const & label)
428 {
429         //lyxerr << "setting label '" << label << "' for row " << row << endl;
430         label_[row] = label;
431 }
432
433
434 void InsetMathHull::numbered(row_type row, bool num)
435 {
436         nonum_[row] = !num;
437 }
438
439
440 bool InsetMathHull::numbered(row_type row) const
441 {
442         return !nonum_[row];
443 }
444
445
446 bool InsetMathHull::ams() const
447 {
448         return
449                 type_ == hullAlign ||
450                 type_ == hullFlAlign ||
451                 type_ == hullMultline ||
452                 type_ == hullGather ||
453                 type_ == hullAlignAt ||
454                 type_ == hullXAlignAt ||
455                 type_ == hullXXAlignAt;
456 }
457
458
459 bool InsetMathHull::display() const
460 {
461         return type_ != hullSimple && type_ != hullNone;
462 }
463
464
465 void InsetMathHull::getLabelList(Buffer const &, vector<docstring> & labels) const
466 {
467         for (row_type row = 0; row < nrows(); ++row)
468                 if (!label_[row].empty() && nonum_[row] != 1)
469                         labels.push_back(label_[row]);
470 }
471
472
473 bool InsetMathHull::numberedType() const
474 {
475         if (type_ == hullNone)
476                 return false;
477         if (type_ == hullSimple)
478                 return false;
479         if (type_ == hullXXAlignAt)
480                 return false;
481         for (row_type row = 0; row < nrows(); ++row)
482                 if (!nonum_[row])
483                         return true;
484         return false;
485 }
486
487
488 void InsetMathHull::validate(LaTeXFeatures & features) const
489 {
490         if (ams())
491                 features.require("amsmath");
492
493
494         // Validation is necessary only if not using AMS math.
495         // To be safe, we will always run mathedvalidate.
496         //if (features.amsstyle)
497         //  return;
498
499         features.require("boldsymbol");
500         //features.binom      = true;
501
502         InsetMathGrid::validate(features);
503 }
504
505
506 void InsetMathHull::header_write(WriteStream & os) const
507 {
508         bool n = numberedType();
509
510         switch(type_) {
511         case hullNone:
512                 break;
513
514         case hullSimple:
515                 os << '$';
516                 if (cell(0).empty())
517                         os << ' ';
518                 break;
519
520         case hullEquation:
521                 if (n)
522                         os << "\\begin{equation" << star(n) << "}\n";
523                 else
524                         os << "\\[\n";
525                 break;
526
527         case hullEqnArray:
528         case hullAlign:
529         case hullFlAlign:
530         case hullGather:
531         case hullMultline:
532                 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
533                 break;
534
535         case hullAlignAt:
536         case hullXAlignAt:
537                 os << "\\begin{" << hullName(type_) << star(n) << '}'
538                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
539                 break;
540
541         case hullXXAlignAt:
542                 os << "\\begin{" << hullName(type_) << '}'
543                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
544                 break;
545
546         default:
547                 os << "\\begin{unknown" << star(n) << '}';
548                 break;
549         }
550 }
551
552
553 void InsetMathHull::footer_write(WriteStream & os) const
554 {
555         bool n = numberedType();
556
557         switch(type_) {
558         case hullNone:
559                 os << "\n";
560                 break;
561
562         case hullSimple:
563                 os << '$';
564                 break;
565
566         case hullEquation:
567                 if (n)
568                         os << "\\end{equation" << star(n) << "}\n";
569                 else
570                         os << "\\]\n";
571                 break;
572
573         case hullEqnArray:
574         case hullAlign:
575         case hullFlAlign:
576         case hullAlignAt:
577         case hullXAlignAt:
578         case hullGather:
579         case hullMultline:
580                 os << "\\end{" << hullName(type_) << star(n) << "}\n";
581                 break;
582
583         case hullXXAlignAt:
584                 os << "\\end{" << hullName(type_) << "}\n";
585                 break;
586
587         default:
588                 os << "\\end{unknown" << star(n) << '}';
589                 break;
590         }
591 }
592
593
594 bool InsetMathHull::rowChangeOK() const
595 {
596         return
597                 type_ == hullEqnArray || type_ == hullAlign ||
598                 type_ == hullFlAlign || type_ == hullAlignAt ||
599                 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
600                 type_ == hullGather || type_ == hullMultline;
601 }
602
603
604 bool InsetMathHull::colChangeOK() const
605 {
606         return
607                 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
608                 type_ == hullXAlignAt || type_ == hullXXAlignAt;
609 }
610
611
612 void InsetMathHull::addRow(row_type row)
613 {
614         if (!rowChangeOK())
615                 return;
616         nonum_.insert(nonum_.begin() + row + 1, !numberedType());
617         label_.insert(label_.begin() + row + 1, docstring());
618         InsetMathGrid::addRow(row);
619 }
620
621
622 void InsetMathHull::swapRow(row_type row)
623 {
624         if (nrows() <= 1)
625                 return;
626         if (row + 1 == nrows())
627                 --row;
628         swap(nonum_[row], nonum_[row + 1]);
629         swap(label_[row], label_[row + 1]);
630         InsetMathGrid::swapRow(row);
631 }
632
633
634 void InsetMathHull::delRow(row_type row)
635 {
636         if (nrows() <= 1 || !rowChangeOK())
637                 return;
638         InsetMathGrid::delRow(row);
639         // The last dummy row has no number info nor a label.
640         // Test nrows() + 1 because we have already erased the row.
641         if (row == nrows() + 1)
642                 row--;
643         nonum_.erase(nonum_.begin() + row);
644         label_.erase(label_.begin() + row);
645 }
646
647
648 void InsetMathHull::addCol(col_type col)
649 {
650         if (!colChangeOK())
651                 return;
652         InsetMathGrid::addCol(col);
653 }
654
655
656 void InsetMathHull::delCol(col_type col)
657 {
658         if (ncols() <= 1 || !colChangeOK())
659                 return;
660         InsetMathGrid::delCol(col);
661 }
662
663
664 docstring InsetMathHull::nicelabel(row_type row) const
665 {
666         if (nonum_[row])
667                 return docstring();
668         if (label_[row].empty())
669                 return from_ascii("(#)");
670         // FIXME UNICODE
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                         docstring 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 '" << to_utf8(hullName(type_))
897                        << "' to '" << to_utf8(hullName(newtype))
898                        << "' not implemented" << endl;
899         }
900 }
901
902
903 docstring InsetMathHull::eolString(row_type row, bool emptyline, bool fragile) const
904 {
905         docstring 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(MathStream & os) const
933 {
934         InsetMathGrid::mathmlize(os);
935 }
936
937
938 void InsetMathHull::infoize(odocstream & 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         docstring dlang;
954         docstring extra;
955         idocstringstream iss(func.argument());
956         iss >> dlang >> extra;
957         if (extra.empty())
958                 extra = from_ascii("noextra");
959         std::string const lang = to_ascii(dlang);
960
961 #ifdef WITH_WARNINGS
962 #warning temporarily disabled
963         //if (cur.selection()) {
964         //      MathArray ar;
965         //      selGet(cur.ar);
966         //      lyxerr << "use selection: " << ar << endl;
967         //      insert(pipeThroughExtern(lang, extra, ar));
968         //      return;
969         //}
970 #endif
971
972         MathArray eq;
973         eq.push_back(MathAtom(new InsetMathChar('=')));
974
975         // go to first item in line
976         cur.idx() -= cur.idx() % ncols();
977         cur.pos() = 0;
978
979         if (getType() == hullSimple) {
980                 size_type pos = cur.cell().find_last(eq);
981                 MathArray ar;
982                 if (cur.inMathed() && cur.selection()) {
983                         // FIXME UNICODE
984                         asArray(grabAndEraseSelection(cur), ar);
985                 } else if (pos == cur.cell().size()) {
986                         ar = cur.cell();
987                         lyxerr << "use whole cell: " << ar << endl;
988                 } else {
989                         ar = MathArray(cur.cell().begin() + pos + 1, cur.cell().end());
990                         lyxerr << "use partial cell form pos: " << pos << endl;
991                 }
992                 cur.cell().append(eq);
993                 cur.cell().append(pipeThroughExtern(lang, extra, ar));
994                 cur.pos() = cur.lastpos();
995                 return;
996         }
997
998         if (getType() == hullEquation) {
999                 lyxerr << "use equation inset" << endl;
1000                 mutate(hullEqnArray);
1001                 MathArray & ar = cur.cell();
1002                 lyxerr << "use cell: " << ar << endl;
1003                 ++cur.idx();
1004                 cur.cell() = eq;
1005                 ++cur.idx();
1006                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1007                 // move to end of line
1008                 cur.pos() = cur.lastpos();
1009                 return;
1010         }
1011
1012         {
1013                 lyxerr << "use eqnarray" << endl;
1014                 cur.idx() += 2 - cur.idx() % ncols();
1015                 cur.pos() = 0;
1016                 MathArray ar = cur.cell();
1017                 lyxerr << "use cell: " << ar << endl;
1018 #ifdef WITH_WARNINGS
1019 #warning temporarily disabled
1020 #endif
1021                 addRow(cur.row());
1022                 ++cur.idx();
1023                 ++cur.idx();
1024                 cur.cell() = eq;
1025                 ++cur.idx();
1026                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1027                 cur.pos() = cur.lastpos();
1028         }
1029 }
1030
1031
1032 void InsetMathHull::doDispatch(LCursor & cur, FuncRequest & cmd)
1033 {
1034         //lyxerr << "action: " << cmd.action << endl;
1035         switch (cmd.action) {
1036
1037         case LFUN_FINISHED_LEFT:
1038         case LFUN_FINISHED_RIGHT:
1039         case LFUN_FINISHED_UP:
1040         case LFUN_FINISHED_DOWN:
1041                 //lyxerr << "action: " << cmd.action << endl;
1042                 InsetMathGrid::doDispatch(cur, cmd);
1043                 notifyCursorLeaves(cur);
1044                 cur.undispatched();
1045                 break;
1046
1047         case LFUN_BREAK_PARAGRAPH:
1048                 // just swallow this
1049                 break;
1050
1051         case LFUN_BREAK_LINE:
1052                 // some magic for the common case
1053                 if (type_ == hullSimple || type_ == hullEquation) {
1054                         recordUndoInset(cur);
1055                         bool const align =
1056                                 cur.bv().buffer()->params().use_amsmath == BufferParams::AMS_ON;
1057                         mutate(align ? hullAlign : hullEqnArray);
1058                         cur.idx() = 0;
1059                         cur.pos() = cur.lastpos();
1060                 }
1061                 InsetMathGrid::doDispatch(cur, cmd);
1062                 break;
1063
1064         case LFUN_MATH_NUMBER:
1065                 //lyxerr << "toggling all numbers" << endl;
1066                 if (display()) {
1067                         recordUndoInset(cur);
1068                         bool old = numberedType();
1069                         if (type_ == hullMultline)
1070                                 numbered(nrows() - 1, !old);
1071                         else
1072                                 for (row_type row = 0; row < nrows(); ++row)
1073                                         numbered(row, !old);
1074
1075                         cur.message(old ? _("No number") : _("Number"));
1076                 }
1077                 break;
1078
1079         case LFUN_MATH_NONUMBER:
1080                 if (display()) {
1081                         recordUndoInset(cur);
1082                         row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1083                         bool old = numbered(r);
1084                         cur.message(old ? _("No number") : _("Number"));
1085                         numbered(r, !old);
1086                 }
1087                 break;
1088
1089         case LFUN_LABEL_INSERT: {
1090                 recordUndoInset(cur);
1091                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1092                 docstring old_label = label(r);
1093                 docstring const default_label = from_ascii(
1094                         (lyxrc.label_init_length >= 0) ? "eq:" : "");
1095                 if (old_label.empty())
1096                         old_label = default_label;
1097
1098                 InsetCommandParams p("label");
1099                 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1100                 std::string const data = InsetCommandMailer::params2string("label", p);
1101
1102                 if (cmd.argument().empty())
1103                         cur.bv().showInsetDialog("label", data, 0);
1104                 else {
1105                         FuncRequest fr(LFUN_INSET_INSERT, data);
1106                         dispatch(cur, fr);
1107                 }
1108                 break;
1109         }
1110
1111         case LFUN_INSET_INSERT: {
1112                 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1113                 std::string const name = cmd.getArg(0);
1114                 if (name == "label") {
1115                         InsetCommandParams p("label");
1116                         InsetCommandMailer::string2params(name, to_utf8(cmd.argument()), p);
1117                         docstring str = p["name"];
1118                         recordUndoInset(cur);
1119                         row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1120                         str = support::trim(str);
1121                         if (!str.empty())
1122                                 numbered(r, true);
1123                         docstring old = label(r);
1124                         if (str != old) {
1125                                 cur.bv().buffer()->changeRefsIfUnique(old, str,
1126                                                         InsetBase::REF_CODE);
1127                                 label(r, str);
1128                         }
1129                         break;
1130                 }
1131                 InsetMathGrid::doDispatch(cur, cmd);
1132                 return;
1133         }
1134
1135         case LFUN_MATH_EXTERN:
1136                 recordUndoInset(cur);
1137                 doExtern(cur, cmd);
1138                 break;
1139
1140         case LFUN_MATH_MUTATE: {
1141                 recordUndoInset(cur);
1142                 row_type row = cur.row();
1143                 col_type col = cur.col();
1144                 mutate(hullType(cmd.argument()));
1145                 cur.idx() = row * ncols() + col;
1146                 if (cur.idx() > cur.lastidx()) {
1147                         cur.idx() = cur.lastidx();
1148                         cur.pos() = cur.lastpos();
1149                 }
1150                 if (cur.pos() > cur.lastpos())
1151                         cur.pos() = cur.lastpos();
1152                 //cur.dispatched(FINISHED);
1153                 break;
1154         }
1155
1156         case LFUN_MATH_DISPLAY: {
1157                 recordUndoInset(cur);
1158                 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1159                 cur.idx() = 0;
1160                 cur.pos() = cur.lastpos();
1161                 //cur.dispatched(FINISHED);
1162                 break;
1163         }
1164
1165         default:
1166                 InsetMathGrid::doDispatch(cur, cmd);
1167                 break;
1168         }
1169 }
1170
1171
1172 bool InsetMathHull::getStatus(LCursor & cur, FuncRequest const & cmd,
1173                 FuncStatus & status) const
1174 {
1175         switch (cmd.action) {
1176         case LFUN_FINISHED_LEFT:
1177         case LFUN_FINISHED_RIGHT:
1178         case LFUN_FINISHED_UP:
1179         case LFUN_FINISHED_DOWN:
1180                 status.enabled(true);
1181                 return true;
1182         case LFUN_BREAK_LINE:
1183         case LFUN_MATH_NUMBER:
1184         case LFUN_MATH_NONUMBER:
1185         case LFUN_MATH_EXTERN:
1186         case LFUN_MATH_MUTATE:
1187         case LFUN_MATH_DISPLAY:
1188                 // we handle these
1189                 status.enabled(true);
1190                 return true;
1191         case LFUN_LABEL_INSERT:
1192                 status.enabled(type_ != hullSimple);
1193                 return true;
1194         case LFUN_INSET_INSERT:
1195                 if (cmd.getArg(0) == "label") {
1196                         status.enabled(type_ != hullSimple);
1197                         return true;
1198                 }
1199                 return InsetMathGrid::getStatus(cur, cmd, status);
1200         case LFUN_TABULAR_FEATURE: {
1201                 istringstream is(to_utf8(cmd.argument()));
1202                 std::string s;
1203                 is >> s;
1204                 if (!rowChangeOK()
1205                     && (s == "append-row"
1206                         || s == "delete-row"
1207                         || s == "copy-row")) {
1208                         status.message(bformat(
1209                                 from_utf8(N_("Can't change number of rows in '%1$s'")),
1210                                 hullName(type_)));
1211                         status.enabled(false);
1212                         return true;
1213                 }
1214                 if (!colChangeOK()
1215                     && (s == "append-column"
1216                         || s == "delete-column"
1217                         || s == "copy-column")) {
1218                         status.message(bformat(
1219                                 from_utf8(N_("Can't change number of columns in '%1$s'")),
1220                                 hullName(type_)));
1221                         status.enabled(false);
1222                         return true;
1223                 }
1224                 if ((type_ == hullSimple
1225                   || type_ == hullEquation
1226                   || type_ == hullNone) &&
1227                     (s == "add-hline-above" || s == "add-hline-below")) {
1228                         status.message(bformat(
1229                                 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1230                                 hullName(type_)));
1231                         status.enabled(false);
1232                         return true;
1233                 }
1234                 if (s == "add-vline-left" || s == "add-vline-right") {
1235                         status.message(bformat(
1236                                 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1237                                 hullName(type_)));
1238                         status.enabled(false);
1239                         return true;
1240                 }
1241                 if (s == "valign-top" || s == "valign-middle"
1242                  || s == "valign-bottom" || s == "align-left"
1243                  || s == "align-center" || s == "align-right") {
1244                         status.enabled(false);
1245                         return true;
1246                 }
1247                 return InsetMathGrid::getStatus(cur, cmd, status);
1248         }
1249         default:
1250                 return InsetMathGrid::getStatus(cur, cmd, status);
1251         }
1252
1253         // This cannot really happen, but inserted to shut-up gcc
1254         return InsetMathGrid::getStatus(cur, cmd, status);
1255 }
1256
1257
1258 /////////////////////////////////////////////////////////////////////
1259
1260
1261
1262 // simply scrap this function if you want
1263 void InsetMathHull::mutateToText()
1264 {
1265 #if 0
1266         // translate to latex
1267         ostringstream os;
1268         latex(NULL, os, false, false);
1269         string str = os.str();
1270
1271         // insert this text
1272         LyXText * lt = view_->getLyXText();
1273         string::const_iterator cit = str.begin();
1274         string::const_iterator end = str.end();
1275         for (; cit != end; ++cit)
1276                 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1277
1278         // remove ourselves
1279         //dispatch(LFUN_ESCAPE);
1280 #endif
1281 }
1282
1283
1284 void InsetMathHull::handleFont(LCursor & cur, docstring const & arg,
1285         docstring const & font)
1286 {
1287         // this whole function is a hack and won't work for incremental font
1288         // changes...
1289         recordUndo(cur);
1290         if (cur.inset().asInsetMath()->name() == font)
1291                 cur.handleFont(to_utf8(font));
1292         else {
1293                 cur.handleNest(createInsetMath(font));
1294                 cur.insert(arg);
1295         }
1296 }
1297
1298
1299 void InsetMathHull::handleFont2(LCursor & cur, docstring const & arg)
1300 {
1301         recordUndo(cur);
1302         LyXFont font;
1303         bool b;
1304         bv_funcs::string2font(to_utf8(arg), font, b);
1305         if (font.color() != LColor::inherit) {
1306                 MathAtom at = MathAtom(new InsetMathColor(true, font.color()));
1307                 cur.handleNest(at, 0);
1308         }
1309 }
1310
1311
1312 void InsetMathHull::edit(LCursor & cur, bool left)
1313 {
1314         cur.push(*this);
1315         left ? idxFirst(cur) : idxLast(cur);
1316 }
1317
1318
1319 docstring const InsetMathHull::editMessage() const
1320 {
1321         return _("Math editor mode");
1322 }
1323
1324
1325 void InsetMathHull::revealCodes(LCursor & cur) const
1326 {
1327         if (!cur.inMathed())
1328                 return;
1329         odocstringstream os;
1330         cur.info(os);
1331         cur.message(os.str());
1332 /*
1333         // write something to the minibuffer
1334         // translate to latex
1335         cur.markInsert(bv);
1336         ostringstream os;
1337         write(NULL, os);
1338         string str = os.str();
1339         cur.markErase(bv);
1340         string::size_type pos = 0;
1341         string res;
1342         for (string::iterator it = str.begin(); it != str.end(); ++it) {
1343                 if (*it == '\n')
1344                         res += ' ';
1345                 else if (*it == '\0') {
1346                         res += "  -X-  ";
1347                         pos = it - str.begin();
1348                 }
1349                 else
1350                         res += *it;
1351         }
1352         if (pos > 30)
1353                 res = res.substr(pos - 30);
1354         if (res.size() > 60)
1355                 res = res.substr(0, 60);
1356         cur.message(res);
1357 */
1358 }
1359
1360
1361 InsetBase::Code InsetMathHull::lyxCode() const
1362 {
1363         return MATH_CODE;
1364 }
1365
1366
1367 /////////////////////////////////////////////////////////////////////
1368
1369
1370 #if 0
1371 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1372                                      bool, bool)
1373 {
1374 #ifdef WITH_WARNINGS
1375 #warning completely broken
1376 #endif
1377         static InsetMathHull * lastformula = 0;
1378         static CursorBase current = DocIterator(ibegin(nucleus()));
1379         static MathArray ar;
1380         static string laststr;
1381
1382         if (lastformula != this || laststr != str) {
1383                 //lyxerr << "reset lastformula to " << this << endl;
1384                 lastformula = this;
1385                 laststr = str;
1386                 current = ibegin(nucleus());
1387                 ar.clear();
1388                 mathed_parse_cell(ar, str);
1389         } else {
1390                 increment(current);
1391         }
1392         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1393
1394         for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1395                 CursorSlice & top = it.back();
1396                 MathArray const & a = top.asInsetMath()->cell(top.idx_);
1397                 if (a.matchpart(ar, top.pos_)) {
1398                         bv->cursor().setSelection(it, ar.size());
1399                         current = it;
1400                         top.pos_ += ar.size();
1401                         bv->update();
1402                         return true;
1403                 }
1404         }
1405
1406         //lyxerr << "not found!" << endl;
1407         lastformula = 0;
1408         return false;
1409 }
1410 #endif
1411
1412
1413 void InsetMathHull::write(Buffer const &, std::ostream & os) const
1414 {
1415         odocstringstream oss;
1416         WriteStream wi(oss, false, false);
1417         oss << "Formula ";
1418         write(wi);
1419         os << to_utf8(oss.str());
1420 }
1421
1422
1423 void InsetMathHull::read(Buffer const &, LyXLex & lex)
1424 {
1425         MathAtom at;
1426         mathed_parse_normal(at, lex);
1427         operator=(*at->asHullInset());
1428 }
1429
1430
1431 int InsetMathHull::plaintext(Buffer const &, odocstream & os,
1432                         OutputParams const &) const
1433 {
1434         if (0 && display()) {
1435                 Dimension dim;
1436                 TextMetricsInfo mi;
1437                 metricsT(mi, dim);
1438                 TextPainter tpain(dim.width(), dim.height());
1439                 drawT(tpain, 0, dim.ascent());
1440                 tpain.show(os, 3);
1441                 // reset metrics cache to "real" values
1442                 //metrics();
1443                 return tpain.textheight();
1444         } else {
1445                 WriteStream wi(os, false, true);
1446                 wi << cell(0);
1447                 return wi.line();
1448         }
1449 }
1450
1451
1452 int InsetMathHull::docbook(Buffer const & buf, odocstream & os,
1453                           OutputParams const & runparams) const
1454 {
1455         MathStream ms(os);
1456         int res = 0;
1457         docstring name;
1458         if (getType() == hullSimple)
1459                 name = from_ascii("inlineequation");
1460         else
1461                 name = from_ascii("informalequation");
1462
1463         docstring bname = name;
1464         if (!label(0).empty())
1465                 bname += " id='" + sgml::cleanID(buf, runparams, label(0)) + "'";
1466         ms << MTag(bname);
1467
1468         odocstringstream ls;
1469         if (runparams.flavor == OutputParams::XML) {
1470                 ms << MTag(from_ascii("alt role='tex' "));
1471                 // Workaround for db2latex: db2latex always includes equations with
1472                 // \ensuremath{} or \begin{display}\end{display}
1473                 // so we strip LyX' math environment
1474                 WriteStream wi(ls, false, false);
1475                 InsetMathGrid::write(wi);
1476                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
1477                 ms << ETag(from_ascii("alt"));
1478                 ms << MTag(from_ascii("math"));
1479                 ms << ETag(from_ascii("alt"));
1480                 ms << MTag(from_ascii("math"));
1481                 InsetMathGrid::mathmlize(ms);
1482                 ms << ETag(from_ascii("math"));
1483         } else {
1484                 ms << MTag(from_ascii("alt role='tex'"));
1485                 res = latex(buf, ls, runparams);
1486                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
1487                 ms << ETag(from_ascii("alt"));
1488         }
1489
1490         ms << from_ascii("<graphic fileref=\"eqn/");
1491         if (!label(0).empty())
1492                 ms << sgml::cleanID(buf, runparams, label(0));
1493         else
1494                 ms << sgml::uniqueID(from_ascii("anon"));
1495
1496         if (runparams.flavor == OutputParams::XML)
1497                 ms << from_ascii("\"/>");
1498         else
1499                 ms << from_ascii("\">");
1500
1501         ms << ETag(name);
1502         return ms.line() + res;
1503 }
1504
1505
1506 int InsetMathHull::textString(Buffer const & buf, odocstream & os,
1507                        OutputParams const & op) const
1508 {
1509         return plaintext(buf, os, op);
1510 }
1511
1512
1513 } // namespace lyx