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