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