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