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