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