]> git.lyx.org Git - features.git/blob - src/mathed/math_hullinset.C
support for color in math
[features.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_hullinset.h"
14 #include "math_mathmlstream.h"
15 #include "math_streamstr.h"
16 #include "math_cursor.h"
17 #include "math_support.h"
18 #include "math_extern.h"
19 #include "math_charinset.h"
20 #include "textpainter.h"
21 #include "debug.h"
22 #include "funcrequest.h"
23 #include "gettext.h"
24 #include "LaTeXFeatures.h"
25 #include "LColor.h"
26 #include "lyxrc.h"
27
28 #include "frontends/Alert.h"
29
30 #include "support/std_sstream.h"
31
32
33 using lyx::support::trim;
34
35 using std::endl;
36 using std::max;
37
38 using std::auto_ptr;
39 using std::istringstream;
40 using std::ostringstream;
41 using std::pair;
42
43
44 namespace {
45
46         int getCols(string const & type)
47         {
48                 if (type == "eqnarray")
49                         return 3;
50                 if (type == "align")
51                         return 2;
52                 if (type == "flalign")
53                         return 2;
54                 if (type == "alignat")
55                         return 2;
56                 if (type == "xalignat")
57                         return 2;
58                 if (type == "xxalignat")
59                         return 2;
60                 return 1;
61         }
62
63
64         // returns position of first relation operator in the array
65         // used for "intelligent splitting"
66         MathArray::size_type firstRelOp(MathArray const & ar)
67         {
68                 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
69                         if ((*it)->isRelOp())
70                                 return it - ar.begin();
71                 return ar.size();
72         }
73
74
75         char const * star(bool numbered)
76         {
77                 return numbered ? "" : "*";
78         }
79
80
81         int typecode(string const & s)
82         {
83                 if (s == "none")      return 0;
84                 if (s == "simple")    return 1;
85                 if (s == "equation")  return 2;
86                 if (s == "eqnarray")  return 3;
87                 if (s == "align")     return 4;
88                 if (s == "alignat")   return 5;
89                 if (s == "xalignat")  return 6;
90                 if (s == "xxalignat") return 7;
91                 if (s == "multline")  return 8;
92                 if (s == "gather")    return 9;
93                 if (s == "flalign")   return 10;
94                 lyxerr << "unknown hull type '" << s << "'" << endl;
95                 return 0;
96         }
97
98         bool smaller(string const & s, string const & t)
99         {
100                 return typecode(s) < typecode(t);
101         }
102
103
104 } // end anon namespace
105
106
107 MathHullInset::MathHullInset()
108         : MathGridInset(1, 1), type_("none"), nonum_(1), label_(1)
109 {
110         setDefaults();
111 }
112
113
114 MathHullInset::MathHullInset(string const & type)
115         : MathGridInset(getCols(type), 1), type_(type), nonum_(1), label_(1)
116 {
117         setDefaults();
118 }
119
120
121 auto_ptr<InsetBase> MathHullInset::clone() const
122 {
123         return auto_ptr<InsetBase>(new MathHullInset(*this));
124 }
125
126
127 MathInset::mode_type MathHullInset::currentMode() const
128 {
129         if (type_ == "none")
130                 return UNDECIDED_MODE;
131         // definitely math mode ...
132         return MATH_MODE;
133 }
134
135
136 bool MathHullInset::idxFirst(idx_type & idx, pos_type & pos) const
137 {
138         idx = 0;
139         pos = 0;
140         return true;
141 }
142
143
144 bool MathHullInset::idxLast(idx_type & idx, pos_type & pos) const
145 {
146         idx = nargs() - 1;
147         pos = cell(idx).size();
148         return true;
149 }
150
151
152 char MathHullInset::defaultColAlign(col_type col)
153 {
154         if (type_ == "eqnarray")
155                 return "rcl"[col];
156         if (typecode(type_) >= typecode("align"))
157                 return "rl"[col & 1];
158         return 'c';
159 }
160
161
162 int MathHullInset::defaultColSpace(col_type col)
163 {
164         if (type_ == "align" || type_ == "alignat")
165                 return 0;
166         if (type_ == "xalignat")
167                 return (col & 1) ? 20 : 0;
168         if (type_ == "xxalignat" || type_ == "flalign")
169                 return (col & 1) ? 40 : 0;
170         return 0;
171 }
172
173
174 char const * MathHullInset::standardFont() const
175 {
176         if (type_ == "none")
177                 return "lyxnochange";
178         lyxerr << "standard font: mathnormal\n";
179         return "mathnormal";
180 }
181
182
183 void MathHullInset::metrics(MetricsInfo & mi, Dimension & dim) const
184 {
185         FontSetChanger dummy1(mi.base, standardFont());
186         StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
187
188         // let the cells adjust themselves
189         MathGridInset::metrics(mi);
190
191         if (display()) {
192                 dim_.asc += 12;
193                 dim_.des += 12;
194         }
195
196         if (numberedType()) {
197                 FontSetChanger dummy(mi.base, "mathbf");
198                 int l = 0;
199                 for (row_type row = 0; row < nrows(); ++row)
200                         l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
201
202                 if (l)
203                         dim_.wid += 30 + l;
204         }
205
206         // make it at least as high as the current font
207         int asc = 0;
208         int des = 0;
209         math_font_max_dim(mi.base.font, asc, des);
210         dim_.asc = max(dim_.asc, asc);
211         dim_.des = max(dim_.des, des);
212
213         // for markers
214         metricsMarkers2();
215         dim = dim_;
216 }
217
218
219 void MathHullInset::draw(PainterInfo & pi, int x, int y) const
220 {
221         FontSetChanger dummy1(pi.base, standardFont());
222         StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
223         MathGridInset::draw(pi, x + 1, y);
224
225         if (numberedType()) {
226                 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
227                 for (row_type row = 0; row < nrows(); ++row) {
228                         int const yy = y + rowinfo_[row].offset_;
229                         FontSetChanger dummy(pi.base, "mathrm");
230                         drawStr(pi, pi.base.font, xx, yy, nicelabel(row));
231                 }
232         }
233
234         drawMarkers2(pi, x, y);
235 }
236
237
238 void MathHullInset::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
239 {
240         if (display()) {
241                 MathGridInset::metricsT(mi, dim);
242         } else {
243                 ostringstream os;
244                 WriteStream wi(os, false, true);
245                 write(wi);
246                 dim.wid = os.str().size();
247                 dim.asc = 1;
248                 dim.des = 0;
249         }
250 }
251
252
253 void MathHullInset::drawT(TextPainter & pain, int x, int y) const
254 {
255         if (display()) {
256                 MathGridInset::drawT(pain, x, y);
257         } else {
258                 ostringstream os;
259                 WriteStream wi(os, false, true);
260                 write(wi);
261                 pain.draw(x, y, os.str().c_str());
262         }
263 }
264
265
266 string MathHullInset::label(row_type row) const
267 {
268         row_type n = nrows();
269         BOOST_ASSERT(row < n);
270         return label_[row];
271 }
272
273
274 void MathHullInset::label(row_type row, string const & label)
275 {
276         //lyxerr << "setting label '" << label << "' for row " << row << endl;
277         label_[row] = label;
278 }
279
280
281 void MathHullInset::numbered(row_type row, bool num)
282 {
283         nonum_[row] = !num;
284 }
285
286
287 bool MathHullInset::numbered(row_type row) const
288 {
289         return !nonum_[row];
290 }
291
292
293 bool MathHullInset::ams() const
294 {
295         return
296                 type_ == "align" ||
297                 type_ == "flalign" ||
298                 type_ == "multline" ||
299                 type_ == "gather" ||
300                 type_ == "alignat" ||
301                 type_ == "xalignat" ||
302                 type_ == "xxalignat";
303 }
304
305
306 bool MathHullInset::display() const
307 {
308         return type_ != "simple" && type_ != "none";
309 }
310
311
312 void MathHullInset::getLabelList(Buffer const &,
313                                  std::vector<string> & labels) const
314 {
315         for (row_type row = 0; row < nrows(); ++row)
316                 if (!label_[row].empty() && nonum_[row] != 1)
317                         labels.push_back(label_[row]);
318 }
319
320
321 bool MathHullInset::numberedType() const
322 {
323         if (type_ == "none")
324                 return false;
325         if (type_ == "simple")
326                 return false;
327         if (type_ == "xxalignat")
328                 return false;
329         for (row_type row = 0; row < nrows(); ++row)
330                 if (!nonum_[row])
331                         return true;
332         return false;
333 }
334
335
336 void MathHullInset::validate(LaTeXFeatures & features) const
337 {
338         if (ams())
339                 features.require("amsmath");
340
341
342         // Validation is necessary only if not using AMS math.
343         // To be safe, we will always run mathedvalidate.
344         //if (features.amsstyle)
345         //  return;
346
347         features.require("boldsymbol");
348         //features.binom      = true;
349
350         MathGridInset::validate(features);
351 }
352
353
354 void MathHullInset::header_write(WriteStream & os) const
355 {
356         bool n = numberedType();
357
358         if (type_ == "none")
359                 ;
360
361         else if (type_ == "simple") {
362                 os << '$';
363                 if (cell(0).empty())
364                         os << ' ';
365         }
366
367         else if (type_ == "equation") {
368                 if (n)
369                         os << "\\begin{equation" << star(n) << "}\n";
370                 else
371                         os << "\\[\n";
372         }
373
374         else if (type_ == "eqnarray" || type_ == "align" || type_ == "flalign"
375                  || type_ == "gather" || type_ == "multline")
376                         os << "\\begin{" << type_ << star(n) << "}\n";
377
378         else if (type_ == "alignat" || type_ == "xalignat")
379                 os << "\\begin{" << type_ << star(n) << '}'
380                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
381
382         else if (type_ == "xxalignat")
383                 os << "\\begin{" << type_ << '}'
384                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
385
386         else
387                 os << "\\begin{unknown" << star(n) << '}';
388 }
389
390
391 void MathHullInset::footer_write(WriteStream & os) const
392 {
393         bool n = numberedType();
394
395         if (type_ == "none")
396                 os << "\n";
397
398         else if (type_ == "simple")
399                 os << '$';
400
401         else if (type_ == "equation")
402                 if (n)
403                         os << "\\end{equation" << star(n) << "}\n";
404                 else
405                         os << "\\]\n";
406
407         else if (type_ == "eqnarray" || type_ == "align" || type_ == "flalign"
408                  || type_ == "alignat" || type_ == "xalignat"
409                  || type_ == "gather" || type_ == "multline")
410                 os << "\\end{" << type_ << star(n) << "}\n";
411
412         else if (type_ == "xxalignat")
413                 os << "\\end{" << type_ << "}\n";
414
415         else
416                 os << "\\end{unknown" << star(n) << '}';
417 }
418
419
420 bool MathHullInset::colChangeOK() const
421 {
422         return
423                 type_ == "align" || type_ == "flalign" ||type_ == "alignat" ||
424                 type_ == "xalignat" || type_ == "xxalignat";
425 }
426
427
428 void MathHullInset::addRow(row_type row)
429 {
430         nonum_.insert(nonum_.begin() + row + 1, !numberedType());
431         label_.insert(label_.begin() + row + 1, string());
432         MathGridInset::addRow(row);
433 }
434
435
436 void MathHullInset::delRow(row_type row)
437 {
438         if (nrows() <= 1)
439                 return;
440         MathGridInset::delRow(row);
441         nonum_.erase(nonum_.begin() + row);
442         label_.erase(label_.begin() + row);
443 }
444
445
446 void MathHullInset::addCol(col_type col)
447 {
448         if (colChangeOK())
449                 MathGridInset::addCol(col);
450         else
451                 lyxerr << "Can't change number of columns in '" << type_ << "'" << endl;
452 }
453
454
455 void MathHullInset::delCol(col_type col)
456 {
457         if (colChangeOK())
458                 MathGridInset::delCol(col);
459         else
460                 lyxerr << "Can't change number of columns in '" << type_ << "'" << endl;
461 }
462
463
464 string MathHullInset::nicelabel(row_type row) const
465 {
466         if (nonum_[row])
467                 return string();
468         if (label_[row].empty())
469                 return string("(#)");
470         return '(' + label_[row] + ')';
471 }
472
473
474 void MathHullInset::glueall()
475 {
476         MathArray ar;
477         for (idx_type i = 0; i < nargs(); ++i)
478                 ar.append(cell(i));
479         *this = MathHullInset("simple");
480         cell(0) = ar;
481         setDefaults();
482 }
483
484
485 string const & MathHullInset::getType() const
486 {
487         return type_;
488 }
489
490
491 void MathHullInset::setType(string const & type)
492 {
493         type_ = type;
494         setDefaults();
495 }
496
497
498
499 void MathHullInset::mutate(string const & newtype)
500 {
501         //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
502
503         // we try to move along the chain
504         // none <-> simple <-> equation <-> eqnarray
505
506         if (newtype == "dump") {
507                 dump();
508         }
509
510         else if (newtype == type_) {
511                 // done
512         }
513
514         else if (type_ == "none") {
515                 setType("simple");
516                 numbered(0, false);
517                 mutate(newtype);
518         }
519
520         else if (type_ == "simple") {
521                 if (newtype == "none") {
522                         setType("none");
523                 } else {
524                         setType("equation");
525                         numbered(0, false);
526                         mutate(newtype);
527                 }
528         }
529
530         else if (type_ == "equation") {
531                 if (smaller(newtype, type_)) {
532                         setType("simple");
533                         mutate(newtype);
534                 } else if (newtype == "eqnarray") {
535                         MathGridInset::addCol(1);
536                         MathGridInset::addCol(1);
537
538                         // split it "nicely" on the firest relop
539                         pos_type pos = firstRelOp(cell(0));
540                         cell(1) = MathArray(cell(0).begin() + pos, cell(0).end());
541                         cell(0).erase(pos, cell(0).size());
542
543                         if (cell(1).size()) {
544                                 cell(2) = MathArray(cell(1).begin() + 1, cell(1).end());
545                                 cell(1).erase(1, cell(1).size());
546                         }
547                         setType("eqnarray");
548                         mutate(newtype);
549                 } else if (newtype == "multline" || newtype == "gather") {
550                         setType(newtype);
551                         numbered(0, false);
552                 } else {
553                         MathGridInset::addCol(1);
554                         // split it "nicely"
555                         pos_type pos = firstRelOp(cell(0));
556                         cell(1) = cell(0);
557                         cell(0).erase(pos, cell(0).size());
558                         cell(1).erase(0, pos);
559                         setType("align");
560                         mutate(newtype);
561                 }
562         }
563
564         else if (type_ == "eqnarray") {
565                 if (smaller(newtype, type_)) {
566                         // set correct (no)numbering
567                         bool allnonum = true;
568                         for (row_type row = 0; row < nrows(); ++row)
569                                 if (!nonum_[row])
570                                         allnonum = false;
571
572                         // set first non-empty label
573                         string label;
574                         for (row_type row = 0; row < nrows(); ++row) {
575                                 if (!label_[row].empty()) {
576                                         label = label_[row];
577                                         break;
578                                 }
579                         }
580
581                         glueall();
582                         nonum_[0] = allnonum;
583                         label_[0] = label;
584                         mutate(newtype);
585                 } else { // align & Co.
586                         for (row_type row = 0; row < nrows(); ++row) {
587                                 idx_type c = 3 * row + 1;
588                                 cell(c).append(cell(c + 1));
589                         }
590                         MathGridInset::delCol(2);
591                         setType("align");
592                         mutate(newtype);
593                 }
594         }
595
596         else if (type_ == "align") {
597                 if (smaller(newtype, type_)) {
598                         MathGridInset::addCol(1);
599                         setType("eqnarray");
600                         mutate(newtype);
601                 } else {
602                         setType(newtype);
603                 }
604         }
605
606         else if (type_ == "multline") {
607                 if (newtype == "gather" || newtype == "align" ||
608                     newtype == "xalignat" || newtype == "xxalignat" || newtype == "flalign")
609                         setType(newtype);
610                 else if (newtype == "eqnarray") {
611                         MathGridInset::addCol(1);
612                         MathGridInset::addCol(1);
613                         setType("eqnarray");
614                 } else {
615                         lyxerr << "mutation from '" << type_
616                                 << "' to '" << newtype << "' not implemented" << endl;
617                 }
618         }
619
620         else if (type_ == "gather") {
621                 if (newtype == "multline") {
622                         setType("multline");
623                 } else {
624                         lyxerr << "mutation from '" << type_
625                                 << "' to '" << newtype << "' not implemented" << endl;
626                 }
627         }
628
629         else {
630                 lyxerr << "mutation from '" << type_
631                                          << "' to '" << newtype << "' not implemented" << endl;
632         }
633 }
634
635
636 string MathHullInset::eolString(row_type row, bool fragile) const
637 {
638         string res;
639         if (numberedType()) {
640                 if (!label_[row].empty() && !nonum_[row])
641                         res += "\\label{" + label_[row] + '}';
642                 if (nonum_[row] && (type_ != "multline"))
643                         res += "\\nonumber ";
644         }
645         return res + MathGridInset::eolString(row, fragile);
646 }
647
648
649 void MathHullInset::write(WriteStream & os) const
650 {
651         header_write(os);
652         MathGridInset::write(os);
653         footer_write(os);
654 }
655
656
657 void MathHullInset::normalize(NormalStream & os) const
658 {
659         os << "[formula " << type_ << ' ';
660         MathGridInset::normalize(os);
661         os << "] ";
662 }
663
664
665 void MathHullInset::mathmlize(MathMLStream & os) const
666 {
667         MathGridInset::mathmlize(os);
668 }
669
670
671 void MathHullInset::infoize(std::ostream & os) const
672 {
673         os << "Type: " << type_;
674 }
675
676
677 void MathHullInset::check() const
678 {
679         BOOST_ASSERT(nonum_.size() == nrows());
680         BOOST_ASSERT(label_.size() == nrows());
681 }
682
683
684 void MathHullInset::doExtern
685         (FuncRequest const & func, idx_type & idx, pos_type & pos)
686 {
687         string lang;
688         string extra;
689         istringstream iss(func.argument.c_str());
690         iss >> lang >> extra;
691         if (extra.empty())
692                 extra = "noextra";
693
694 #ifdef WITH_WARNINGS
695 #warning temporarily disabled
696         //if (selection()) {
697         //      MathArray ar;
698         //      selGet(ar);
699         //      lyxerr << "use selection: " << ar << endl;
700         //      insert(pipeThroughExtern(lang, extra, ar));
701         //      return;
702         //}
703 #endif
704
705         MathArray eq;
706         eq.push_back(MathAtom(new MathCharInset('=')));
707
708         // go to first item in line
709         idx -= idx % ncols();
710         pos = 0;
711
712         if (getType() == "simple") {
713                 size_type pos = cell(idx).find_last(eq);
714                 MathArray ar;
715                 if (mathcursor && mathcursor->selection()) {
716                         asArray(mathcursor->grabAndEraseSelection(), ar);
717                 } else if (pos == cell(idx).size()) {
718                         ar = cell(idx);
719                         lyxerr << "use whole cell: " << ar << endl;
720                 } else {
721                         ar = MathArray(cell(idx).begin() + pos + 1, cell(idx).end());
722                         lyxerr << "use partial cell form pos: " << pos << endl;
723                 }
724                 cell(idx).append(eq);
725                 cell(idx).append(pipeThroughExtern(lang, extra, ar));
726                 pos = cell(idx).size();
727                 return;
728         }
729
730         if (getType() == "equation") {
731                 lyxerr << "use equation inset" << endl;
732                 mutate("eqnarray");
733                 MathArray & ar = cell(idx);
734                 lyxerr << "use cell: " << ar << endl;
735                 cell(idx + 1) = eq;
736                 cell(idx + 2) = pipeThroughExtern(lang, extra, ar);
737                 // move to end of line
738                 idx += 2;
739                 pos = cell(idx).size();
740                 return;
741         }
742
743         {
744                 lyxerr << "use eqnarray" << endl;
745                 idx -= idx % ncols();
746                 idx += 2;
747                 pos = 0;
748                 MathArray ar = cell(idx);
749                 lyxerr << "use cell: " << ar << endl;
750 #ifdef WITH_WARNINGS
751 #warning temporarily disabled
752 #endif
753                 addRow(row(idx));
754                 cell(idx + 2) = eq;
755                 cell(idx + 3) = pipeThroughExtern(lang, extra, ar);
756                 idx += 3;
757                 pos = cell(idx).size();
758         }
759 }
760
761
762 dispatch_result MathHullInset::dispatch
763         (FuncRequest const & cmd, idx_type & idx, pos_type & pos)
764 {
765         switch (cmd.action) {
766
767                 case LFUN_BREAKLINE:
768                         if (type_ == "simple" || type_ == "equation") {
769                                 mutate("eqnarray");
770                                 idx = 1;
771                                 pos = 0;
772                                 return DISPATCHED_POP;
773                         }
774                         return MathGridInset::dispatch(cmd, idx, pos);
775
776                 case LFUN_MATH_NUMBER:
777                         //lyxerr << "toggling all numbers" << endl;
778                         if (display()) {
779                                 //recordUndo(bv, Undo::INSERT);
780                                 bool old = numberedType();
781                                 if (type_ == "multline")
782                                         numbered(nrows() - 1, !old);
783                                 else
784                                         for (row_type row = 0; row < nrows(); ++row)
785                                                 numbered(row, !old);
786                                 //bv->owner()->message(old ? _("No number") : _("Number"));
787                         }
788                         return DISPATCHED;
789
790                 case LFUN_MATH_NONUMBER:
791                         if (display()) {
792                                 row_type r = (type_ == "multline") ? nrows() - 1 : row(idx);
793                                 //recordUndo(bv, Undo::INSERT);
794                                 bool old = numbered(r);
795                                 //bv->owner()->message(old ? _("No number") : _("Number"));
796                                 numbered(r, !old);
797                         }
798                         return DISPATCHED;
799
800                 case LFUN_INSERT_LABEL: {
801                         row_type r = (type_ == "multline") ? nrows() - 1 : row(idx);
802                         string old_label = label(r);
803                         string new_label = cmd.argument;
804
805                         if (new_label.empty()) {
806                                 string const default_label =
807                                         (lyxrc.label_init_length >= 0) ? "eq:" : "";
808                                 pair<bool, string> const res = old_label.empty()
809                                         ? Alert::askForText(_("Enter new label to insert:"), default_label)
810                                         : Alert::askForText(_("Enter label:"), old_label);
811                                 if (!res.first)
812                                         return UNDISPATCHED;
813                                 new_label = trim(res.second);
814                         }
815
816                         //if (new_label == old_label)
817                         //      break;  // Nothing to do
818
819                         if (!new_label.empty())
820                                 numbered(r, true);
821                         label(r, new_label);
822                         return DISPATCHED;
823                 }
824
825                 case LFUN_MATH_EXTERN:
826                         doExtern(cmd, idx, pos);
827                         return DISPATCHED_POP;
828
829                 case LFUN_MATH_MUTATE: {
830                         row_type r = row(idx);
831                         col_type c = col(idx);
832                         mutate(cmd.argument);
833                         idx = r * ncols() + c;
834                         if (idx >= nargs())
835                                 idx = nargs() - 1;
836                         if (pos > cell(idx).size())
837                                 pos = cell(idx).size();
838                         return DISPATCHED_POP;
839                 }
840
841                 case LFUN_MATH_DISPLAY: {
842                         mutate(type_ == "simple" ? "equation" : "simple");
843                         idx = 0;
844                         pos = cell(idx).size();
845                         return DISPATCHED_POP;
846                 }
847
848                 default:
849                         return MathGridInset::dispatch(cmd, idx, pos);
850         }
851 }
852
853
854 string MathHullInset::fileInsetLabel() const
855 {
856         return "Formula";
857 }