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