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