]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathHull.cpp
This patch introduces an optional argument to Buffer::updateLabels(), so
[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                 reloadPreview(inset_pos);
465         }
466 }
467
468
469 void InsetMathHull::reloadPreview(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         // start preview  
488         docstring const snippet = macro_preamble.str() + latexString(*this);  
489         LYXERR(Debug::MACROS, "Preview snippet: " << snippet);  
490         preview_->addPreview(snippet, *buffer);  
491         preview_->startLoading(*buffer);  
492 }  
493
494 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
495 {
496         if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
497                 reloadPreview(old);
498                 cur.updateFlags(Update::Force);
499         }
500         return false;
501 }
502
503
504 docstring InsetMathHull::label(row_type row) const
505 {
506         LASSERT(row < nrows(), /**/);
507         if (InsetLabel * il = label_[row])
508                 return il->screenLabel();
509         return docstring();
510 }
511
512
513 void InsetMathHull::label(row_type row, docstring const & label)
514 {
515         //lyxerr << "setting label '" << label << "' for row " << row << endl;
516         if (label_[row]) {
517                 if (label.empty()) {
518                         delete label_[row];
519                         label_[row] = dummy_pointer;
520                         // We need an update of the Buffer reference cache.
521                         // This is achieved by updateLabels().
522                         if (buffer_)
523                                 buffer().updateLabels();
524                 } else {
525                         if (buffer_)
526                                 label_[row]->updateCommand(label);
527                         else
528                                 label_[row]->setParam("name", label);
529                 }
530                 return;
531         }
532         InsetCommandParams p(LABEL_CODE);
533         p["name"] = label;
534         label_[row] = new InsetLabel(buffer_, p);
535         if (buffer_)
536                 label_[row]->setBuffer(buffer());
537 }
538
539
540 void InsetMathHull::numbered(row_type row, bool num)
541 {
542         nonum_[row] = !num;
543         if (nonum_[row] && label_[row]) {
544                 delete label_[row];
545                 label_[row] = 0;
546                 if (!buffer_) {
547                         // The buffer is set at the end of readInset.
548                         // When parsing the inset, buffer_ is 0.
549                         return;
550                 }
551                 // We need an update of the Buffer reference cache.
552                 // This is achieved by updateLabels().
553                 buffer().updateLabels();
554         }
555 }
556
557
558 bool InsetMathHull::numbered(row_type row) const
559 {
560         return !nonum_[row];
561 }
562
563
564 bool InsetMathHull::ams() const
565 {
566         return type_ == hullAlign
567                 || type_ == hullFlAlign
568                 || type_ == hullMultline
569                 || type_ == hullGather
570                 || type_ == hullAlignAt
571                 || type_ == hullXAlignAt
572                 || type_ == hullXXAlignAt;
573 }
574
575
576 Inset::DisplayType InsetMathHull::display() const
577 {
578         if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
579                 return Inline;
580         return AlignCenter;
581 }
582
583 bool InsetMathHull::numberedType() const
584 {
585         if (type_ == hullNone)
586                 return false;
587         if (type_ == hullSimple)
588                 return false;
589         if (type_ == hullXXAlignAt)
590                 return false;
591         if (type_ == hullRegexp)
592                 return false;
593         for (row_type row = 0; row < nrows(); ++row)
594                 if (!nonum_[row])
595                         return true;
596         return false;
597 }
598
599
600 void InsetMathHull::validate(LaTeXFeatures & features) const
601 {
602         if (ams())
603                 features.require("amsmath");
604
605         // Validation is necessary only if not using AMS math.
606         // To be safe, we will always run mathedvalidate.
607         //if (features.amsstyle)
608         //  return;
609
610         //features.binom      = true;
611
612         InsetMathGrid::validate(features);
613 }
614
615
616 void InsetMathHull::header_write(WriteStream & os) const
617 {
618         bool n = numberedType();
619
620         switch(type_) {
621         case hullNone:
622                 break;
623
624         case hullSimple:
625                 os << '$';
626                 if (cell(0).empty())
627                         os << ' ';
628                 break;
629
630         case hullEquation:
631                 if (n)
632                         os << "\\begin{equation" << star(n) << "}\n";
633                 else
634                         os << "\\[\n";
635                 break;
636
637         case hullEqnArray:
638         case hullAlign:
639         case hullFlAlign:
640         case hullGather:
641         case hullMultline:
642                 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
643                 break;
644
645         case hullAlignAt:
646         case hullXAlignAt:
647                 os << "\\begin{" << hullName(type_) << star(n) << '}'
648                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
649                 break;
650
651         case hullXXAlignAt:
652                 os << "\\begin{" << hullName(type_) << '}'
653                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
654                 break;
655
656         case hullRegexp:
657                 os << "\\regexp{";
658                 break;
659
660         default:
661                 os << "\\begin{unknown" << star(n) << '}';
662                 break;
663         }
664 }
665
666
667 void InsetMathHull::footer_write(WriteStream & os) const
668 {
669         bool n = numberedType();
670
671         switch(type_) {
672         case hullNone:
673                 os << "\n";
674                 break;
675
676         case hullSimple:
677                 os << '$';
678                 break;
679
680         case hullEquation:
681                 if (n)
682                         os << "\\end{equation" << star(n) << "}\n";
683                 else
684                         os << "\\]\n";
685                 break;
686
687         case hullEqnArray:
688         case hullAlign:
689         case hullFlAlign:
690         case hullAlignAt:
691         case hullXAlignAt:
692         case hullGather:
693         case hullMultline:
694                 os << "\\end{" << hullName(type_) << star(n) << "}\n";
695                 break;
696
697         case hullXXAlignAt:
698                 os << "\\end{" << hullName(type_) << "}\n";
699                 break;
700
701         case hullRegexp:
702                 os << "}";
703                 break;
704
705         default:
706                 os << "\\end{unknown" << star(n) << '}';
707                 break;
708         }
709 }
710
711
712 bool InsetMathHull::rowChangeOK() const
713 {
714         return
715                 type_ == hullEqnArray || type_ == hullAlign ||
716                 type_ == hullFlAlign || type_ == hullAlignAt ||
717                 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
718                 type_ == hullGather || type_ == hullMultline;
719 }
720
721
722 bool InsetMathHull::colChangeOK() const
723 {
724         return
725                 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
726                 type_ == hullXAlignAt || type_ == hullXXAlignAt;
727 }
728
729
730 void InsetMathHull::addRow(row_type row)
731 {
732         if (!rowChangeOK())
733                 return;
734
735         bool numbered = numberedType();
736         docstring lab;
737         if (type_ == hullMultline) {
738                 if (row + 1 == nrows())  {
739                         nonum_[row] = true;
740                         lab = label(row);
741                 } else
742                         numbered = false;
743         }
744
745         nonum_.insert(nonum_.begin() + row + 1, !numbered);
746         label_.insert(label_.begin() + row + 1, dummy_pointer);
747         if (!lab.empty())
748                 label(row + 1, lab);
749         InsetMathGrid::addRow(row);
750 }
751
752
753 void InsetMathHull::swapRow(row_type row)
754 {
755         if (nrows() <= 1)
756                 return;
757         if (row + 1 == nrows())
758                 --row;
759         // gcc implements the standard std::vector<bool> which is *not* a container:
760         //   http://www.gotw.ca/publications/N1185.pdf
761         // As a results, it doesn't like this:
762         //      swap(nonum_[row], nonum_[row + 1]);
763         // so we do it manually:
764         bool const b = nonum_[row];
765         nonum_[row] = nonum_[row + 1];
766         nonum_[row + 1] = b;
767         swap(label_[row], label_[row + 1]);
768         InsetMathGrid::swapRow(row);
769 }
770
771
772 void InsetMathHull::delRow(row_type row)
773 {
774         if (nrows() <= 1 || !rowChangeOK())
775                 return;
776         if (row + 1 == nrows() && type_ == hullMultline) {
777                 bool const b = nonum_[row - 1];
778                 nonum_[row - 1] = nonum_[row];
779                 nonum_[row] = b;
780                 swap(label_[row - 1], label_[row]);
781                 InsetMathGrid::delRow(row);
782                 return;
783         }
784         InsetMathGrid::delRow(row);
785         // The last dummy row has no number info nor a label.
786         // Test nrows() + 1 because we have already erased the row.
787         if (row == nrows() + 1)
788                 row--;
789         nonum_.erase(nonum_.begin() + row);
790         delete label_[row];
791         label_.erase(label_.begin() + row);
792 }
793
794
795 void InsetMathHull::addCol(col_type col)
796 {
797         if (!colChangeOK())
798                 return;
799         InsetMathGrid::addCol(col);
800 }
801
802
803 void InsetMathHull::delCol(col_type col)
804 {
805         if (ncols() <= 1 || !colChangeOK())
806                 return;
807         InsetMathGrid::delCol(col);
808 }
809
810
811 docstring InsetMathHull::nicelabel(row_type row) const
812 {
813         if (nonum_[row])
814                 return docstring();
815         if (!label_[row])
816                 return from_ascii("(#)");
817         return '(' + label_[row]->screenLabel() + from_ascii(", #)");
818 }
819
820
821 void InsetMathHull::glueall()
822 {
823         MathData ar;
824         for (idx_type i = 0; i < nargs(); ++i)
825                 ar.append(cell(i));
826         *this = InsetMathHull(buffer_, hullSimple);
827         cell(0) = ar;
828         setDefaults();
829 }
830
831
832 void InsetMathHull::splitTo2Cols()
833 {
834         LASSERT(ncols() == 1, /**/);
835         InsetMathGrid::addCol(1);
836         for (row_type row = 0; row < nrows(); ++row) {
837                 idx_type const i = 2 * row;
838                 pos_type pos = firstRelOp(cell(i));
839                 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
840                 cell(i).erase(pos, cell(i).size());
841         }
842 }
843
844
845 void InsetMathHull::splitTo3Cols()
846 {
847         LASSERT(ncols() < 3, /**/);
848         if (ncols() < 2)
849                 splitTo2Cols();
850         InsetMathGrid::addCol(2);
851         for (row_type row = 0; row < nrows(); ++row) {
852                 idx_type const i = 3 * row + 1;
853                 if (cell(i).size()) {
854                         cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
855                         cell(i).erase(1, cell(i).size());
856                 }
857         }
858 }
859
860
861 void InsetMathHull::changeCols(col_type cols)
862 {
863         if (ncols() == cols)
864                 return;
865         else if (ncols() < cols) {
866                 // split columns
867                 if (cols < 3)
868                         splitTo2Cols();
869                 else {
870                         splitTo3Cols();
871                         while (ncols() < cols)
872                                 InsetMathGrid::addCol(ncols());
873                 }
874                 return;
875         }
876
877         // combine columns
878         for (row_type row = 0; row < nrows(); ++row) {
879                 idx_type const i = row * ncols();
880                 for (col_type col = cols; col < ncols(); ++col) {
881                         cell(i + cols - 1).append(cell(i + col));
882                 }
883         }
884         // delete columns
885         while (ncols() > cols) {
886                 InsetMathGrid::delCol(ncols() - 1);
887         }
888 }
889
890
891 HullType InsetMathHull::getType() const
892 {
893         return type_;
894 }
895
896
897 void InsetMathHull::setType(HullType type)
898 {
899         type_ = type;
900         setDefaults();
901 }
902
903
904 void InsetMathHull::mutate(HullType newtype)
905 {
906         //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
907
908         // we try to move along the chain
909         // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
910         //                                     ^                                     |
911         //                                     +-------------------------------------+
912         // we use eqnarray as intermediate type for mutations that are not
913         // directly supported because it handles labels and numbering for
914         // "down mutation".
915
916         if (newtype == type_) {
917                 // done
918         }
919
920         else if (newtype < hullNone) {
921                 // unknown type
922                 dump();
923         }
924
925         else if (type_ == hullNone) {
926                 setType(hullSimple);
927                 numbered(0, false);
928                 mutate(newtype);
929         }
930
931         else if (type_ == hullSimple) {
932                 if (newtype == hullNone) {
933                         setType(hullNone);
934                         numbered(0, false);
935                 } else {
936                         setType(hullEquation);
937                         numbered(0, false);
938                         mutate(newtype);
939                 }
940         }
941
942         else if (type_ == hullEquation) {
943                 if (newtype < type_) {
944                         setType(hullSimple);
945                         numbered(0, false);
946                         mutate(newtype);
947                 } else if (newtype == hullEqnArray) {
948                         // split it "nicely" on the first relop
949                         splitTo3Cols();
950                         setType(hullEqnArray);
951                 } else if (newtype == hullMultline || newtype == hullGather) {
952                         setType(newtype);
953                 } else {
954                         // split it "nicely"
955                         splitTo2Cols();
956                         setType(hullAlign);
957                         mutate(newtype);
958                 }
959         }
960
961         else if (type_ == hullEqnArray) {
962                 if (newtype < type_) {
963                         // set correct (no)numbering
964                         nonum_[0] = true;
965                         for (row_type row = 0; row < nrows(); ++row) {
966                                 if (!nonum_[row]) {
967                                         nonum_[0] = false;
968                                         break;
969                                 }
970                         }
971
972                         // set first non-empty label
973                         for (row_type row = 0; row < nrows(); ++row) {
974                                 if (label_[row]) {
975                                         label_[0] = label_[row];
976                                         break;
977                                 }
978                         }
979
980                         glueall();
981                         mutate(newtype);
982                 } else { // align & Co.
983                         changeCols(2);
984                         setType(hullAlign);
985                         mutate(newtype);
986                 }
987         }
988
989         else if (type_ ==  hullAlign || type_ == hullAlignAt ||
990                  type_ == hullXAlignAt || type_ == hullFlAlign) {
991                 if (newtype < hullAlign) {
992                         changeCols(3);
993                         setType(hullEqnArray);
994                         mutate(newtype);
995                 } else if (newtype == hullGather || newtype == hullMultline) {
996                         changeCols(1);
997                         setType(newtype);
998                 } else if (newtype ==   hullXXAlignAt) {
999                         for (row_type row = 0; row < nrows(); ++row)
1000                                 numbered(row, false);
1001                         setType(newtype);
1002                 } else {
1003                         setType(newtype);
1004                 }
1005         }
1006
1007         else if (type_ == hullXXAlignAt) {
1008                 for (row_type row = 0; row < nrows(); ++row)
1009                         numbered(row, false);
1010                 if (newtype < hullAlign) {
1011                         changeCols(3);
1012                         setType(hullEqnArray);
1013                         mutate(newtype);
1014                 } else if (newtype == hullGather || newtype == hullMultline) {
1015                         changeCols(1);
1016                         setType(newtype);
1017                 } else {
1018                         setType(newtype);
1019                 }
1020         }
1021
1022         else if (type_ == hullMultline || type_ == hullGather) {
1023                 if (newtype == hullGather || newtype == hullMultline)
1024                         setType(newtype);
1025                 else if (newtype == hullAlign || newtype == hullFlAlign  ||
1026                          newtype == hullAlignAt || newtype == hullXAlignAt) {
1027                         splitTo2Cols();
1028                         setType(newtype);
1029                 } else if (newtype ==   hullXXAlignAt) {
1030                         splitTo2Cols();
1031                         for (row_type row = 0; row < nrows(); ++row)
1032                                 numbered(row, false);
1033                         setType(newtype);
1034                 } else {
1035                         splitTo3Cols();
1036                         setType(hullEqnArray);
1037                         mutate(newtype);
1038                 }
1039         }
1040
1041         else {
1042                 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1043                        << "' to '" << to_utf8(hullName(newtype))
1044                        << "' not implemented" << endl;
1045         }
1046 }
1047
1048
1049 docstring InsetMathHull::eolString(row_type row, bool fragile) const
1050 {
1051         docstring res;
1052         if (numberedType()) {
1053                 if (label_[row] && !nonum_[row])
1054                         res += "\\label{" + label_[row]->getParam("name") + '}';
1055                 if (nonum_[row] && (type_ != hullMultline))
1056                         res += "\\nonumber ";
1057         }
1058         return res + InsetMathGrid::eolString(row, fragile);
1059 }
1060
1061
1062 void InsetMathHull::write(WriteStream & os) const
1063 {
1064         ModeSpecifier specifier(os, MATH_MODE);
1065         header_write(os);
1066         InsetMathGrid::write(os);
1067         footer_write(os);
1068 }
1069
1070
1071 void InsetMathHull::normalize(NormalStream & os) const
1072 {
1073         os << "[formula " << hullName(type_) << ' ';
1074         InsetMathGrid::normalize(os);
1075         os << "] ";
1076 }
1077
1078
1079 void InsetMathHull::mathmlize(MathStream & os) const
1080 {
1081         InsetMathGrid::mathmlize(os);
1082 }
1083
1084
1085 void InsetMathHull::infoize(odocstream & os) const
1086 {
1087         os << "Type: " << hullName(type_);
1088 }
1089
1090
1091 void InsetMathHull::check() const
1092 {
1093         LASSERT(nonum_.size() == nrows(), /**/);
1094         LASSERT(label_.size() == nrows(), /**/);
1095 }
1096
1097
1098 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1099 {
1100         docstring dlang;
1101         docstring extra;
1102         idocstringstream iss(func.argument());
1103         iss >> dlang >> extra;
1104         if (extra.empty())
1105                 extra = from_ascii("noextra");
1106         string const lang = to_ascii(dlang);
1107
1108         // FIXME: temporarily disabled
1109         //if (cur.selection()) {
1110         //      MathData ar;
1111         //      selGet(cur.ar);
1112         //      lyxerr << "use selection: " << ar << endl;
1113         //      insert(pipeThroughExtern(lang, extra, ar));
1114         //      return;
1115         //}
1116
1117         MathData eq;
1118         eq.push_back(MathAtom(new InsetMathChar('=')));
1119
1120         // go to first item in line
1121         cur.idx() -= cur.idx() % ncols();
1122         cur.pos() = 0;
1123
1124         if (getType() == hullSimple) {
1125                 size_type pos = cur.cell().find_last(eq);
1126                 MathData ar;
1127                 if (cur.inMathed() && cur.selection()) {
1128                         asArray(grabAndEraseSelection(cur), ar);
1129                 } else if (pos == cur.cell().size()) {
1130                         ar = cur.cell();
1131                         lyxerr << "use whole cell: " << ar << endl;
1132                 } else {
1133                         ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1134                         lyxerr << "use partial cell form pos: " << pos << endl;
1135                 }
1136                 cur.cell().append(eq);
1137                 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1138                 cur.pos() = cur.lastpos();
1139                 return;
1140         }
1141
1142         if (getType() == hullEquation) {
1143                 lyxerr << "use equation inset" << endl;
1144                 mutate(hullEqnArray);
1145                 MathData & ar = cur.cell();
1146                 lyxerr << "use cell: " << ar << endl;
1147                 ++cur.idx();
1148                 cur.cell() = eq;
1149                 ++cur.idx();
1150                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1151                 // move to end of line
1152                 cur.pos() = cur.lastpos();
1153                 return;
1154         }
1155
1156         {
1157                 lyxerr << "use eqnarray" << endl;
1158                 cur.idx() += 2 - cur.idx() % ncols();
1159                 cur.pos() = 0;
1160                 MathData ar = cur.cell();
1161                 lyxerr << "use cell: " << ar << endl;
1162                 // FIXME: temporarily disabled
1163                 addRow(cur.row());
1164                 ++cur.idx();
1165                 ++cur.idx();
1166                 cur.cell() = eq;
1167                 ++cur.idx();
1168                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1169                 cur.pos() = cur.lastpos();
1170         }
1171 }
1172
1173
1174 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1175 {
1176         //lyxerr << "action: " << cmd.action << endl;
1177         switch (cmd.action) {
1178
1179         case LFUN_FINISHED_BACKWARD:
1180         case LFUN_FINISHED_FORWARD:
1181         case LFUN_FINISHED_RIGHT:
1182         case LFUN_FINISHED_LEFT:
1183                 //lyxerr << "action: " << cmd.action << endl;
1184                 InsetMathGrid::doDispatch(cur, cmd);
1185                 cur.undispatched();
1186                 break;
1187
1188         case LFUN_BREAK_PARAGRAPH:
1189                 // just swallow this
1190                 break;
1191
1192         case LFUN_NEWLINE_INSERT:
1193                 // some magic for the common case
1194                 if (type_ == hullSimple || type_ == hullEquation) {
1195                         cur.recordUndoInset();
1196                         bool const align =
1197                                 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1198                         mutate(align ? hullAlign : hullEqnArray);
1199                         cur.idx() = nrows() * ncols() - 1;
1200                         cur.pos() = cur.lastpos();
1201                 }
1202                 InsetMathGrid::doDispatch(cur, cmd);
1203                 break;
1204
1205         case LFUN_MATH_NUMBER_TOGGLE: {
1206                 //lyxerr << "toggling all numbers" << endl;
1207                 cur.recordUndoInset();
1208                 bool old = numberedType();
1209                 if (type_ == hullMultline)
1210                         numbered(nrows() - 1, !old);
1211                 else
1212                         for (row_type row = 0; row < nrows(); ++row)
1213                                 numbered(row, !old);
1214
1215                 cur.message(old ? _("No number") : _("Number"));
1216                 break;
1217         }
1218
1219         case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1220                 cur.recordUndoInset();
1221                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1222                 bool old = numbered(r);
1223                 cur.message(old ? _("No number") : _("Number"));
1224                 numbered(r, !old);
1225                 break;
1226         }
1227
1228         case LFUN_LABEL_INSERT: {
1229                 cur.recordUndoInset();
1230                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1231                 docstring old_label = label(r);
1232                 docstring const default_label = from_ascii(
1233                         (lyxrc.label_init_length >= 0) ? "eq:" : "");
1234                 if (old_label.empty())
1235                         old_label = default_label;
1236
1237                 InsetCommandParams p(LABEL_CODE);
1238                 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1239                 string const data = InsetCommand::params2string("label", p);
1240
1241                 if (cmd.argument().empty())
1242                         cur.bv().showDialog("label", data);
1243                 else {
1244                         FuncRequest fr(LFUN_INSET_INSERT, data);
1245                         dispatch(cur, fr);
1246                 }
1247                 break;
1248         }
1249
1250         case LFUN_LABEL_COPY_AS_REF: {
1251                 row_type row;
1252                 if (cmd.argument().empty() && &cur.inset() == this)
1253                         // if there is no argument and we're inside math, we retrieve
1254                         // the row number from the cursor position.
1255                         row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1256                 else {
1257                         // if there is an argument, find the corresponding label, else
1258                         // check whether there is at least one label.
1259                         for (row = 0; row != nrows(); ++row)
1260                                 if (!nonum_[row] && label_[row]
1261                                           && (cmd.argument().empty() || label(row) == cmd.argument()))
1262                                         break;
1263                 }
1264
1265                 if (row == nrows())
1266                         break;
1267
1268                 InsetCommandParams p(REF_CODE, "ref");
1269                 p["reference"] = label(row);
1270                 cap::clearSelection();
1271                 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1272                 break;
1273         }
1274
1275         case LFUN_WORD_DELETE_FORWARD:
1276         case LFUN_CHAR_DELETE_FORWARD:
1277                 if (col(cur.idx()) + 1 == ncols()
1278                     && cur.pos() == cur.lastpos()
1279                     && !cur.selection()) {
1280                         if (!label(row(cur.idx())).empty()) {
1281                                 cur.recordUndoInset();
1282                                 label(row(cur.idx()), docstring());
1283                         } else if (numbered(row(cur.idx()))) {
1284                                 cur.recordUndoInset();
1285                                 numbered(row(cur.idx()), false);
1286                         } else {
1287                                 InsetMathGrid::doDispatch(cur, cmd);
1288                                 return;
1289                         }
1290                 } else {
1291                         InsetMathGrid::doDispatch(cur, cmd);
1292                         return;
1293                 }
1294                 break;
1295
1296         case LFUN_INSET_INSERT: {
1297                 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1298                 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1299                 string const name = cmd.getArg(0);
1300                 if (name == "label") {
1301                         InsetCommandParams p(LABEL_CODE);
1302                         InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1303                         docstring str = p["name"];
1304                         cur.recordUndoInset();
1305                         row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1306                         str = trim(str);
1307                         if (!str.empty())
1308                                 numbered(r, true);
1309                         docstring old = label(r);
1310                         if (str != old) {
1311                                 if (label_[r])
1312                                         // The label will take care of the reference update.
1313                                         label(r, str);
1314                                 else {
1315                                         label(r, str);
1316                                         // Newly created inset so initialize it.
1317                                         label_[r]->initView();
1318                                 }
1319                         }
1320                         break;
1321                 }
1322                 InsetMathGrid::doDispatch(cur, cmd);
1323                 return;
1324         }
1325
1326         case LFUN_MATH_EXTERN:
1327                 cur.recordUndoInset();
1328                 doExtern(cur, cmd);
1329                 break;
1330
1331         case LFUN_MATH_MUTATE: {
1332                 cur.recordUndoInset();
1333                 row_type row = cur.row();
1334                 col_type col = cur.col();
1335                 mutate(hullType(cmd.argument()));
1336                 cur.idx() = row * ncols() + col;
1337                 if (cur.idx() > cur.lastidx()) {
1338                         cur.idx() = cur.lastidx();
1339                         cur.pos() = cur.lastpos();
1340                 }
1341                 if (cur.pos() > cur.lastpos())
1342                         cur.pos() = cur.lastpos();
1343
1344                 // FIXME: find some more clever handling of the selection,
1345                 // i.e. preserve it.
1346                 cur.clearSelection();
1347                 //cur.dispatched(FINISHED);
1348                 break;
1349         }
1350
1351         case LFUN_MATH_DISPLAY: {
1352                 cur.recordUndoInset();
1353                 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1354                 cur.idx() = 0;
1355                 cur.pos() = cur.lastpos();
1356                 //cur.dispatched(FINISHED);
1357                 break;
1358         }
1359
1360         default:
1361                 InsetMathGrid::doDispatch(cur, cmd);
1362                 break;
1363         }
1364 }
1365
1366
1367 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1368                 FuncStatus & status) const
1369 {
1370         switch (cmd.action) {
1371         case LFUN_FINISHED_BACKWARD:
1372         case LFUN_FINISHED_FORWARD:
1373         case LFUN_FINISHED_RIGHT:
1374         case LFUN_FINISHED_LEFT:
1375         case LFUN_UP:
1376         case LFUN_DOWN:
1377         case LFUN_NEWLINE_INSERT:
1378         case LFUN_MATH_EXTERN:
1379         case LFUN_MATH_DISPLAY:
1380                 // we handle these
1381                 status.setEnabled(true);
1382                 return true;
1383
1384         case LFUN_MATH_MUTATE: {
1385                 HullType ht = hullType(cmd.argument());
1386                 status.setOnOff(type_ == ht);
1387                 status.setEnabled(true);
1388                 return true;
1389         }
1390
1391         case LFUN_MATH_NUMBER_TOGGLE:
1392                 // FIXME: what is the right test, this or the one of
1393                 // LABEL_INSERT?
1394                 status.setEnabled(display());
1395                 status.setOnOff(numberedType());
1396                 return true;
1397
1398         case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1399                 // FIXME: what is the right test, this or the one of
1400                 // LABEL_INSERT?
1401                 bool const enable = (type_ == hullMultline)
1402                         ? (nrows() - 1 == cur.row())
1403                         : display() != Inline && nrows() > 1;
1404                 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1405                 status.setEnabled(enable);
1406                 status.setOnOff(enable && numbered(r));
1407                 return true;
1408         }
1409
1410         case LFUN_LABEL_INSERT:
1411                 status.setEnabled(type_ != hullSimple);
1412                 return true;
1413
1414         case LFUN_LABEL_COPY_AS_REF: {
1415                 bool enabled = false;
1416                 row_type row;
1417                 if (cmd.argument().empty() && &cur.inset() == this) {
1418                         // if there is no argument and we're inside math, we retrieve
1419                         // the row number from the cursor position.
1420                         row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1421                         enabled = numberedType() && label_[row] && !nonum_[row];
1422                 } else {
1423                         // if there is an argument, find the corresponding label, else
1424                         // check whether there is at least one label.
1425                         for (row_type row = 0; row != nrows(); ++row) {
1426                                 if (!nonum_[row] && label_[row] && 
1427                                         (cmd.argument().empty() || label(row) == cmd.argument())) {
1428                                                 enabled = true;
1429                                                 break;
1430                                 }
1431                         }
1432                 }
1433                 status.setEnabled(enabled);
1434                 return true;
1435         }
1436
1437         case LFUN_INSET_INSERT:
1438                 if (cmd.getArg(0) == "label") {
1439                         status.setEnabled(type_ != hullSimple);
1440                         return true;
1441                 }
1442                 return InsetMathGrid::getStatus(cur, cmd, status);
1443
1444         case LFUN_TABULAR_FEATURE: {
1445                 istringstream is(to_utf8(cmd.argument()));
1446                 string s;
1447                 is >> s;
1448                 if (!rowChangeOK()
1449                     && (s == "append-row"
1450                         || s == "delete-row"
1451                         || s == "copy-row")) {
1452                         status.message(bformat(
1453                                 from_utf8(N_("Can't change number of rows in '%1$s'")),
1454                                 hullName(type_)));
1455                         status.setEnabled(false);
1456                         return true;
1457                 }
1458                 if (!colChangeOK()
1459                     && (s == "append-column"
1460                         || s == "delete-column"
1461                         || s == "copy-column")) {
1462                         status.message(bformat(
1463                                 from_utf8(N_("Can't change number of columns in '%1$s'")),
1464                                 hullName(type_)));
1465                         status.setEnabled(false);
1466                         return true;
1467                 }
1468                 if ((type_ == hullSimple
1469                   || type_ == hullEquation
1470                   || type_ == hullNone) &&
1471                     (s == "add-hline-above" || s == "add-hline-below")) {
1472                         status.message(bformat(
1473                                 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1474                                 hullName(type_)));
1475                         status.setEnabled(false);
1476                         return true;
1477                 }
1478                 if (s == "add-vline-left" || s == "add-vline-right") {
1479                         status.message(bformat(
1480                                 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1481                                 hullName(type_)));
1482                         status.setEnabled(false);
1483                         return true;
1484                 }
1485                 if (s == "valign-top" || s == "valign-middle"
1486                  || s == "valign-bottom" || s == "align-left"
1487                  || s == "align-center" || s == "align-right") {
1488                         status.setEnabled(false);
1489                         return true;
1490                 }
1491                 return InsetMathGrid::getStatus(cur, cmd, status);
1492         }
1493
1494         default:
1495                 return InsetMathGrid::getStatus(cur, cmd, status);
1496         }
1497
1498         // This cannot really happen, but inserted to shut-up gcc
1499         return InsetMathGrid::getStatus(cur, cmd, status);
1500 }
1501
1502
1503 /////////////////////////////////////////////////////////////////////
1504
1505
1506
1507 // simply scrap this function if you want
1508 void InsetMathHull::mutateToText()
1509 {
1510 #if 0
1511         // translate to latex
1512         ostringstream os;
1513         latex(os, false, false);
1514         string str = os.str();
1515
1516         // insert this text
1517         Text * lt = view_->cursor().innerText();
1518         string::const_iterator cit = str.begin();
1519         string::const_iterator end = str.end();
1520         for (; cit != end; ++cit)
1521                 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1522
1523         // remove ourselves
1524         //dispatch(LFUN_ESCAPE);
1525 #endif
1526 }
1527
1528
1529 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1530         docstring const & font)
1531 {
1532         // this whole function is a hack and won't work for incremental font
1533         // changes...
1534         cur.recordUndo();
1535         if (cur.inset().asInsetMath()->name() == font)
1536                 cur.handleFont(to_utf8(font));
1537         else {
1538                 cur.handleNest(createInsetMath(font, cur.buffer()));
1539                 cur.insert(arg);
1540         }
1541 }
1542
1543
1544 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1545 {
1546         cur.recordUndo();
1547         Font font;
1548         bool b;
1549         font.fromString(to_utf8(arg), b);
1550         if (font.fontInfo().color() != Color_inherit) {
1551                 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1552                 cur.handleNest(at, 0);
1553         }
1554 }
1555
1556
1557 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1558 {
1559         cur.push(*this);
1560         bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1561                 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1562         enter_front ? idxFirst(cur) : idxLast(cur);
1563         // The inset formula dimension is not necessarily the same as the
1564         // one of the instant preview image, so we have to indicate to the
1565         // BufferView that a metrics update is needed.
1566         cur.updateFlags(Update::Force);
1567 }
1568
1569
1570 void InsetMathHull::revealCodes(Cursor & cur) const
1571 {
1572         if (!cur.inMathed())
1573                 return;
1574         odocstringstream os;
1575         cur.info(os);
1576         cur.message(os.str());
1577 /*
1578         // write something to the minibuffer
1579         // translate to latex
1580         cur.markInsert(bv);
1581         ostringstream os;
1582         write(os);
1583         string str = os.str();
1584         cur.markErase(bv);
1585         string::size_type pos = 0;
1586         string res;
1587         for (string::iterator it = str.begin(); it != str.end(); ++it) {
1588                 if (*it == '\n')
1589                         res += ' ';
1590                 else if (*it == '\0') {
1591                         res += "  -X-  ";
1592                         pos = it - str.begin();
1593                 }
1594                 else
1595                         res += *it;
1596         }
1597         if (pos > 30)
1598                 res = res.substr(pos - 30);
1599         if (res.size() > 60)
1600                 res = res.substr(0, 60);
1601         cur.message(res);
1602 */
1603 }
1604
1605
1606 /////////////////////////////////////////////////////////////////////
1607
1608
1609 #if 0
1610 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1611                                      bool, bool)
1612 {
1613         // FIXME: completely broken
1614         static InsetMathHull * lastformula = 0;
1615         static CursorBase current = DocIterator(ibegin(nucleus()));
1616         static MathData ar;
1617         static string laststr;
1618
1619         if (lastformula != this || laststr != str) {
1620                 //lyxerr << "reset lastformula to " << this << endl;
1621                 lastformula = this;
1622                 laststr = str;
1623                 current = ibegin(nucleus());
1624                 ar.clear();
1625                 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1626         } else {
1627                 increment(current);
1628         }
1629         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1630
1631         for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1632                 CursorSlice & top = it.back();
1633                 MathData const & a = top.asInsetMath()->cell(top.idx_);
1634                 if (a.matchpart(ar, top.pos_)) {
1635                         bv->cursor().setSelection(it, ar.size());
1636                         current = it;
1637                         top.pos_ += ar.size();
1638                         bv->update();
1639                         return true;
1640                 }
1641         }
1642
1643         //lyxerr << "not found!" << endl;
1644         lastformula = 0;
1645         return false;
1646 }
1647 #endif
1648
1649
1650 void InsetMathHull::write(ostream & os) const
1651 {
1652         odocstringstream oss;
1653         WriteStream wi(oss, false, false, WriteStream::wsDefault);
1654         oss << "Formula ";
1655         write(wi);
1656         os << to_utf8(oss.str());
1657 }
1658
1659
1660 void InsetMathHull::read(Lexer & lex)
1661 {
1662         MathAtom at;
1663         mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1664         operator=(*at->asHullInset());
1665 }
1666
1667
1668 bool InsetMathHull::readQuiet(Lexer & lex)
1669 {
1670         MathAtom at;
1671         bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1672         if (success)
1673                 operator=(*at->asHullInset());
1674         return success;
1675 }
1676
1677
1678 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1679 {
1680         if (0 && display()) {
1681                 Dimension dim;
1682                 TextMetricsInfo mi;
1683                 metricsT(mi, dim);
1684                 TextPainter tpain(dim.width(), dim.height());
1685                 drawT(tpain, 0, dim.ascent());
1686                 tpain.show(os, 3);
1687                 // reset metrics cache to "real" values
1688                 //metrics();
1689                 return tpain.textheight();
1690         } else {
1691                 odocstringstream oss;
1692                 Encoding const * const enc = encodings.fromLyXName("utf8");
1693                 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1694                 // Fix Bug #6139
1695                 if (type_ == hullRegexp)
1696                         write(wi);
1697                 else
1698                         wi << cell(0);
1699                 docstring const str = oss.str();
1700                 os << str;
1701                 return str.size();
1702         }
1703 }
1704
1705
1706 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1707 {
1708         MathStream ms(os);
1709         int res = 0;
1710         docstring name;
1711         if (getType() == hullSimple)
1712                 name = from_ascii("inlineequation");
1713         else
1714                 name = from_ascii("informalequation");
1715
1716         docstring bname = name;
1717         if (!label(0).empty())
1718                 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1719
1720         ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1721
1722         odocstringstream ls;
1723         if (runparams.flavor == OutputParams::XML) {
1724                 ms << MTag("alt role='tex' ");
1725                 // Workaround for db2latex: db2latex always includes equations with
1726                 // \ensuremath{} or \begin{display}\end{display}
1727                 // so we strip LyX' math environment
1728                 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1729                 InsetMathGrid::write(wi);
1730                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
1731                 ms << ETag("alt");
1732                 ms << MTag("math");
1733                 ms << ETag("alt");
1734                 ms << MTag("math");
1735                 InsetMathGrid::mathmlize(ms);
1736                 ms << ETag("math");
1737         } else {
1738                 ms << MTag("alt role='tex'");
1739                 res = latex(ls, runparams);
1740                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
1741                 ms << ETag("alt");
1742         }
1743
1744         ms << from_ascii("<graphic fileref=\"eqn/");
1745         if (!label(0).empty())
1746                 ms << sgml::cleanID(buffer(), runparams, label(0));
1747         else
1748                 ms << sgml::uniqueID(from_ascii("anon"));
1749
1750         if (runparams.flavor == OutputParams::XML)
1751                 ms << from_ascii("\"/>");
1752         else
1753                 ms << from_ascii("\">");
1754
1755         ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1756
1757         return ms.line() + res;
1758 }
1759
1760
1761 docstring InsetMathHull::xhtml(odocstream & os, OutputParams const &) const
1762 {
1763         if (getType() == hullSimple)
1764                 os << "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">";
1765         else 
1766                 os << "<math display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\">";
1767         MathStream ms(os);
1768         InsetMathGrid::mathmlize(ms);
1769         os << "</math>";
1770         return docstring();
1771 }
1772
1773
1774 void InsetMathHull::tocString(odocstream & os) const
1775 {
1776         plaintext(os, OutputParams(0));
1777 }
1778
1779
1780 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1781 {
1782         return from_ascii("context-math");
1783 }
1784
1785
1786 } // namespace lyx