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