]> git.lyx.org Git - lyx.git/blob - src/mathed/math_hullinset.C
minimal effort implementation of:
[lyx.git] / src / mathed / math_hullinset.C
1 /**
2  * \file math_hullinset.C
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 "math_charinset.h"
14 #include "math_colorinset.h"
15 #include "math_data.h"
16 #include "math_extern.h"
17 #include "math_factory.h"
18 #include "math_hullinset.h"
19 #include "math_mathmlstream.h"
20 #include "math_streamstr.h"
21 #include "math_support.h"
22
23 #include "buffer.h"
24 #include "bufferparams.h"
25 #include "BufferView.h"
26 #include "CutAndPaste.h"
27 #include "FuncStatus.h"
28 #include "LColor.h"
29 #include "LaTeXFeatures.h"
30 #include "cursor.h"
31 #include "debug.h"
32 #include "dispatchresult.h"
33 #include "funcrequest.h"
34 #include "gettext.h"
35 #include "lyx_main.h"
36 #include "lyxrc.h"
37 #include "outputparams.h"
38 #include "sgml.h"
39 #include "textpainter.h"
40 #include "undo.h"
41
42 #include "insets/render_preview.h"
43 #include "insets/insetlabel.h"
44
45 #include "frontends/Dialogs.h"
46 #include "frontends/LyXView.h"
47
48 #include "graphics/PreviewImage.h"
49 #include "graphics/PreviewLoader.h"
50
51 #include "support/lstrings.h"
52
53 #include <boost/bind.hpp>
54
55 #include <sstream>
56
57 using lyx::docstring;
58 using lyx::cap::grabAndEraseSelection;
59 using lyx::support::bformat;
60 using lyx::support::subst;
61
62 using std::endl;
63 using std::max;
64 using std::string;
65 using std::ostream;
66 using std::auto_ptr;
67 using std::istringstream;
68 using std::ostream;
69 using std::ostringstream;
70 using std::pair;
71 using std::swap;
72 using std::vector;
73
74
75 namespace {
76
77         int getCols(string const & type)
78         {
79                 if (type == "eqnarray")
80                         return 3;
81                 if (type == "align")
82                         return 2;
83                 if (type == "flalign")
84                         return 2;
85                 if (type == "alignat")
86                         return 2;
87                 if (type == "xalignat")
88                         return 2;
89                 if (type == "xxalignat")
90                         return 2;
91                 return 1;
92         }
93
94
95         // returns position of first relation operator in the array
96         // used for "intelligent splitting"
97         size_t firstRelOp(MathArray const & ar)
98         {
99                 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
100                         if ((*it)->isRelOp())
101                                 return it - ar.begin();
102                 return ar.size();
103         }
104
105
106         char const * star(bool numbered)
107         {
108                 return numbered ? "" : "*";
109         }
110
111
112         int typecode(string const & s)
113         {
114                 if (s == "none")      return 0;
115                 if (s == "simple")    return 1;
116                 if (s == "equation")  return 2;
117                 if (s == "eqnarray")  return 3;
118                 if (s == "align")     return 4;
119                 if (s == "alignat")   return 5;
120                 if (s == "xalignat")  return 6;
121                 if (s == "xxalignat") return 7;
122                 if (s == "multline")  return 8;
123                 if (s == "gather")    return 9;
124                 if (s == "flalign")   return 10;
125                 lyxerr << "unknown hull type '" << s << "'" << endl;
126                 return -1;
127         }
128
129         bool smaller(string const & s, string const & t)
130         {
131                 return typecode(s) < typecode(t);
132         }
133
134
135 } // end anon namespace
136
137
138
139 MathHullInset::MathHullInset()
140         : MathGridInset(1, 1), type_("none"), nonum_(1), label_(1),
141           preview_(new RenderPreview(this))
142 {
143         //lyxerr << "sizeof MathInset: " << sizeof(MathInset) << endl;
144         //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
145         //lyxerr << "sizeof MathCharInset: " << sizeof(MathCharInset) << endl;
146         //lyxerr << "sizeof LyXFont: " << sizeof(LyXFont) << endl;
147         initMath();
148         setDefaults();
149 }
150
151
152 MathHullInset::MathHullInset(string const & type)
153         : MathGridInset(getCols(type), 1), type_(type), nonum_(1), label_(1),
154           preview_(new RenderPreview(this))
155 {
156         initMath();
157         setDefaults();
158 }
159
160
161 MathHullInset::MathHullInset(MathHullInset const & other)
162         : MathGridInset(other),
163           type_(other.type_), nonum_(other.nonum_), label_(other.label_),
164           preview_(new RenderPreview(this))
165 {}
166
167
168 MathHullInset::~MathHullInset()
169 {}
170
171
172 auto_ptr<InsetBase> MathHullInset::doClone() const
173 {
174         return auto_ptr<InsetBase>(new MathHullInset(*this));
175 }
176
177
178 MathHullInset & MathHullInset::operator=(MathHullInset const & other)
179 {
180         if (this == &other)
181                 return *this;
182         *static_cast<MathGridInset*>(this) = MathGridInset(other);
183         type_  = other.type_;
184         nonum_ = other.nonum_;
185         label_ = other.label_;
186         preview_.reset(new RenderPreview(*other.preview_, this));
187
188         return *this;
189 }
190
191
192 InsetBase * MathHullInset::editXY(LCursor & cur, int x, int y)
193 {
194         if (use_preview_) {
195                 edit(cur, true);
196                 return this;
197         }
198         return MathNestInset::editXY(cur, x, y);
199 }
200
201
202 MathInset::mode_type MathHullInset::currentMode() const
203 {
204         if (type_ == "none")
205                 return UNDECIDED_MODE;
206         // definitely math mode ...
207         return MATH_MODE;
208 }
209
210
211 bool MathHullInset::idxFirst(LCursor & cur) const
212 {
213         cur.idx() = 0;
214         cur.pos() = 0;
215         return true;
216 }
217
218
219 bool MathHullInset::idxLast(LCursor & cur) const
220 {
221         cur.idx() = nargs() - 1;
222         cur.pos() = cur.lastpos();
223         return true;
224 }
225
226
227 char MathHullInset::defaultColAlign(col_type col)
228 {
229         if (type_ == "eqnarray")
230                 return "rcl"[col];
231         if (typecode(type_) >= typecode("align"))
232                 return "rl"[col & 1];
233         return 'c';
234 }
235
236
237 int MathHullInset::defaultColSpace(col_type col)
238 {
239         if (type_ == "align" || type_ == "alignat")
240                 return 0;
241         if (type_ == "xalignat")
242                 return (col & 1) ? 20 : 0;
243         if (type_ == "xxalignat" || type_ == "flalign")
244                 return (col & 1) ? 40 : 0;
245         return 0;
246 }
247
248
249 char const * MathHullInset::standardFont() const
250 {
251         return type_ == "none" ? "lyxnochange" : "mathnormal";
252 }
253
254
255 bool MathHullInset::previewState(BufferView * bv) const
256 {
257         if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
258                 lyx::graphics::PreviewImage const * pimage =
259                         preview_->getPreviewImage(*bv->buffer());
260                 return pimage && pimage->image();
261         }
262         return false;
263 }
264
265
266 void MathHullInset::metrics(MetricsInfo & mi, Dimension & dim) const
267 {
268         if (previewState(mi.base.bv)) {
269                 preview_->metrics(mi, dim);
270                 // insert a one pixel gap in front of the formula
271                 dim.wid += 1;
272                 if (display())
273                         dim.des += 12;
274                 dim_ = dim;
275                 return;
276         }
277
278         FontSetChanger dummy1(mi.base, standardFont());
279         StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
280
281         // let the cells adjust themselves
282         MathGridInset::metrics(mi, dim);
283
284         if (display()) {
285                 dim.asc += 12;
286                 dim.des += 12;
287         }
288
289         if (numberedType()) {
290                 FontSetChanger dummy(mi.base, "mathbf");
291                 int l = 0;
292                 for (row_type row = 0; row < nrows(); ++row)
293                         l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
294
295                 if (l)
296                         dim.wid += 30 + l;
297         }
298
299         // make it at least as high as the current font
300         int asc = 0;
301         int des = 0;
302         math_font_max_dim(mi.base.font, asc, des);
303         dim.asc = max(dim.asc, asc);
304         dim.des = max(dim.des, des);
305
306         dim_ = dim;
307 }
308
309
310 void MathHullInset::draw(PainterInfo & pi, int x, int y) const
311 {
312         use_preview_ = previewState(pi.base.bv);
313
314         if (use_preview_) {
315                 // one pixel gap in front
316                 preview_->draw(pi, x + 1, y);
317                 setPosCache(pi, x, y);
318                 return;
319         }
320
321         FontSetChanger dummy1(pi.base, standardFont());
322         StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
323         MathGridInset::draw(pi, x + 1, y);
324
325         if (numberedType()) {
326                 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
327                 for (row_type row = 0; row < nrows(); ++row) {
328                         int const yy = y + rowinfo_[row].offset_;
329                         FontSetChanger dummy(pi.base, "mathrm");
330                         string const nl = nicelabel(row);
331                         docstring const dnl(nl.begin(), nl.end());
332                         pi.draw(xx, yy, dnl);
333                 }
334         }
335         setPosCache(pi, x, y);
336 }
337
338
339 void MathHullInset::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
340 {
341         if (display()) {
342                 MathGridInset::metricsT(mi, dim);
343         } else {
344                 ostringstream os;
345                 WriteStream wi(os, false, true);
346                 write(wi);
347                 dim.wid = os.str().size();
348                 dim.asc = 1;
349                 dim.des = 0;
350         }
351 }
352
353
354 void MathHullInset::drawT(TextPainter & pain, int x, int y) const
355 {
356         if (display()) {
357                 MathGridInset::drawT(pain, x, y);
358         } else {
359                 ostringstream os;
360                 WriteStream wi(os, false, true);
361                 write(wi);
362                 pain.draw(x, y, os.str().c_str());
363         }
364 }
365
366
367 namespace {
368
369 string const latex_string(MathHullInset const & inset)
370 {
371         ostringstream ls;
372         WriteStream wi(ls, false, false);
373         inset.write(wi);
374         return ls.str();
375 }
376
377 } // namespace anon
378
379
380 void MathHullInset::addPreview(lyx::graphics::PreviewLoader & ploader) const
381 {
382         if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
383                 string const snippet = latex_string(*this);
384                 preview_->addPreview(snippet, ploader);
385         }
386 }
387
388
389 bool MathHullInset::notifyCursorLeaves(LCursor & cur)
390 {
391         if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
392                 Buffer const & buffer = cur.buffer();
393                 string const snippet = latex_string(*this);
394                 preview_->addPreview(snippet, buffer);
395                 preview_->startLoading(buffer);
396         }
397         return false;
398 }
399
400
401 string MathHullInset::label(row_type row) const
402 {
403         BOOST_ASSERT(row < nrows());
404         return label_[row];
405 }
406
407
408 void MathHullInset::label(row_type row, string const & label)
409 {
410         //lyxerr << "setting label '" << label << "' for row " << row << endl;
411         label_[row] = label;
412 }
413
414
415 void MathHullInset::numbered(row_type row, bool num)
416 {
417         nonum_[row] = !num;
418 }
419
420
421 bool MathHullInset::numbered(row_type row) const
422 {
423         return !nonum_[row];
424 }
425
426
427 bool MathHullInset::ams() const
428 {
429         return
430                 type_ == "align" ||
431                 type_ == "flalign" ||
432                 type_ == "multline" ||
433                 type_ == "gather" ||
434                 type_ == "alignat" ||
435                 type_ == "xalignat" ||
436                 type_ == "xxalignat";
437 }
438
439
440 bool MathHullInset::display() const
441 {
442         return type_ != "simple" && type_ != "none";
443 }
444
445
446 void MathHullInset::getLabelList(Buffer const &, vector<string> & labels) const
447 {
448         for (row_type row = 0; row < nrows(); ++row)
449                 if (!label_[row].empty() && nonum_[row] != 1)
450                         labels.push_back(label_[row]);
451 }
452
453
454 bool MathHullInset::numberedType() const
455 {
456         if (type_ == "none")
457                 return false;
458         if (type_ == "simple")
459                 return false;
460         if (type_ == "xxalignat")
461                 return false;
462         for (row_type row = 0; row < nrows(); ++row)
463                 if (!nonum_[row])
464                         return true;
465         return false;
466 }
467
468
469 void MathHullInset::validate(LaTeXFeatures & features) const
470 {
471         if (ams())
472                 features.require("amsmath");
473
474
475         // Validation is necessary only if not using AMS math.
476         // To be safe, we will always run mathedvalidate.
477         //if (features.amsstyle)
478         //  return;
479
480         features.require("boldsymbol");
481         //features.binom      = true;
482
483         MathGridInset::validate(features);
484 }
485
486
487 void MathHullInset::header_write(WriteStream & os) const
488 {
489         bool n = numberedType();
490
491         if (type_ == "none")
492                 ;
493
494         else if (type_ == "simple") {
495                 os << '$';
496                 if (cell(0).empty())
497                         os << ' ';
498         }
499
500         else if (type_ == "equation") {
501                 if (n)
502                         os << "\\begin{equation" << star(n) << "}\n";
503                 else
504                         os << "\\[\n";
505         }
506
507         else if (type_ == "eqnarray" || type_ == "align" || type_ == "flalign"
508                  || type_ == "gather" || type_ == "multline")
509                         os << "\\begin{" << type_ << star(n) << "}\n";
510
511         else if (type_ == "alignat" || type_ == "xalignat")
512                 os << "\\begin{" << type_ << star(n) << '}'
513                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
514
515         else if (type_ == "xxalignat")
516                 os << "\\begin{" << type_ << '}'
517                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
518
519         else
520                 os << "\\begin{unknown" << star(n) << '}';
521 }
522
523
524 void MathHullInset::footer_write(WriteStream & os) const
525 {
526         bool n = numberedType();
527
528         if (type_ == "none")
529                 os << "\n";
530
531         else if (type_ == "simple")
532                 os << '$';
533
534         else if (type_ == "equation")
535                 if (n)
536                         os << "\\end{equation" << star(n) << "}\n";
537                 else
538                         os << "\\]\n";
539
540         else if (type_ == "eqnarray" || type_ == "align" || type_ == "flalign"
541                  || type_ == "alignat" || type_ == "xalignat"
542                  || type_ == "gather" || type_ == "multline")
543                 os << "\\end{" << type_ << star(n) << "}\n";
544
545         else if (type_ == "xxalignat")
546                 os << "\\end{" << type_ << "}\n";
547
548         else
549                 os << "\\end{unknown" << star(n) << '}';
550 }
551
552
553 bool MathHullInset::rowChangeOK() const
554 {
555         return
556                 type_ == "eqnarray" || type_ == "align" ||
557                 type_ == "flalign" || type_ == "alignat" ||
558                 type_ == "xalignat" || type_ == "xxalignat" ||
559                 type_ == "gather" || type_ == "multline";
560 }
561
562
563 bool MathHullInset::colChangeOK() const
564 {
565         return
566                 type_ == "align" || type_ == "flalign" ||type_ == "alignat" ||
567                 type_ == "xalignat" || type_ == "xxalignat";
568 }
569
570
571 void MathHullInset::addRow(row_type row)
572 {
573         if (!rowChangeOK())
574                 return;
575         nonum_.insert(nonum_.begin() + row + 1, !numberedType());
576         label_.insert(label_.begin() + row + 1, string());
577         MathGridInset::addRow(row);
578 }
579
580
581 void MathHullInset::swapRow(row_type row)
582 {
583         if (nrows() <= 1)
584                 return;
585         if (row + 1 == nrows())
586                 --row;
587         swap(nonum_[row], nonum_[row + 1]);
588         swap(label_[row], label_[row + 1]);
589         MathGridInset::swapRow(row);
590 }
591
592
593 void MathHullInset::delRow(row_type row)
594 {
595         if (nrows() <= 1 || !rowChangeOK())
596                 return;
597         MathGridInset::delRow(row);
598         // The last dummy row has no number info nor a label.
599         // Test nrows() + 1 because we have already erased the row.
600         if (row == nrows() + 1)
601                 row--;
602         nonum_.erase(nonum_.begin() + row);
603         label_.erase(label_.begin() + row);
604 }
605
606
607 void MathHullInset::addCol(col_type col)
608 {
609         if (!colChangeOK())
610                 return;
611         MathGridInset::addCol(col);
612 }
613
614
615 void MathHullInset::delCol(col_type col)
616 {
617         if (ncols() <= 1 || !colChangeOK())
618                 return;
619         MathGridInset::delCol(col);
620 }
621
622
623 string MathHullInset::nicelabel(row_type row) const
624 {
625         if (nonum_[row])
626                 return string();
627         if (label_[row].empty())
628                 return string("(#)");
629         return '(' + label_[row] + ')';
630 }
631
632
633 void MathHullInset::glueall()
634 {
635         MathArray ar;
636         for (idx_type i = 0; i < nargs(); ++i)
637                 ar.append(cell(i));
638         *this = MathHullInset("simple");
639         cell(0) = ar;
640         setDefaults();
641 }
642
643
644 void MathHullInset::splitTo2Cols()
645 {
646         BOOST_ASSERT(ncols() == 1);
647         MathGridInset::addCol(1);
648         for (row_type row = 0; row < nrows(); ++row) {
649                 idx_type const i = 2 * row;
650                 pos_type pos = firstRelOp(cell(i));
651                 cell(i + 1) = MathArray(cell(i).begin() + pos, cell(i).end());
652                 cell(i).erase(pos, cell(i).size());
653         }
654 }
655
656
657 void MathHullInset::splitTo3Cols()
658 {
659         BOOST_ASSERT(ncols() < 3);
660         if (ncols() < 2)
661                 splitTo2Cols();
662         MathGridInset::addCol(1);
663         for (row_type row = 0; row < nrows(); ++row) {
664                 idx_type const i = 3 * row + 1;
665                 if (cell(i).size()) {
666                         cell(i + 1) = MathArray(cell(i).begin() + 1, cell(i).end());
667                         cell(i).erase(1, cell(i).size());
668                 }
669         }
670 }
671
672
673 void MathHullInset::changeCols(col_type cols)
674 {
675         if (ncols() == cols)
676                 return;
677         else if (ncols() < cols) {
678                 // split columns
679                 if (cols < 3)
680                         splitTo2Cols();
681                 else {
682                         splitTo3Cols();
683                         while (ncols() < cols)
684                                 MathGridInset::addCol(ncols() - 1);
685                 }
686                 return;
687         }
688
689         // combine columns
690         for (row_type row = 0; row < nrows(); ++row) {
691                 idx_type const i = row * ncols();
692                 for (col_type col = cols; col < ncols(); ++col) {
693                         cell(i + cols - 1).append(cell(i + col));
694                 }
695         }
696         // delete columns
697         while (ncols() > cols) {
698                 MathGridInset::delCol(ncols() - 1);
699         }
700 }
701
702
703 string const & MathHullInset::getType() const
704 {
705         return type_;
706 }
707
708
709 void MathHullInset::setType(string const & type)
710 {
711         type_ = type;
712         setDefaults();
713 }
714
715
716
717 void MathHullInset::mutate(string const & newtype)
718 {
719         //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
720
721         // we try to move along the chain
722         // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
723         //                                     ^                                     |
724         //                                     +-------------------------------------+
725         // we use eqnarray as intermediate type for mutations that are not
726         // directly supported because it handles labels and numbering for
727         // "down mutation".
728
729         if (newtype == "dump") {
730                 dump();
731         }
732
733         else if (newtype == type_) {
734                 // done
735         }
736
737         else if (typecode(newtype) < 0) {
738                 // unknown type
739         }
740
741         else if (type_ == "none") {
742                 setType("simple");
743                 numbered(0, false);
744                 mutate(newtype);
745         }
746
747         else if (type_ == "simple") {
748                 if (newtype == "none") {
749                         setType("none");
750                         numbered(0, false);
751                 } else {
752                         setType("equation");
753                         numbered(0, false);
754                         mutate(newtype);
755                 }
756         }
757
758         else if (type_ == "equation") {
759                 if (smaller(newtype, type_)) {
760                         setType("simple");
761                         numbered(0, false);
762                         mutate(newtype);
763                 } else if (newtype == "eqnarray") {
764                         // split it "nicely" on the first relop
765                         splitTo3Cols();
766                         setType("eqnarray");
767                 } else if (newtype == "multline" || newtype == "gather") {
768                         setType(newtype);
769                 } else {
770                         // split it "nicely"
771                         splitTo2Cols();
772                         setType("align");
773                         mutate(newtype);
774                 }
775         }
776
777         else if (type_ == "eqnarray") {
778                 if (smaller(newtype, type_)) {
779                         // set correct (no)numbering
780                         bool allnonum = true;
781                         for (row_type row = 0; row < nrows(); ++row)
782                                 if (!nonum_[row])
783                                         allnonum = false;
784
785                         // set first non-empty label
786                         string label;
787                         for (row_type row = 0; row < nrows(); ++row) {
788                                 if (!label_[row].empty()) {
789                                         label = label_[row];
790                                         break;
791                                 }
792                         }
793
794                         glueall();
795                         nonum_[0] = allnonum;
796                         label_[0] = label;
797                         mutate(newtype);
798                 } else { // align & Co.
799                         changeCols(2);
800                         setType("align");
801                         mutate(newtype);
802                 }
803         }
804
805         else if (type_ ==  "align"   || type_ == "alignat" ||
806                  type_ == "xalignat" || type_ == "flalign") {
807                 if (smaller(newtype, "align")) {
808                         changeCols(3);
809                         setType("eqnarray");
810                         mutate(newtype);
811                 } else if (newtype == "gather" || newtype == "multline") {
812                         changeCols(1);
813                         setType(newtype);
814                 } else if (newtype ==   "xxalignat") {
815                         for (row_type row = 0; row < nrows(); ++row)
816                                 numbered(row, false);
817                         setType(newtype);
818                 } else {
819                         setType(newtype);
820                 }
821         }
822
823         else if (type_ == "xxalignat") {
824                 for (row_type row = 0; row < nrows(); ++row)
825                         numbered(row, false);
826                 if (smaller(newtype, "align")) {
827                         changeCols(3);
828                         setType("eqnarray");
829                         mutate(newtype);
830                 } else if (newtype == "gather" || newtype == "multline") {
831                         changeCols(1);
832                         setType(newtype);
833                 } else {
834                         setType(newtype);
835                 }
836         }
837
838         else if (type_ == "multline" || type_ == "gather") {
839                 if (newtype == "gather" || newtype == "multline")
840                         setType(newtype);
841                 else if (newtype ==   "align"   || newtype == "flalign"  ||
842                          newtype ==   "alignat" || newtype == "xalignat") {
843                         splitTo2Cols();
844                         setType(newtype);
845                 } else if (newtype ==   "xxalignat") {
846                         splitTo2Cols();
847                         for (row_type row = 0; row < nrows(); ++row)
848                                 numbered(row, false);
849                         setType(newtype);
850                 } else {
851                         splitTo3Cols();
852                         setType("eqnarray");
853                         mutate(newtype);
854                 }
855         }
856
857         else {
858                 lyxerr << "mutation from '" << type_
859                        << "' to '" << newtype << "' not implemented" << endl;
860         }
861 }
862
863
864 string MathHullInset::eolString(row_type row, bool emptyline, bool fragile) const
865 {
866         string res;
867         if (numberedType()) {
868                 if (!label_[row].empty() && !nonum_[row])
869                         res += "\\label{" + label_[row] + '}';
870                 if (nonum_[row] && (type_ != "multline"))
871                         res += "\\nonumber ";
872         }
873         return res + MathGridInset::eolString(row, emptyline, fragile);
874 }
875
876
877 void MathHullInset::write(WriteStream & os) const
878 {
879         header_write(os);
880         MathGridInset::write(os);
881         footer_write(os);
882 }
883
884
885 void MathHullInset::normalize(NormalStream & os) const
886 {
887         os << "[formula " << type_ << ' ';
888         MathGridInset::normalize(os);
889         os << "] ";
890 }
891
892
893 void MathHullInset::mathmlize(MathMLStream & os) const
894 {
895         MathGridInset::mathmlize(os);
896 }
897
898
899 void MathHullInset::infoize(ostream & os) const
900 {
901         os << "Type: " << type_;
902 }
903
904
905 void MathHullInset::check() const
906 {
907         BOOST_ASSERT(nonum_.size() == nrows());
908         BOOST_ASSERT(label_.size() == nrows());
909 }
910
911
912 void MathHullInset::doExtern(LCursor & cur, FuncRequest & func)
913 {
914         string lang;
915         string extra;
916         istringstream iss(func.argument);
917         iss >> lang >> extra;
918         if (extra.empty())
919                 extra = "noextra";
920
921 #ifdef WITH_WARNINGS
922 #warning temporarily disabled
923         //if (cur.selection()) {
924         //      MathArray ar;
925         //      selGet(cur.ar);
926         //      lyxerr << "use selection: " << ar << endl;
927         //      insert(pipeThroughExtern(lang, extra, ar));
928         //      return;
929         //}
930 #endif
931
932         MathArray eq;
933         eq.push_back(MathAtom(new MathCharInset('=')));
934
935         // go to first item in line
936         cur.idx() -= cur.idx() % ncols();
937         cur.pos() = 0;
938
939         if (getType() == "simple") {
940                 size_type pos = cur.cell().find_last(eq);
941                 MathArray ar;
942                 if (cur.inMathed() && cur.selection()) {
943                         asArray(grabAndEraseSelection(cur), ar);
944                 } else if (pos == cur.cell().size()) {
945                         ar = cur.cell();
946                         lyxerr << "use whole cell: " << ar << endl;
947                 } else {
948                         ar = MathArray(cur.cell().begin() + pos + 1, cur.cell().end());
949                         lyxerr << "use partial cell form pos: " << pos << endl;
950                 }
951                 cur.cell().append(eq);
952                 cur.cell().append(pipeThroughExtern(lang, extra, ar));
953                 cur.pos() = cur.lastpos();
954                 return;
955         }
956
957         if (getType() == "equation") {
958                 lyxerr << "use equation inset" << endl;
959                 mutate("eqnarray");
960                 MathArray & ar = cur.cell();
961                 lyxerr << "use cell: " << ar << endl;
962                 ++cur.idx();
963                 cur.cell() = eq;
964                 ++cur.idx();
965                 cur.cell() = pipeThroughExtern(lang, extra, ar);
966                 // move to end of line
967                 cur.pos() = cur.lastpos();
968                 return;
969         }
970
971         {
972                 lyxerr << "use eqnarray" << endl;
973                 cur.idx() += 2 - cur.idx() % ncols();
974                 cur.pos() = 0;
975                 MathArray ar = cur.cell();
976                 lyxerr << "use cell: " << ar << endl;
977 #ifdef WITH_WARNINGS
978 #warning temporarily disabled
979 #endif
980                 addRow(cur.row());
981                 ++cur.idx();
982                 ++cur.idx();
983                 cur.cell() = eq;
984                 ++cur.idx();
985                 cur.cell() = pipeThroughExtern(lang, extra, ar);
986                 cur.pos() = cur.lastpos();
987         }
988 }
989
990
991 void MathHullInset::doDispatch(LCursor & cur, FuncRequest & cmd)
992 {
993         //lyxerr << "action: " << cmd.action << endl;
994         switch (cmd.action) {
995
996         case LFUN_FINISHED_LEFT:
997         case LFUN_FINISHED_RIGHT:
998         case LFUN_FINISHED_UP:
999         case LFUN_FINISHED_DOWN:
1000                 //lyxerr << "action: " << cmd.action << endl;
1001                 MathGridInset::doDispatch(cur, cmd);
1002                 notifyCursorLeaves(cur);
1003                 cur.undispatched();
1004                 break;
1005
1006         case LFUN_BREAK_PARAGRAPH:
1007                 // just swallow this
1008                 break;
1009
1010         case LFUN_BREAK_LINE:
1011                 // some magic for the common case
1012                 if (type_ == "simple" || type_ == "equation") {
1013                         recordUndoInset(cur);
1014                         bool const align =
1015                                 cur.bv().buffer()->params().use_amsmath == BufferParams::AMS_ON;
1016                         mutate(align ? "align" : "eqnarray");
1017                         cur.idx() = 0;
1018                         cur.pos() = cur.lastpos();
1019                 }
1020                 MathGridInset::doDispatch(cur, cmd);
1021                 break;
1022
1023         case LFUN_MATH_NUMBER:
1024                 //lyxerr << "toggling all numbers" << endl;
1025                 if (display()) {
1026                         recordUndoInset(cur);
1027                         bool old = numberedType();
1028                         if (type_ == "multline")
1029                                 numbered(nrows() - 1, !old);
1030                         else
1031                                 for (row_type row = 0; row < nrows(); ++row)
1032                                         numbered(row, !old);
1033                         cur.message(old ? _("No number") : _("Number"));
1034                 }
1035                 break;
1036
1037         case LFUN_MATH_NONUMBER:
1038                 if (display()) {
1039                         recordUndoInset(cur);
1040                         row_type r = (type_ == "multline") ? nrows() - 1 : cur.row();
1041                         bool old = numbered(r);
1042                         cur.message(old ? _("No number") : _("Number"));
1043                         numbered(r, !old);
1044                 }
1045                 break;
1046
1047         case LFUN_LABEL_INSERT: {
1048                 recordUndoInset(cur);
1049                 row_type r = (type_ == "multline") ? nrows() - 1 : cur.row();
1050                 string old_label = label(r);
1051                 string const default_label =
1052                         (lyxrc.label_init_length >= 0) ? "eq:" : "";
1053                 if (old_label.empty())
1054                         old_label = default_label;
1055                 string const contents = cmd.argument.empty() ?
1056                         old_label : cmd.argument;
1057
1058                 InsetCommandParams p("label", contents);
1059                 string const data = InsetCommandMailer::params2string("label", p);
1060
1061                 if (cmd.argument.empty()) {
1062                         cur.bv().owner()->getDialogs().show("label", data, 0);
1063                 } else {
1064                         FuncRequest fr(LFUN_INSET_INSERT, data);
1065                         dispatch(cur, fr);
1066                 }
1067                 break;
1068         }
1069
1070         case LFUN_INSET_INSERT: {
1071                 //lyxerr << "arg: " << cmd.argument << endl;
1072                 string const name = cmd.getArg(0);
1073                 if (name == "label") {
1074                         InsetCommandParams p;
1075                         InsetCommandMailer::string2params(name, cmd.argument, p);
1076                         string str = p.getContents();
1077                         recordUndoInset(cur);
1078                         row_type const r = (type_ == "multline") ? nrows() - 1 : cur.row();
1079                         str = lyx::support::trim(str);
1080                         if (!str.empty())
1081                                 numbered(r, true);
1082                         string old = label(r);
1083                         if (str != old) {
1084                                 cur.bv().buffer()->changeRefsIfUnique(old, str);
1085                                 label(r, str);
1086                         }
1087                         break;
1088                 }
1089                 MathArray ar;
1090                 if (createMathInset_fromDialogStr(cmd.argument, ar)) {
1091                         recordUndo(cur);
1092                         cur.insert(ar);
1093                 } else
1094                         cur.undispatched();
1095                 break;
1096         }
1097
1098         case LFUN_MATH_EXTERN:
1099                 recordUndoInset(cur);
1100                 doExtern(cur, cmd);
1101                 break;
1102
1103         case LFUN_MATH_MUTATE: {
1104                 recordUndoInset(cur);
1105                 row_type row = cur.row();
1106                 col_type col = cur.col();
1107                 mutate(cmd.argument);
1108                 cur.idx() = row * ncols() + col;
1109                 if (cur.idx() > cur.lastidx()) {
1110                         cur.idx() = cur.lastidx();
1111                         cur.pos() = cur.lastpos();
1112                 }
1113                 if (cur.pos() > cur.lastpos())
1114                         cur.pos() = cur.lastpos();
1115                 //cur.dispatched(FINISHED);
1116                 break;
1117         }
1118
1119         case LFUN_MATH_DISPLAY: {
1120                 recordUndoInset(cur);
1121                 mutate(type_ == "simple" ? "equation" : "simple");
1122                 cur.idx() = 0;
1123                 cur.pos() = cur.lastpos();
1124                 //cur.dispatched(FINISHED);
1125                 break;
1126         }
1127
1128         default:
1129                 MathGridInset::doDispatch(cur, cmd);
1130                 break;
1131         }
1132 }
1133
1134
1135 bool MathHullInset::getStatus(LCursor & cur, FuncRequest const & cmd,
1136                 FuncStatus & status) const
1137 {
1138         switch (cmd.action) {
1139         case LFUN_FINISHED_LEFT:
1140         case LFUN_FINISHED_RIGHT:
1141         case LFUN_FINISHED_UP:
1142         case LFUN_FINISHED_DOWN:
1143                 status.enabled(true);
1144                 return true;
1145         case LFUN_BREAK_LINE:
1146         case LFUN_MATH_NUMBER:
1147         case LFUN_MATH_NONUMBER:
1148         case LFUN_MATH_EXTERN:
1149         case LFUN_MATH_MUTATE:
1150         case LFUN_MATH_DISPLAY:
1151                 // we handle these
1152                 status.enabled(true);
1153                 return true;
1154         case LFUN_LABEL_INSERT:
1155                 status.enabled(type_ != "simple");
1156                 return true;
1157         case LFUN_INSET_INSERT: {
1158                 // Don't test createMathInset_fromDialogStr(), since
1159                 // getStatus is not called with a valid reference and the
1160                 // dialog would not be applyable.
1161                 string const name = cmd.getArg(0);
1162                 status.enabled(name == "ref" ||
1163                                (name == "label" && type_ != "simple"));
1164                 break;
1165         }
1166         case LFUN_TABULAR_FEATURE: {
1167                 istringstream is(cmd.argument);
1168                 string s;
1169                 is >> s;
1170                 if (!rowChangeOK()
1171                     && (s == "append-row"
1172                         || s == "delete-row"
1173                         || s == "copy-row")) {
1174                         status.message(bformat(
1175                                 N_("Can't change number of rows in '%1$s'"),
1176                                 type_));
1177                         status.enabled(false);
1178                         return true;
1179                 }
1180                 if (!colChangeOK()
1181                     && (s == "append-column"
1182                         || s == "delete-column"
1183                         || s == "copy-column")) {
1184                         status.message(bformat(
1185                                 N_("Can't change number of columns in '%1$s'"),
1186                                 type_));
1187                         status.enabled(false);
1188                         return true;
1189                 }
1190                 if ((type_ == "simple"
1191                   || type_ == "equation"
1192                   || type_ == "none") &&
1193                     (s == "add-hline-above" || s == "add-hline-below")) {
1194                         status.message(bformat(
1195                                 N_("Can't add horizontal grid lines in '%1$s'"),
1196                                 type_));
1197                         status.enabled(false);
1198                         return true;
1199                 }
1200                 if (s == "add-vline-left" || s == "add-vline-right") {
1201                         status.message(bformat(
1202                                 N_("Can't add vertical grid lines in '%1$s'"),
1203                                 type_));
1204                         status.enabled(false);
1205                         return true;
1206                 }
1207                 if (s == "valign-top" || s == "valign-middle"
1208                  || s == "valign-bottom" || s == "align-left"
1209                  || s == "align-center" || s == "align-right") {
1210                         status.enabled(false);
1211                         return true;
1212                 }
1213                 return MathGridInset::getStatus(cur, cmd, status);
1214         }
1215         default:
1216                 return MathGridInset::getStatus(cur, cmd, status);
1217         }
1218
1219         // This cannot really happen, but inserted to shut-up gcc
1220         return MathGridInset::getStatus(cur, cmd, status);
1221 }
1222
1223
1224 /////////////////////////////////////////////////////////////////////
1225
1226 #include "math_arrayinset.h"
1227 #include "math_deliminset.h"
1228 #include "math_factory.h"
1229 #include "math_parser.h"
1230 #include "math_spaceinset.h"
1231 #include "ref_inset.h"
1232
1233 #include "bufferview_funcs.h"
1234 #include "lyxtext.h"
1235
1236 #include "frontends/LyXView.h"
1237 #include "frontends/Dialogs.h"
1238
1239 #include "support/lyxlib.h"
1240
1241
1242 // simply scrap this function if you want
1243 void MathHullInset::mutateToText()
1244 {
1245 #if 0
1246         // translate to latex
1247         ostringstream os;
1248         latex(NULL, os, false, false);
1249         string str = os.str();
1250
1251         // insert this text
1252         LyXText * lt = view_->getLyXText();
1253         string::const_iterator cit = str.begin();
1254         string::const_iterator end = str.end();
1255         for (; cit != end; ++cit)
1256                 view_->owner()->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1257
1258         // remove ourselves
1259         //view_->owner()->dispatch(LFUN_ESCAPE);
1260 #endif
1261 }
1262
1263
1264 void MathHullInset::handleFont(LCursor & cur, string const & arg,
1265         string const & font)
1266 {
1267         // this whole function is a hack and won't work for incremental font
1268         // changes...
1269         recordUndo(cur);
1270         if (cur.inset().asMathInset()->name() == font)
1271                 cur.handleFont(font);
1272         else {
1273                 cur.handleNest(createMathInset(font));
1274                 cur.insert(arg);
1275         }
1276 }
1277
1278
1279 void MathHullInset::handleFont2(LCursor & cur, string const & arg)
1280 {
1281         recordUndo(cur);
1282         LyXFont font;
1283         bool b;
1284         bv_funcs::string2font(arg, font, b);
1285         if (font.color() != LColor::inherit) {
1286                 MathAtom at = MathAtom(new MathColorInset(true, font.color()));
1287                 cur.handleNest(at, 0);
1288         }
1289 }
1290
1291
1292 void MathHullInset::edit(LCursor & cur, bool left)
1293 {
1294         cur.push(*this);
1295         left ? idxFirst(cur) : idxLast(cur);
1296 }
1297
1298
1299 string const MathHullInset::editMessage() const
1300 {
1301         return _("Math editor mode");
1302 }
1303
1304
1305 void MathHullInset::revealCodes(LCursor & cur) const
1306 {
1307         if (!cur.inMathed())
1308                 return;
1309         ostringstream os;
1310         cur.info(os);
1311         cur.message(os.str());
1312 /*
1313         // write something to the minibuffer
1314         // translate to latex
1315         cur.markInsert(bv);
1316         ostringstream os;
1317         write(NULL, os);
1318         string str = os.str();
1319         cur.markErase(bv);
1320         string::size_type pos = 0;
1321         string res;
1322         for (string::iterator it = str.begin(); it != str.end(); ++it) {
1323                 if (*it == '\n')
1324                         res += ' ';
1325                 else if (*it == '\0') {
1326                         res += "  -X-  ";
1327                         pos = it - str.begin();
1328                 }
1329                 else
1330                         res += *it;
1331         }
1332         if (pos > 30)
1333                 res = res.substr(pos - 30);
1334         if (res.size() > 60)
1335                 res = res.substr(0, 60);
1336         cur.message(res);
1337 */
1338 }
1339
1340
1341 InsetBase::Code MathHullInset::lyxCode() const
1342 {
1343         return MATH_CODE;
1344 }
1345
1346
1347 /////////////////////////////////////////////////////////////////////
1348
1349
1350 #if 0
1351 bool MathHullInset::searchForward(BufferView * bv, string const & str,
1352                                      bool, bool)
1353 {
1354 #ifdef WITH_WARNINGS
1355 #warning completely broken
1356 #endif
1357         static MathHullInset * lastformula = 0;
1358         static CursorBase current = DocIterator(ibegin(nucleus()));
1359         static MathArray ar;
1360         static string laststr;
1361
1362         if (lastformula != this || laststr != str) {
1363                 //lyxerr << "reset lastformula to " << this << endl;
1364                 lastformula = this;
1365                 laststr = str;
1366                 current = ibegin(nucleus());
1367                 ar.clear();
1368                 mathed_parse_cell(ar, str);
1369         } else {
1370                 increment(current);
1371         }
1372         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1373
1374         for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1375                 CursorSlice & top = it.back();
1376                 MathArray const & a = top.asMathInset()->cell(top.idx_);
1377                 if (a.matchpart(ar, top.pos_)) {
1378                         bv->cursor().setSelection(it, ar.size());
1379                         current = it;
1380                         top.pos_ += ar.size();
1381                         bv->update();
1382                         return true;
1383                 }
1384         }
1385
1386         //lyxerr << "not found!" << endl;
1387         lastformula = 0;
1388         return false;
1389 }
1390 #endif
1391
1392
1393 void MathHullInset::write(Buffer const &, std::ostream & os) const
1394 {
1395         WriteStream wi(os, false, false);
1396         os << "Formula ";
1397         write(wi);
1398 }
1399
1400
1401 void MathHullInset::read(Buffer const &, LyXLex & lex)
1402 {
1403         MathAtom at;
1404         mathed_parse_normal(at, lex);
1405         operator=(*at->asHullInset());
1406 }
1407
1408
1409 int MathHullInset::plaintext(Buffer const &, ostream & os,
1410                         OutputParams const &) const
1411 {
1412         if (0 && display()) {
1413                 Dimension dim;
1414                 TextMetricsInfo mi;
1415                 metricsT(mi, dim);
1416                 TextPainter tpain(dim.width(), dim.height());
1417                 drawT(tpain, 0, dim.ascent());
1418                 tpain.show(os, 3);
1419                 // reset metrics cache to "real" values
1420                 //metrics();
1421                 return tpain.textheight();
1422         } else {
1423                 WriteStream wi(os, false, true);
1424                 wi << cell(0);
1425                 return wi.line();
1426         }
1427 }
1428
1429
1430 int MathHullInset::docbook(Buffer const & buf, ostream & os,
1431                           OutputParams const & runparams) const
1432 {
1433         MathMLStream ms(os);
1434         int res = 0;
1435         string name;
1436         if (getType() == "simple")
1437                 name= "inlineequation";
1438         else
1439                 name = "informalequation";
1440
1441         string bname = name;
1442         if (!label(0).empty())
1443                 bname += " id=\"" + sgml::cleanID(buf, runparams, label(0)) + "\"";
1444         ms << MTag(bname.c_str());
1445
1446         ostringstream ls;
1447         if (runparams.flavor == OutputParams::XML) {
1448                 ms << MTag("alt role=\"tex\" ");
1449                 // Workaround for db2latex: db2latex always includes equations with
1450                 // \ensuremath{} or \begin{display}\end{display}
1451                 // so we strip LyX' math environment
1452                 WriteStream wi(ls, false, false);
1453                 MathGridInset::write(wi);
1454                 ms << subst(subst(ls.str(), "&", "&amp;"), "<", "&lt;");
1455                 ms << ETag("alt");
1456                 ms << MTag("math");
1457                 MathGridInset::mathmlize(ms);
1458                 ms << ETag("math");
1459         } else {
1460                 ms << MTag("alt role=\"tex\"");
1461                 res = latex(buf, ls, runparams);
1462                 ms << subst(subst(ls.str(), "&", "&amp;"), "<", "&lt;");
1463                 ms << ETag("alt");
1464         }
1465
1466         ms <<  "<graphic fileref=\"eqn/";
1467         if ( !label(0).empty())
1468                 ms << sgml::cleanID(buf, runparams, label(0));
1469         else
1470                 ms << sgml::uniqueID("anon");
1471
1472         if (runparams.flavor == OutputParams::XML)
1473                 ms << "\"/>";
1474         else
1475                 ms << "\">";
1476
1477         ms << ETag(name.c_str());
1478         return ms.line() + res;
1479 }
1480
1481
1482 int MathHullInset::textString(Buffer const & buf, ostream & os,
1483                        OutputParams const & op) const
1484 {
1485         return plaintext(buf, os, op);
1486 }