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