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