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