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