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