]> git.lyx.org Git - features.git/blob - src/mathed/InsetMathHull.cpp
Fix bug #3325: Labels with special characters in equations do not work
[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{" +
1073                             escape(label_[row]->getParam("name")) + '}';
1074                 if (nonum_[row] && (type_ != hullMultline))
1075                         res += "\\nonumber ";
1076         }
1077         return res + InsetMathGrid::eolString(row, fragile);
1078 }
1079
1080
1081 void InsetMathHull::write(WriteStream & os) const
1082 {
1083         ModeSpecifier specifier(os, MATH_MODE);
1084         header_write(os);
1085         InsetMathGrid::write(os);
1086         footer_write(os);
1087 }
1088
1089
1090 void InsetMathHull::normalize(NormalStream & os) const
1091 {
1092         os << "[formula " << hullName(type_) << ' ';
1093         InsetMathGrid::normalize(os);
1094         os << "] ";
1095 }
1096
1097
1098 void InsetMathHull::mathmlize(MathStream & os) const
1099 {
1100         InsetMathGrid::mathmlize(os);
1101 }
1102
1103
1104 void InsetMathHull::infoize(odocstream & os) const
1105 {
1106         os << "Type: " << hullName(type_);
1107 }
1108
1109
1110 void InsetMathHull::check() const
1111 {
1112         LASSERT(nonum_.size() == nrows(), /**/);
1113         LASSERT(label_.size() == nrows(), /**/);
1114 }
1115
1116
1117 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1118 {
1119         docstring dlang;
1120         docstring extra;
1121         idocstringstream iss(func.argument());
1122         iss >> dlang >> extra;
1123         if (extra.empty())
1124                 extra = from_ascii("noextra");
1125         string const lang = to_ascii(dlang);
1126
1127         // FIXME: temporarily disabled
1128         //if (cur.selection()) {
1129         //      MathData ar;
1130         //      selGet(cur.ar);
1131         //      lyxerr << "use selection: " << ar << endl;
1132         //      insert(pipeThroughExtern(lang, extra, ar));
1133         //      return;
1134         //}
1135
1136         MathData eq;
1137         eq.push_back(MathAtom(new InsetMathChar('=')));
1138
1139         // go to first item in line
1140         cur.idx() -= cur.idx() % ncols();
1141         cur.pos() = 0;
1142
1143         if (getType() == hullSimple) {
1144                 size_type pos = cur.cell().find_last(eq);
1145                 MathData ar;
1146                 if (cur.inMathed() && cur.selection()) {
1147                         asArray(grabAndEraseSelection(cur), ar);
1148                 } else if (pos == cur.cell().size()) {
1149                         ar = cur.cell();
1150                         lyxerr << "use whole cell: " << ar << endl;
1151                 } else {
1152                         ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1153                         lyxerr << "use partial cell form pos: " << pos << endl;
1154                 }
1155                 cur.cell().append(eq);
1156                 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1157                 cur.pos() = cur.lastpos();
1158                 return;
1159         }
1160
1161         if (getType() == hullEquation) {
1162                 lyxerr << "use equation inset" << endl;
1163                 mutate(hullEqnArray);
1164                 MathData & ar = cur.cell();
1165                 lyxerr << "use cell: " << ar << endl;
1166                 ++cur.idx();
1167                 cur.cell() = eq;
1168                 ++cur.idx();
1169                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1170                 // move to end of line
1171                 cur.pos() = cur.lastpos();
1172                 return;
1173         }
1174
1175         {
1176                 lyxerr << "use eqnarray" << endl;
1177                 cur.idx() += 2 - cur.idx() % ncols();
1178                 cur.pos() = 0;
1179                 MathData ar = cur.cell();
1180                 lyxerr << "use cell: " << ar << endl;
1181                 // FIXME: temporarily disabled
1182                 addRow(cur.row());
1183                 ++cur.idx();
1184                 ++cur.idx();
1185                 cur.cell() = eq;
1186                 ++cur.idx();
1187                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1188                 cur.pos() = cur.lastpos();
1189         }
1190 }
1191
1192
1193 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1194 {
1195         //lyxerr << "action: " << cmd.action << endl;
1196         switch (cmd.action) {
1197
1198         case LFUN_FINISHED_BACKWARD:
1199         case LFUN_FINISHED_FORWARD:
1200         case LFUN_FINISHED_RIGHT:
1201         case LFUN_FINISHED_LEFT:
1202                 //lyxerr << "action: " << cmd.action << endl;
1203                 InsetMathGrid::doDispatch(cur, cmd);
1204                 cur.undispatched();
1205                 break;
1206
1207         case LFUN_BREAK_PARAGRAPH:
1208                 // just swallow this
1209                 break;
1210
1211         case LFUN_NEWLINE_INSERT:
1212                 // some magic for the common case
1213                 if (type_ == hullSimple || type_ == hullEquation) {
1214                         cur.recordUndoInset();
1215                         bool const align =
1216                                 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1217                         mutate(align ? hullAlign : hullEqnArray);
1218                         cur.idx() = nrows() * ncols() - 1;
1219                         cur.pos() = cur.lastpos();
1220                 }
1221                 InsetMathGrid::doDispatch(cur, cmd);
1222                 break;
1223
1224         case LFUN_MATH_NUMBER_TOGGLE: {
1225                 //lyxerr << "toggling all numbers" << endl;
1226                 cur.recordUndoInset();
1227                 bool old = numberedType();
1228                 if (type_ == hullMultline)
1229                         numbered(nrows() - 1, !old);
1230                 else
1231                         for (row_type row = 0; row < nrows(); ++row)
1232                                 numbered(row, !old);
1233
1234                 cur.message(old ? _("No number") : _("Number"));
1235                 break;
1236         }
1237
1238         case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1239                 cur.recordUndoInset();
1240                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1241                 bool old = numbered(r);
1242                 cur.message(old ? _("No number") : _("Number"));
1243                 numbered(r, !old);
1244                 break;
1245         }
1246
1247         case LFUN_LABEL_INSERT: {
1248                 cur.recordUndoInset();
1249                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1250                 docstring old_label = label(r);
1251                 docstring const default_label = from_ascii(
1252                         (lyxrc.label_init_length >= 0) ? "eq:" : "");
1253                 if (old_label.empty())
1254                         old_label = default_label;
1255
1256                 InsetCommandParams p(LABEL_CODE);
1257                 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1258                 string const data = InsetCommand::params2string("label", p);
1259
1260                 if (cmd.argument().empty())
1261                         cur.bv().showDialog("label", data);
1262                 else {
1263                         FuncRequest fr(LFUN_INSET_INSERT, data);
1264                         dispatch(cur, fr);
1265                 }
1266                 break;
1267         }
1268
1269         case LFUN_LABEL_COPY_AS_REF: {
1270                 row_type row;
1271                 if (cmd.argument().empty() && &cur.inset() == this)
1272                         // if there is no argument and we're inside math, we retrieve
1273                         // the row number from the cursor position.
1274                         row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1275                 else {
1276                         // if there is an argument, find the corresponding label, else
1277                         // check whether there is at least one label.
1278                         for (row = 0; row != nrows(); ++row)
1279                                 if (!nonum_[row] && label_[row]
1280                                           && (cmd.argument().empty() || label(row) == cmd.argument()))
1281                                         break;
1282                 }
1283
1284                 if (row == nrows())
1285                         break;
1286
1287                 InsetCommandParams p(REF_CODE, "ref");
1288                 p["reference"] = label(row);
1289                 cap::clearSelection();
1290                 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1291                 break;
1292         }
1293
1294         case LFUN_WORD_DELETE_FORWARD:
1295         case LFUN_CHAR_DELETE_FORWARD:
1296                 if (col(cur.idx()) + 1 == ncols()
1297                     && cur.pos() == cur.lastpos()
1298                     && !cur.selection()) {
1299                         if (!label(row(cur.idx())).empty()) {
1300                                 cur.recordUndoInset();
1301                                 label(row(cur.idx()), docstring());
1302                         } else if (numbered(row(cur.idx()))) {
1303                                 cur.recordUndoInset();
1304                                 numbered(row(cur.idx()), false);
1305                         } else {
1306                                 InsetMathGrid::doDispatch(cur, cmd);
1307                                 return;
1308                         }
1309                 } else {
1310                         InsetMathGrid::doDispatch(cur, cmd);
1311                         return;
1312                 }
1313                 break;
1314
1315         case LFUN_INSET_INSERT: {
1316                 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1317                 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1318                 string const name = cmd.getArg(0);
1319                 if (name == "label") {
1320                         InsetCommandParams p(LABEL_CODE);
1321                         InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1322                         docstring str = p["name"];
1323                         cur.recordUndoInset();
1324                         row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1325                         str = trim(str);
1326                         if (!str.empty())
1327                                 numbered(r, true);
1328                         docstring old = label(r);
1329                         if (str != old) {
1330                                 if (label_[r])
1331                                         // The label will take care of the reference update.
1332                                         label(r, str);
1333                                 else {
1334                                         label(r, str);
1335                                         // Newly created inset so initialize it.
1336                                         label_[r]->initView();
1337                                 }
1338                         }
1339                         break;
1340                 }
1341                 InsetMathGrid::doDispatch(cur, cmd);
1342                 return;
1343         }
1344
1345         case LFUN_MATH_EXTERN:
1346                 cur.recordUndoInset();
1347                 doExtern(cur, cmd);
1348                 break;
1349
1350         case LFUN_MATH_MUTATE: {
1351                 cur.recordUndoInset();
1352                 row_type row = cur.row();
1353                 col_type col = cur.col();
1354                 mutate(hullType(cmd.argument()));
1355                 cur.idx() = row * ncols() + col;
1356                 if (cur.idx() > cur.lastidx()) {
1357                         cur.idx() = cur.lastidx();
1358                         cur.pos() = cur.lastpos();
1359                 }
1360                 if (cur.pos() > cur.lastpos())
1361                         cur.pos() = cur.lastpos();
1362
1363                 // FIXME: find some more clever handling of the selection,
1364                 // i.e. preserve it.
1365                 cur.clearSelection();
1366                 //cur.dispatched(FINISHED);
1367                 break;
1368         }
1369
1370         case LFUN_MATH_DISPLAY: {
1371                 cur.recordUndoInset();
1372                 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1373                 cur.idx() = 0;
1374                 cur.pos() = cur.lastpos();
1375                 //cur.dispatched(FINISHED);
1376                 break;
1377         }
1378
1379         default:
1380                 InsetMathGrid::doDispatch(cur, cmd);
1381                 break;
1382         }
1383 }
1384
1385
1386 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1387                 FuncStatus & status) const
1388 {
1389         switch (cmd.action) {
1390         case LFUN_FINISHED_BACKWARD:
1391         case LFUN_FINISHED_FORWARD:
1392         case LFUN_FINISHED_RIGHT:
1393         case LFUN_FINISHED_LEFT:
1394         case LFUN_UP:
1395         case LFUN_DOWN:
1396         case LFUN_NEWLINE_INSERT:
1397         case LFUN_MATH_EXTERN:
1398         case LFUN_MATH_DISPLAY:
1399                 // we handle these
1400                 status.setEnabled(true);
1401                 return true;
1402
1403         case LFUN_MATH_MUTATE: {
1404                 HullType ht = hullType(cmd.argument());
1405                 status.setOnOff(type_ == ht);
1406                 status.setEnabled(true);
1407                 return true;
1408         }
1409
1410         case LFUN_MATH_NUMBER_TOGGLE:
1411                 // FIXME: what is the right test, this or the one of
1412                 // LABEL_INSERT?
1413                 status.setEnabled(display());
1414                 status.setOnOff(numberedType());
1415                 return true;
1416
1417         case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1418                 // FIXME: what is the right test, this or the one of
1419                 // LABEL_INSERT?
1420                 bool const enable = (type_ == hullMultline)
1421                         ? (nrows() - 1 == cur.row())
1422                         : display() != Inline && nrows() > 1;
1423                 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1424                 status.setEnabled(enable);
1425                 status.setOnOff(enable && numbered(r));
1426                 return true;
1427         }
1428
1429         case LFUN_LABEL_INSERT:
1430                 status.setEnabled(type_ != hullSimple);
1431                 return true;
1432
1433         case LFUN_LABEL_COPY_AS_REF: {
1434                 bool enabled = false;
1435                 row_type row;
1436                 if (cmd.argument().empty() && &cur.inset() == this) {
1437                         // if there is no argument and we're inside math, we retrieve
1438                         // the row number from the cursor position.
1439                         row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1440                         enabled = numberedType() && label_[row] && !nonum_[row];
1441                 } else {
1442                         // if there is an argument, find the corresponding label, else
1443                         // check whether there is at least one label.
1444                         for (row_type row = 0; row != nrows(); ++row) {
1445                                 if (!nonum_[row] && label_[row] && 
1446                                         (cmd.argument().empty() || label(row) == cmd.argument())) {
1447                                                 enabled = true;
1448                                                 break;
1449                                 }
1450                         }
1451                 }
1452                 status.setEnabled(enabled);
1453                 return true;
1454         }
1455
1456         case LFUN_INSET_INSERT:
1457                 if (cmd.getArg(0) == "label") {
1458                         status.setEnabled(type_ != hullSimple);
1459                         return true;
1460                 }
1461                 return InsetMathGrid::getStatus(cur, cmd, status);
1462
1463         case LFUN_TABULAR_FEATURE: {
1464                 istringstream is(to_utf8(cmd.argument()));
1465                 string s;
1466                 is >> s;
1467                 if (!rowChangeOK()
1468                     && (s == "append-row"
1469                         || s == "delete-row"
1470                         || s == "copy-row")) {
1471                         status.message(bformat(
1472                                 from_utf8(N_("Can't change number of rows in '%1$s'")),
1473                                 hullName(type_)));
1474                         status.setEnabled(false);
1475                         return true;
1476                 }
1477                 if (!colChangeOK()
1478                     && (s == "append-column"
1479                         || s == "delete-column"
1480                         || s == "copy-column")) {
1481                         status.message(bformat(
1482                                 from_utf8(N_("Can't change number of columns in '%1$s'")),
1483                                 hullName(type_)));
1484                         status.setEnabled(false);
1485                         return true;
1486                 }
1487                 if ((type_ == hullSimple
1488                   || type_ == hullEquation
1489                   || type_ == hullNone) &&
1490                     (s == "add-hline-above" || s == "add-hline-below")) {
1491                         status.message(bformat(
1492                                 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1493                                 hullName(type_)));
1494                         status.setEnabled(false);
1495                         return true;
1496                 }
1497                 if (s == "add-vline-left" || s == "add-vline-right") {
1498                         status.message(bformat(
1499                                 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1500                                 hullName(type_)));
1501                         status.setEnabled(false);
1502                         return true;
1503                 }
1504                 if (s == "valign-top" || s == "valign-middle"
1505                  || s == "valign-bottom" || s == "align-left"
1506                  || s == "align-center" || s == "align-right") {
1507                         status.setEnabled(false);
1508                         return true;
1509                 }
1510                 return InsetMathGrid::getStatus(cur, cmd, status);
1511         }
1512
1513         default:
1514                 return InsetMathGrid::getStatus(cur, cmd, status);
1515         }
1516
1517         // This cannot really happen, but inserted to shut-up gcc
1518         return InsetMathGrid::getStatus(cur, cmd, status);
1519 }
1520
1521
1522 /////////////////////////////////////////////////////////////////////
1523
1524
1525
1526 // simply scrap this function if you want
1527 void InsetMathHull::mutateToText()
1528 {
1529 #if 0
1530         // translate to latex
1531         ostringstream os;
1532         latex(os, false, false);
1533         string str = os.str();
1534
1535         // insert this text
1536         Text * lt = view_->cursor().innerText();
1537         string::const_iterator cit = str.begin();
1538         string::const_iterator end = str.end();
1539         for (; cit != end; ++cit)
1540                 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1541
1542         // remove ourselves
1543         //dispatch(LFUN_ESCAPE);
1544 #endif
1545 }
1546
1547
1548 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1549         docstring const & font)
1550 {
1551         // this whole function is a hack and won't work for incremental font
1552         // changes...
1553         cur.recordUndo();
1554         if (cur.inset().asInsetMath()->name() == font)
1555                 cur.handleFont(to_utf8(font));
1556         else {
1557                 cur.handleNest(createInsetMath(font, cur.buffer()));
1558                 cur.insert(arg);
1559         }
1560 }
1561
1562
1563 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1564 {
1565         cur.recordUndo();
1566         Font font;
1567         bool b;
1568         font.fromString(to_utf8(arg), b);
1569         if (font.fontInfo().color() != Color_inherit) {
1570                 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1571                 cur.handleNest(at, 0);
1572         }
1573 }
1574
1575
1576 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1577 {
1578         cur.push(*this);
1579         bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1580                 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1581         enter_front ? idxFirst(cur) : idxLast(cur);
1582         // The inset formula dimension is not necessarily the same as the
1583         // one of the instant preview image, so we have to indicate to the
1584         // BufferView that a metrics update is needed.
1585         cur.updateFlags(Update::Force);
1586 }
1587
1588
1589 void InsetMathHull::revealCodes(Cursor & cur) const
1590 {
1591         if (!cur.inMathed())
1592                 return;
1593         odocstringstream os;
1594         cur.info(os);
1595         cur.message(os.str());
1596 /*
1597         // write something to the minibuffer
1598         // translate to latex
1599         cur.markInsert(bv);
1600         ostringstream os;
1601         write(os);
1602         string str = os.str();
1603         cur.markErase(bv);
1604         string::size_type pos = 0;
1605         string res;
1606         for (string::iterator it = str.begin(); it != str.end(); ++it) {
1607                 if (*it == '\n')
1608                         res += ' ';
1609                 else if (*it == '\0') {
1610                         res += "  -X-  ";
1611                         pos = it - str.begin();
1612                 }
1613                 else
1614                         res += *it;
1615         }
1616         if (pos > 30)
1617                 res = res.substr(pos - 30);
1618         if (res.size() > 60)
1619                 res = res.substr(0, 60);
1620         cur.message(res);
1621 */
1622 }
1623
1624
1625 /////////////////////////////////////////////////////////////////////
1626
1627
1628 #if 0
1629 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1630                                      bool, bool)
1631 {
1632         // FIXME: completely broken
1633         static InsetMathHull * lastformula = 0;
1634         static CursorBase current = DocIterator(ibegin(nucleus()));
1635         static MathData ar;
1636         static string laststr;
1637
1638         if (lastformula != this || laststr != str) {
1639                 //lyxerr << "reset lastformula to " << this << endl;
1640                 lastformula = this;
1641                 laststr = str;
1642                 current = ibegin(nucleus());
1643                 ar.clear();
1644                 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1645         } else {
1646                 increment(current);
1647         }
1648         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1649
1650         for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1651                 CursorSlice & top = it.back();
1652                 MathData const & a = top.asInsetMath()->cell(top.idx_);
1653                 if (a.matchpart(ar, top.pos_)) {
1654                         bv->cursor().setSelection(it, ar.size());
1655                         current = it;
1656                         top.pos_ += ar.size();
1657                         bv->update();
1658                         return true;
1659                 }
1660         }
1661
1662         //lyxerr << "not found!" << endl;
1663         lastformula = 0;
1664         return false;
1665 }
1666 #endif
1667
1668
1669 void InsetMathHull::write(ostream & os) const
1670 {
1671         odocstringstream oss;
1672         WriteStream wi(oss, false, false, WriteStream::wsDefault);
1673         oss << "Formula ";
1674         write(wi);
1675         os << to_utf8(oss.str());
1676 }
1677
1678
1679 void InsetMathHull::read(Lexer & lex)
1680 {
1681         MathAtom at;
1682         mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1683         operator=(*at->asHullInset());
1684 }
1685
1686
1687 bool InsetMathHull::readQuiet(Lexer & lex)
1688 {
1689         MathAtom at;
1690         bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1691         if (success)
1692                 operator=(*at->asHullInset());
1693         return success;
1694 }
1695
1696
1697 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1698 {
1699         if (0 && display()) {
1700                 Dimension dim;
1701                 TextMetricsInfo mi;
1702                 metricsT(mi, dim);
1703                 TextPainter tpain(dim.width(), dim.height());
1704                 drawT(tpain, 0, dim.ascent());
1705                 tpain.show(os, 3);
1706                 // reset metrics cache to "real" values
1707                 //metrics();
1708                 return tpain.textheight();
1709         } else {
1710                 odocstringstream oss;
1711                 Encoding const * const enc = encodings.fromLyXName("utf8");
1712                 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1713                 // Fix Bug #6139
1714                 if (type_ == hullRegexp)
1715                         write(wi);
1716                 else
1717                         wi << cell(0);
1718                 docstring const str = oss.str();
1719                 os << str;
1720                 return str.size();
1721         }
1722 }
1723
1724
1725 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1726 {
1727         MathStream ms(os);
1728         int res = 0;
1729         docstring name;
1730         if (getType() == hullSimple)
1731                 name = from_ascii("inlineequation");
1732         else
1733                 name = from_ascii("informalequation");
1734
1735         docstring bname = name;
1736         if (!label(0).empty())
1737                 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1738
1739         ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1740
1741         odocstringstream ls;
1742         if (runparams.flavor == OutputParams::XML) {
1743                 ms << MTag("alt role='tex' ");
1744                 // Workaround for db2latex: db2latex always includes equations with
1745                 // \ensuremath{} or \begin{display}\end{display}
1746                 // so we strip LyX' math environment
1747                 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1748                 InsetMathGrid::write(wi);
1749                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
1750                 ms << ETag("alt");
1751                 ms << MTag("math");
1752                 ms << ETag("alt");
1753                 ms << MTag("math");
1754                 InsetMathGrid::mathmlize(ms);
1755                 ms << ETag("math");
1756         } else {
1757                 ms << MTag("alt role='tex'");
1758                 res = latex(ls, runparams);
1759                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
1760                 ms << ETag("alt");
1761         }
1762
1763         ms << from_ascii("<graphic fileref=\"eqn/");
1764         if (!label(0).empty())
1765                 ms << sgml::cleanID(buffer(), runparams, label(0));
1766         else
1767                 ms << sgml::uniqueID(from_ascii("anon"));
1768
1769         if (runparams.flavor == OutputParams::XML)
1770                 ms << from_ascii("\"/>");
1771         else
1772                 ms << from_ascii("\">");
1773
1774         ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1775
1776         return ms.line() + res;
1777 }
1778
1779
1780 docstring InsetMathHull::xhtml(XHTMLStream & xs, OutputParams const &) const
1781 {
1782         if (getType() == hullSimple)
1783                 xs << html::StartTag("math", "xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1784         else 
1785                 xs << html::StartTag("math", 
1786                         "display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\"", true);
1787         MathStream ms(xs.os());
1788         InsetMathGrid::mathmlize(ms);
1789         xs << html::EndTag("math");
1790         return docstring();
1791 }
1792
1793
1794 void InsetMathHull::tocString(odocstream & os) const
1795 {
1796         plaintext(os, OutputParams(0));
1797 }
1798
1799
1800 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1801 {
1802         return from_ascii("context-math");
1803 }
1804
1805
1806 } // namespace lyx