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