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