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