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