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