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