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