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