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