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