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