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