]> git.lyx.org Git - lyx.git/blob - src/mathed/math_hullinset.C
Fix to bug 2362: Deleting superscript also deletes subscript.
[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                 if (old_label.empty())
1050                         old_label = default_label;
1051                 string const contents = cmd.argument.empty() ?
1052                         old_label : cmd.argument;
1053
1054                 InsetCommandParams p("label", contents);
1055                 string const data = InsetCommandMailer::params2string("label", p);
1056
1057                 if (cmd.argument.empty()) {
1058                         cur.bv().owner()->getDialogs().show("label", data, 0);
1059                 } else {
1060                         FuncRequest fr(LFUN_INSET_INSERT, data);
1061                         dispatch(cur, fr);
1062                 }
1063                 break;
1064         }
1065
1066         case LFUN_INSET_INSERT: {
1067                 //lyxerr << "arg: " << cmd.argument << endl;
1068                 string const name = cmd.getArg(0);
1069                 if (name == "label") {
1070                         InsetCommandParams p;
1071                         InsetCommandMailer::string2params(name, cmd.argument, p);
1072                         string str = p.getContents();
1073                         recordUndoInset(cur);
1074                         row_type const r = (type_ == "multline") ? nrows() - 1 : cur.row();
1075                         str = lyx::support::trim(str);
1076                         if (!str.empty())
1077                                 numbered(r, true);
1078                         string old = label(r);
1079                         if (str != old) {
1080                                 cur.bv().buffer()->changeRefsIfUnique(old, str);
1081                                 label(r, str);
1082                         }
1083                         break;
1084                 }
1085                 MathArray ar;
1086                 if (createMathInset_fromDialogStr(cmd.argument, ar)) {
1087                         recordUndo(cur);
1088                         cur.insert(ar);
1089                 } else
1090                         cur.undispatched();
1091                 break;
1092         }
1093
1094         case LFUN_MATH_EXTERN:
1095                 recordUndoInset(cur);
1096                 doExtern(cur, cmd);
1097                 break;
1098
1099         case LFUN_MATH_MUTATE: {
1100                 recordUndoInset(cur);
1101                 row_type row = cur.row();
1102                 col_type col = cur.col();
1103                 mutate(cmd.argument);
1104                 cur.idx() = row * ncols() + col;
1105                 if (cur.idx() > cur.lastidx()) {
1106                         cur.idx() = cur.lastidx();
1107                         cur.pos() = cur.lastpos();
1108                 }
1109                 if (cur.pos() > cur.lastpos())
1110                         cur.pos() = cur.lastpos();
1111                 //cur.dispatched(FINISHED);
1112                 break;
1113         }
1114
1115         case LFUN_MATH_DISPLAY: {
1116                 recordUndoInset(cur);
1117                 mutate(type_ == "simple" ? "equation" : "simple");
1118                 cur.idx() = 0;
1119                 cur.pos() = cur.lastpos();
1120                 //cur.dispatched(FINISHED);
1121                 break;
1122         }
1123
1124         default:
1125                 MathGridInset::doDispatch(cur, cmd);
1126                 break;
1127         }
1128 }
1129
1130
1131 bool MathHullInset::getStatus(LCursor & cur, FuncRequest const & cmd,
1132                 FuncStatus & status) const
1133 {
1134         switch (cmd.action) {
1135         case LFUN_FINISHED_LEFT:
1136         case LFUN_FINISHED_RIGHT:
1137         case LFUN_FINISHED_UP:
1138         case LFUN_FINISHED_DOWN:
1139                 status.enabled(true);
1140                 return true;
1141         case LFUN_BREAKLINE:
1142         case LFUN_MATH_NUMBER:
1143         case LFUN_MATH_NONUMBER:
1144         case LFUN_MATH_EXTERN:
1145         case LFUN_MATH_MUTATE:
1146         case LFUN_MATH_DISPLAY:
1147                 // we handle these
1148                 status.enabled(true);
1149                 return true;
1150         case LFUN_INSERT_LABEL:
1151                 status.enabled(type_ != "simple");
1152                 return true;
1153         case LFUN_INSET_INSERT: {
1154                 // Don't test createMathInset_fromDialogStr(), since
1155                 // getStatus is not called with a valid reference and the
1156                 // dialog would not be applyable.
1157                 string const name = cmd.getArg(0);
1158                 status.enabled(name == "ref" ||
1159                                (name == "label" && type_ != "simple"));
1160                 break;
1161         }
1162         case LFUN_TABULAR_FEATURE: {
1163                 istringstream is(cmd.argument);
1164                 string s;
1165                 is >> s;
1166                 if (!rowChangeOK()
1167                     && (s == "append-row"
1168                         || s == "delete-row"
1169                         || s == "copy-row")) {
1170                         status.message(bformat(
1171                                 N_("Can't change number of rows in '%1$s'"),
1172                                 type_));
1173                         status.enabled(false);
1174                         return true;
1175                 }
1176                 if (!colChangeOK()
1177                     && (s == "append-column"
1178                         || s == "delete-column"
1179                         || s == "copy-column")) {
1180                         status.message(bformat(
1181                                 N_("Can't change number of columns in '%1$s'"),
1182                                 type_));
1183                         status.enabled(false);
1184                         return true;
1185                 }
1186                 if ((type_ == "simple"
1187                   || type_ == "equation"
1188                   || type_ == "none") &&
1189                     (s == "add-hline-above" || s == "add-hline-below")) {
1190                         status.message(bformat(
1191                                 N_("Can't add horizontal grid lines in '%1$s'"),
1192                                 type_));
1193                         status.enabled(false);
1194                         return true;
1195                 }
1196                 if (s == "add-vline-left" || s == "add-vline-right") {
1197                         status.message(bformat(
1198                                 N_("Can't add vertical grid lines in '%1$s'"),
1199                                 type_));
1200                         status.enabled(false);
1201                         return true;
1202                 }
1203                 if (s == "valign-top" || s == "valign-middle"
1204                  || s == "valign-bottom" || s == "align-left"
1205                  || s == "align-center" || s == "align-right") {
1206                         status.enabled(false);
1207                         return true;
1208                 }
1209                 return MathGridInset::getStatus(cur, cmd, status);
1210         }
1211         default:
1212                 return MathGridInset::getStatus(cur, cmd, status);
1213         }
1214
1215         // This cannot really happen, but inserted to shut-up gcc
1216         return MathGridInset::getStatus(cur, cmd, status);
1217 }
1218
1219
1220 /////////////////////////////////////////////////////////////////////
1221
1222 #include "math_arrayinset.h"
1223 #include "math_deliminset.h"
1224 #include "math_factory.h"
1225 #include "math_parser.h"
1226 #include "math_spaceinset.h"
1227 #include "ref_inset.h"
1228
1229 #include "bufferview_funcs.h"
1230 #include "lyxtext.h"
1231
1232 #include "frontends/LyXView.h"
1233 #include "frontends/Dialogs.h"
1234
1235 #include "support/lyxlib.h"
1236
1237
1238 // simply scrap this function if you want
1239 void MathHullInset::mutateToText()
1240 {
1241 #if 0
1242         // translate to latex
1243         ostringstream os;
1244         latex(NULL, os, false, false);
1245         string str = os.str();
1246
1247         // insert this text
1248         LyXText * lt = view_->getLyXText();
1249         string::const_iterator cit = str.begin();
1250         string::const_iterator end = str.end();
1251         for (; cit != end; ++cit)
1252                 view_->owner()->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1253
1254         // remove ourselves
1255         //view_->owner()->dispatch(LFUN_ESCAPE);
1256 #endif
1257 }
1258
1259
1260 void MathHullInset::handleFont(LCursor & cur, string const & arg,
1261         string const & font)
1262 {
1263         // this whole function is a hack and won't work for incremental font
1264         // changes...
1265         recordUndo(cur);
1266         if (cur.inset().asMathInset()->name() == font)
1267                 cur.handleFont(font);
1268         else {
1269                 cur.handleNest(createMathInset(font));
1270                 cur.insert(arg);
1271         }
1272 }
1273
1274
1275 void MathHullInset::handleFont2(LCursor & cur, string const & arg)
1276 {
1277         recordUndo(cur);
1278         LyXFont font;
1279         bool b;
1280         bv_funcs::string2font(arg, font, b);
1281         if (font.color() != LColor::inherit) {
1282                 MathAtom at = MathAtom(new MathColorInset(true, font.color()));
1283                 cur.handleNest(at, 0);
1284         }
1285 }
1286
1287
1288 void MathHullInset::edit(LCursor & cur, bool left)
1289 {
1290         cur.push(*this);
1291         left ? idxFirst(cur) : idxLast(cur);
1292 }
1293
1294
1295 string const MathHullInset::editMessage() const
1296 {
1297         return _("Math editor mode");
1298 }
1299
1300
1301 void MathHullInset::revealCodes(LCursor & cur) const
1302 {
1303         if (!cur.inMathed())
1304                 return;
1305         ostringstream os;
1306         cur.info(os);
1307         cur.message(os.str());
1308 /*
1309         // write something to the minibuffer
1310         // translate to latex
1311         cur.markInsert(bv);
1312         ostringstream os;
1313         write(NULL, os);
1314         string str = os.str();
1315         cur.markErase(bv);
1316         string::size_type pos = 0;
1317         string res;
1318         for (string::iterator it = str.begin(); it != str.end(); ++it) {
1319                 if (*it == '\n')
1320                         res += ' ';
1321                 else if (*it == '\0') {
1322                         res += "  -X-  ";
1323                         pos = it - str.begin();
1324                 }
1325                 else
1326                         res += *it;
1327         }
1328         if (pos > 30)
1329                 res = res.substr(pos - 30);
1330         if (res.size() > 60)
1331                 res = res.substr(0, 60);
1332         cur.message(res);
1333 */
1334 }
1335
1336
1337 InsetBase::Code MathHullInset::lyxCode() const
1338 {
1339         return MATH_CODE;
1340 }
1341
1342
1343 /////////////////////////////////////////////////////////////////////
1344
1345
1346 #if 0
1347 bool MathHullInset::searchForward(BufferView * bv, string const & str,
1348                                      bool, bool)
1349 {
1350 #ifdef WITH_WARNINGS
1351 #warning completely broken
1352 #endif
1353         static MathHullInset * lastformula = 0;
1354         static CursorBase current = DocIterator(ibegin(nucleus()));
1355         static MathArray ar;
1356         static string laststr;
1357
1358         if (lastformula != this || laststr != str) {
1359                 //lyxerr << "reset lastformula to " << this << endl;
1360                 lastformula = this;
1361                 laststr = str;
1362                 current = ibegin(nucleus());
1363                 ar.clear();
1364                 mathed_parse_cell(ar, str);
1365         } else {
1366                 increment(current);
1367         }
1368         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1369
1370         for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1371                 CursorSlice & top = it.back();
1372                 MathArray const & a = top.asMathInset()->cell(top.idx_);
1373                 if (a.matchpart(ar, top.pos_)) {
1374                         bv->cursor().setSelection(it, ar.size());
1375                         current = it;
1376                         top.pos_ += ar.size();
1377                         bv->update();
1378                         return true;
1379                 }
1380         }
1381
1382         //lyxerr << "not found!" << endl;
1383         lastformula = 0;
1384         return false;
1385 }
1386 #endif
1387
1388
1389 void MathHullInset::write(Buffer const &, std::ostream & os) const
1390 {
1391         WriteStream wi(os, false, false);
1392         os << "Formula ";
1393         write(wi);
1394 }
1395
1396
1397 void MathHullInset::read(Buffer const &, LyXLex & lex)
1398 {
1399         MathAtom at;
1400         mathed_parse_normal(at, lex);
1401         operator=(*at->asHullInset());
1402 }
1403
1404
1405 int MathHullInset::plaintext(Buffer const &, ostream & os,
1406                         OutputParams const &) const
1407 {
1408         if (0 && display()) {
1409                 Dimension dim;
1410                 TextMetricsInfo mi;
1411                 metricsT(mi, dim);
1412                 TextPainter tpain(dim.width(), dim.height());
1413                 drawT(tpain, 0, dim.ascent());
1414                 tpain.show(os, 3);
1415                 // reset metrics cache to "real" values
1416                 //metrics();
1417                 return tpain.textheight();
1418         } else {
1419                 WriteStream wi(os, false, true);
1420                 wi << cell(0);
1421                 return wi.line();
1422         }
1423 }
1424
1425
1426 int MathHullInset::linuxdoc(Buffer const & buf, ostream & os,
1427                            OutputParams const & runparams) const
1428 {
1429         return docbook(buf, os, runparams);
1430 }
1431
1432
1433 int MathHullInset::docbook(Buffer const & buf, ostream & os,
1434                           OutputParams const & runparams) const
1435 {
1436         MathMLStream ms(os);
1437         int res = 0;
1438         string name;
1439         if (getType() == "simple")
1440                 name= "inlineequation";
1441         else
1442                 name = "informalequation";
1443
1444         string bname = name;
1445         if (!label(0).empty())
1446                 bname += " id=\"" + sgml::cleanID(buf, runparams, label(0)) + "\"";
1447         ms << MTag(bname.c_str());
1448
1449         ostringstream ls;
1450         if (runparams.flavor == OutputParams::XML) {
1451                 ms << MTag("alt role=\"tex\" ");
1452                 // Workaround for db2latex: db2latex always includes equations with
1453                 // \ensuremath{} or \begin{display}\end{display}
1454                 // so we strip LyX' math environment
1455                 WriteStream wi(ls, false, false);
1456                 MathGridInset::write(wi);
1457                 ms << subst(subst(ls.str(), "&", "&amp;"), "<", "&lt;");
1458                 ms << ETag("alt");
1459                 ms << MTag("math");
1460                 MathGridInset::mathmlize(ms);
1461                 ms << ETag("math");
1462         } else {
1463                 ms << MTag("alt role=\"tex\"");
1464                 res = latex(buf, ls, runparams);
1465                 ms << subst(subst(ls.str(), "&", "&amp;"), "<", "&lt;");
1466                 ms << ETag("alt");
1467         }
1468
1469         ms <<  "<graphic fileref=\"eqn/";
1470         if ( !label(0).empty())
1471                 ms << sgml::cleanID(buf, runparams, label(0));
1472         else
1473                 ms << sgml::uniqueID("anon");
1474
1475         if (runparams.flavor == OutputParams::XML)
1476                 ms << "\"/>";
1477         else
1478                 ms << "\">";
1479
1480         ms << ETag(name.c_str());
1481         return ms.line() + res;
1482 }
1483
1484
1485 int MathHullInset::textString(Buffer const & buf, ostream & os,
1486                        OutputParams const & op) const
1487 {
1488         return plaintext(buf, os, op);
1489 }