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