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