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