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