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