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