]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathHull.cpp
cleanup error messages
[lyx.git] / src / mathed / InsetMathHull.cpp
1 /**
2  * \file InsetMathHull.cpp
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 "InsetMathHull.h"
14
15 #include "InsetMathChar.h"
16 #include "InsetMathColor.h"
17 #include "MathExtern.h"
18 #include "MathFactory.h"
19 #include "MathStream.h"
20 #include "MathSupport.h"
21
22 #include "Buffer.h"
23 #include "BufferParams.h"
24 #include "BufferView.h"
25 #include "CutAndPaste.h"
26 #include "Encoding.h"
27 #include "FuncRequest.h"
28 #include "FuncStatus.h"
29 #include "LaTeXFeatures.h"
30 #include "LyXRC.h"
31 #include "MacroTable.h"
32 #include "sgml.h"
33 #include "TextPainter.h"
34 #include "TocBackend.h"
35
36 #include "insets/InsetLabel.h"
37 #include "insets/InsetRef.h"
38 #include "insets/RenderPreview.h"
39
40 #include "graphics/PreviewImage.h"
41
42 #include "frontends/Painter.h"
43
44 #include "support/lassert.h"
45 #include "support/debug.h"
46 #include "support/gettext.h"
47 #include "support/lstrings.h"
48
49 #include <sstream>
50
51 using namespace std;
52 using namespace lyx::support;
53
54 namespace lyx {
55
56 using cap::grabAndEraseSelection;
57
58 namespace {
59
60         int getCols(HullType type)
61         {
62                 switch (type) {
63                         case hullEqnArray:
64                                 return 3;
65                         case hullAlign:
66                         case hullFlAlign:
67                         case hullAlignAt:
68                         case hullXAlignAt:
69                         case hullXXAlignAt:
70                                 return 2;
71                         default:
72                                 return 1;
73                 }
74         }
75
76
77         // returns position of first relation operator in the array
78         // used for "intelligent splitting"
79         size_t firstRelOp(MathData const & ar)
80         {
81                 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
82                         if ((*it)->isRelOp())
83                                 return it - ar.begin();
84                 return ar.size();
85         }
86
87
88         char const * star(bool numbered)
89         {
90                 return numbered ? "" : "*";
91         }
92
93
94 } // end anon namespace
95
96
97 HullType hullType(docstring const & s)
98 {
99         if (s == "none")      return hullNone;
100         if (s == "simple")    return hullSimple;
101         if (s == "equation")  return hullEquation;
102         if (s == "eqnarray")  return hullEqnArray;
103         if (s == "align")     return hullAlign;
104         if (s == "alignat")   return hullAlignAt;
105         if (s == "xalignat")  return hullXAlignAt;
106         if (s == "xxalignat") return hullXXAlignAt;
107         if (s == "multline")  return hullMultline;
108         if (s == "gather")    return hullGather;
109         if (s == "flalign")   return hullFlAlign;
110         if (s == "regexp")    return hullRegexp;
111         lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
112         return HullType(-1);
113 }
114
115
116 docstring hullName(HullType type)
117 {
118         switch (type) {
119                 case hullNone:       return from_ascii("none");
120                 case hullSimple:     return from_ascii("simple");
121                 case hullEquation:   return from_ascii("equation");
122                 case hullEqnArray:   return from_ascii("eqnarray");
123                 case hullAlign:      return from_ascii("align");
124                 case hullAlignAt:    return from_ascii("alignat");
125                 case hullXAlignAt:   return from_ascii("xalignat");
126                 case hullXXAlignAt:  return from_ascii("xxalignat");
127                 case hullMultline:   return from_ascii("multline");
128                 case hullGather:     return from_ascii("gather");
129                 case hullFlAlign:    return from_ascii("flalign");
130                 case hullRegexp:     return from_ascii("regexp");
131                 default:
132                         lyxerr << "unknown hull type '" << type << "'" << endl;
133                         return from_ascii("none");
134         }
135 }
136
137 static InsetLabel * dummy_pointer = 0;
138
139 InsetMathHull::InsetMathHull(Buffer * buf)
140         : InsetMathGrid(buf, 1, 1), type_(hullNone), nonum_(1, false),
141           label_(1, dummy_pointer), preview_(new RenderPreview(this))
142 {
143         //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
144         //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
145         //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
146         //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
147         buffer_ = buf;
148         initMath();
149         setDefaults();
150 }
151
152
153 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
154         : InsetMathGrid(buf, getCols(type), 1), type_(type), nonum_(1, false),
155           label_(1, dummy_pointer), preview_(new RenderPreview(this))
156 {
157         buffer_ = buf;
158         initMath();
159         setDefaults();
160 }
161
162
163 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
164 {
165         operator=(other);
166 }
167
168
169 InsetMathHull::~InsetMathHull()
170 {
171         for (size_t i = 0; i < label_.size(); ++i)
172                 delete label_[i];
173 }
174
175
176 Inset * InsetMathHull::clone() const
177 {
178         return new InsetMathHull(*this);
179 }
180
181
182 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
183 {
184         if (this == &other)
185                 return *this;
186         InsetMathGrid::operator=(other);
187         type_  = other.type_;
188         nonum_ = other.nonum_;
189         buffer_ = other.buffer_;
190         for (size_t i = 0; i < label_.size(); ++i)
191                 delete label_[i];
192         label_ = other.label_;
193         for (size_t i = 0; i != label_.size(); ++i) {
194                 if (label_[i])
195                         label_[i] = new InsetLabel(*label_[i]);
196         }
197         preview_.reset(new RenderPreview(*other.preview_, this));
198
199         return *this;
200 }
201
202
203 void InsetMathHull::setBuffer(Buffer & buffer)
204 {
205         InsetMathGrid::setBuffer(buffer);
206
207         for (size_t i = 0; i != label_.size(); ++i) {
208                 if (label_[i])
209                         label_[i]->setBuffer(buffer);
210         }
211 }
212
213
214 void InsetMathHull::updateLabels(ParIterator const & it, bool out)
215 {
216         if (!buffer_) {
217                 //FIXME: buffer_ should be set at creation for this inset! Problem is
218                 // This inset is created at too many places (see Parser::parse1() in
219                 // MathParser.cpp).
220                 return;
221         }
222         for (size_t i = 0; i != label_.size(); ++i) {
223                 if (label_[i])
224                         label_[i]->updateLabels(it, out);
225         }
226 }
227
228
229 void InsetMathHull::addToToc(DocIterator const & pit)
230 {
231         if (!buffer_) {
232                 //FIXME: buffer_ should be set at creation for this inset! Problem is
233                 // This inset is created at too many places (see Parser::parse1() in
234                 // MathParser.cpp).
235                 return;
236         }
237
238         Toc & toc = buffer().tocBackend().toc("equation");
239
240         for (row_type row = 0; row != nrows(); ++row) {
241                 if (nonum_[row])
242                         continue;
243                 if (label_[row])
244                         label_[row]->addToToc(pit);
245                 toc.push_back(TocItem(pit, 0, nicelabel(row)));
246         }
247 }
248
249
250 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
251 {
252         if (use_preview_) {
253                 edit(cur, true);
254                 return this;
255         }
256         return InsetMathNest::editXY(cur, x, y);
257 }
258
259
260 InsetMath::mode_type InsetMathHull::currentMode() const
261 {
262         if (type_ == hullNone)
263                 return UNDECIDED_MODE;
264         // definitely math mode ...
265         return MATH_MODE;
266 }
267
268
269 bool InsetMathHull::idxFirst(Cursor & cur) const
270 {
271         cur.idx() = 0;
272         cur.pos() = 0;
273         return true;
274 }
275
276
277 bool InsetMathHull::idxLast(Cursor & cur) const
278 {
279         cur.idx() = nargs() - 1;
280         cur.pos() = cur.lastpos();
281         return true;
282 }
283
284
285 char InsetMathHull::defaultColAlign(col_type col)
286 {
287         if (type_ == hullEqnArray)
288                 return "rcl"[col];
289         if (type_ == hullGather)
290                 return 'c';
291         if (type_ >= hullAlign)
292                 return "rl"[col & 1];
293         return 'c';
294 }
295
296
297 int InsetMathHull::defaultColSpace(col_type col)
298 {
299         if (type_ == hullAlign || type_ == hullAlignAt)
300                 return 0;
301         if (type_ == hullXAlignAt)
302                 return (col & 1) ? 20 : 0;
303         if (type_ == hullXXAlignAt || type_ == hullFlAlign)
304                 return (col & 1) ? 40 : 0;
305         return 0;
306 }
307
308
309 docstring InsetMathHull::standardFont() const
310 {
311         return from_ascii(type_ == hullNone ? "lyxnochange" : "mathnormal");
312 }
313
314
315 bool InsetMathHull::previewState(BufferView * bv) const
316 {
317         if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
318                 graphics::PreviewImage const * pimage =
319                         preview_->getPreviewImage(bv->buffer());
320                 return pimage && pimage->image();
321         }
322         return false;
323 }
324
325
326 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
327 {
328         if (previewState(mi.base.bv)) {
329                 preview_->metrics(mi, dim);
330                 // insert a one pixel gap in front of the formula
331                 dim.wid += 1;
332                 if (display())
333                         dim.des += displayMargin();
334                 // Cache the inset dimension.
335                 setDimCache(mi, dim);
336                 return;
337         }
338
339         FontSetChanger dummy1(mi.base, standardFont());
340         StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
341
342         // let the cells adjust themselves
343         InsetMathGrid::metrics(mi, dim);
344
345         if (display()) {
346                 dim.asc += displayMargin();
347                 dim.des += displayMargin();
348         }
349
350         if (numberedType()) {
351                 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
352                 int l = 0;
353                 for (row_type row = 0; row < nrows(); ++row)
354                         l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
355
356                 if (l)
357                         dim.wid += 30 + l;
358         }
359
360         // make it at least as high as the current font
361         int asc = 0;
362         int des = 0;
363         math_font_max_dim(mi.base.font, asc, des);
364         dim.asc = max(dim.asc, asc);
365         dim.des = max(dim.des, des);
366         // Cache the inset dimension.
367         // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
368         setDimCache(mi, dim);
369 }
370
371
372 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
373 {
374         Dimension const dim = dimension(*pi.base.bv);
375         pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
376                 dim.asc + dim.des - 1, pi.backgroundColor(this));
377 }
378
379
380 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
381 {
382         use_preview_ = previewState(pi.base.bv);
383
384         if (use_preview_) {
385                 // one pixel gap in front
386                 preview_->draw(pi, x + 1, y);
387                 setPosCache(pi, x, y);
388                 return;
389         }
390
391         FontSetChanger dummy1(pi.base, standardFont());
392         StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
393         InsetMathGrid::draw(pi, x + 1, y);
394
395         if (numberedType()) {
396                 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
397                 for (row_type row = 0; row < nrows(); ++row) {
398                         int const yy = y + rowinfo_[row].offset_;
399                         FontSetChanger dummy(pi.base, from_ascii("mathrm"));
400                         docstring const nl = nicelabel(row);
401                         pi.draw(xx, yy, nl);
402                 }
403         }
404         setPosCache(pi, x, y);
405 }
406
407
408 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
409 {
410         if (display()) {
411                 InsetMathGrid::metricsT(mi, dim);
412         } else {
413                 odocstringstream os;
414                 WriteStream wi(os, false, true, WriteStream::wsDefault);
415                 write(wi);
416                 dim.wid = os.str().size();
417                 dim.asc = 1;
418                 dim.des = 0;
419         }
420 }
421
422
423 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
424 {
425         if (display()) {
426                 InsetMathGrid::drawT(pain, x, y);
427         } else {
428                 odocstringstream os;
429                 WriteStream wi(os, false, true, WriteStream::wsDefault);
430                 write(wi);
431                 pain.draw(x, y, os.str().c_str());
432         }
433 }
434
435
436 static docstring latexString(InsetMathHull const & inset)
437 {
438         odocstringstream ls;
439         // This has to be static, because a preview snippet or a math
440         // macro containing math in text mode (such as $\text{$\phi$}$ or
441         // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
442         // first time as a whole, and the second time only the inner math.
443         // In this last case inset.buffer() would be invalid.
444         static Encoding const * encoding = 0;
445         if (inset.isBufferValid())
446                 encoding = &(inset.buffer().params().encoding());
447         WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
448         inset.write(wi);
449         return ls.str();
450 }
451
452
453 void InsetMathHull::initUnicodeMath() const
454 {
455         // Trigger classification of the unicode symbols in this inset
456         docstring const dummy = latexString(*this);
457 }
458
459
460 void InsetMathHull::addPreview(DocIterator const & inset_pos,
461         graphics::PreviewLoader & /*ploader*/) const
462 {
463         if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
464                 preparePreview(inset_pos);
465         }
466 }
467
468
469 void InsetMathHull::preparePreview(DocIterator const & pos) const  
470 {
471         Buffer const * buffer = pos.buffer();  
472
473         // collect macros at this position  
474         MacroNameSet macros;  
475         buffer->listMacroNames(macros);  
476         MacroNameSet::iterator it = macros.begin();  
477         MacroNameSet::iterator end = macros.end();  
478         odocstringstream macro_preamble;  
479         for (; it != end; ++it) {  
480                 MacroData const * data = buffer->getMacro(*it, pos, true);  
481                 if (data) {  
482                         data->write(macro_preamble, true);  
483                         macro_preamble << endl;  
484                 }
485         }  
486
487         docstring const snippet = macro_preamble.str() + latexString(*this);  
488         LYXERR(Debug::MACROS, "Preview snippet: " << snippet);  
489         preview_->addPreview(snippet, *buffer);  
490 }
491
492
493 void InsetMathHull::reloadPreview(DocIterator const & pos) const
494 {
495         preparePreview(pos);
496         preview_->startLoading(*pos.buffer());
497 }
498
499
500 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
501 {
502         if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
503                 reloadPreview(old);
504                 cur.updateFlags(Update::Force);
505         }
506         return false;
507 }
508
509
510 docstring InsetMathHull::label(row_type row) const
511 {
512         LASSERT(row < nrows(), /**/);
513         if (InsetLabel * il = label_[row])
514                 return il->screenLabel();
515         return docstring();
516 }
517
518
519 void InsetMathHull::label(row_type row, docstring const & label)
520 {
521         //lyxerr << "setting label '" << label << "' for row " << row << endl;
522         if (label_[row]) {
523                 if (label.empty()) {
524                         delete label_[row];
525                         label_[row] = dummy_pointer;
526                         // We need an update of the Buffer reference cache.
527                         // This is achieved by updateLabels().
528                         if (buffer_)
529                                 buffer().updateLabels();
530                 } else {
531                         if (buffer_)
532                                 label_[row]->updateCommand(label);
533                         else
534                                 label_[row]->setParam("name", label);
535                 }
536                 return;
537         }
538         InsetCommandParams p(LABEL_CODE);
539         p["name"] = label;
540         label_[row] = new InsetLabel(buffer_, p);
541         if (buffer_)
542                 label_[row]->setBuffer(buffer());
543 }
544
545
546 void InsetMathHull::numbered(row_type row, bool num)
547 {
548         nonum_[row] = !num;
549         if (nonum_[row] && label_[row]) {
550                 delete label_[row];
551                 label_[row] = 0;
552                 if (!buffer_) {
553                         // The buffer is set at the end of readInset.
554                         // When parsing the inset, buffer_ is 0.
555                         return;
556                 }
557                 // We need an update of the Buffer reference cache.
558                 // This is achieved by updateLabels().
559                 buffer().updateLabels();
560         }
561 }
562
563
564 bool InsetMathHull::numbered(row_type row) const
565 {
566         return !nonum_[row];
567 }
568
569
570 bool InsetMathHull::ams() const
571 {
572         return type_ == hullAlign
573                 || type_ == hullFlAlign
574                 || type_ == hullMultline
575                 || type_ == hullGather
576                 || type_ == hullAlignAt
577                 || type_ == hullXAlignAt
578                 || type_ == hullXXAlignAt;
579 }
580
581
582 Inset::DisplayType InsetMathHull::display() const
583 {
584         if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
585                 return Inline;
586         return AlignCenter;
587 }
588
589 bool InsetMathHull::numberedType() const
590 {
591         if (type_ == hullNone)
592                 return false;
593         if (type_ == hullSimple)
594                 return false;
595         if (type_ == hullXXAlignAt)
596                 return false;
597         if (type_ == hullRegexp)
598                 return false;
599         for (row_type row = 0; row < nrows(); ++row)
600                 if (!nonum_[row])
601                         return true;
602         return false;
603 }
604
605
606 void InsetMathHull::validate(LaTeXFeatures & features) const
607 {
608         if (ams())
609                 features.require("amsmath");
610
611         // Validation is necessary only if not using AMS math.
612         // To be safe, we will always run mathedvalidate.
613         //if (features.amsstyle)
614         //  return;
615
616         //features.binom      = true;
617
618         InsetMathGrid::validate(features);
619 }
620
621
622 void InsetMathHull::header_write(WriteStream & os) const
623 {
624         bool n = numberedType();
625
626         switch(type_) {
627         case hullNone:
628                 break;
629
630         case hullSimple:
631                 os << '$';
632                 if (cell(0).empty())
633                         os << ' ';
634                 break;
635
636         case hullEquation:
637                 if (n)
638                         os << "\\begin{equation" << star(n) << "}\n";
639                 else
640                         os << "\\[\n";
641                 break;
642
643         case hullEqnArray:
644         case hullAlign:
645         case hullFlAlign:
646         case hullGather:
647         case hullMultline:
648                 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
649                 break;
650
651         case hullAlignAt:
652         case hullXAlignAt:
653                 os << "\\begin{" << hullName(type_) << star(n) << '}'
654                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
655                 break;
656
657         case hullXXAlignAt:
658                 os << "\\begin{" << hullName(type_) << '}'
659                   << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
660                 break;
661
662         case hullRegexp:
663                 os << "\\regexp{";
664                 break;
665
666         default:
667                 os << "\\begin{unknown" << star(n) << '}';
668                 break;
669         }
670 }
671
672
673 void InsetMathHull::footer_write(WriteStream & os) const
674 {
675         bool n = numberedType();
676
677         switch(type_) {
678         case hullNone:
679                 os << "\n";
680                 break;
681
682         case hullSimple:
683                 os << '$';
684                 break;
685
686         case hullEquation:
687                 if (n)
688                         os << "\\end{equation" << star(n) << "}\n";
689                 else
690                         os << "\\]\n";
691                 break;
692
693         case hullEqnArray:
694         case hullAlign:
695         case hullFlAlign:
696         case hullAlignAt:
697         case hullXAlignAt:
698         case hullGather:
699         case hullMultline:
700                 os << "\\end{" << hullName(type_) << star(n) << "}\n";
701                 break;
702
703         case hullXXAlignAt:
704                 os << "\\end{" << hullName(type_) << "}\n";
705                 break;
706
707         case hullRegexp:
708                 os << "}";
709                 break;
710
711         default:
712                 os << "\\end{unknown" << star(n) << '}';
713                 break;
714         }
715 }
716
717
718 bool InsetMathHull::rowChangeOK() const
719 {
720         return
721                 type_ == hullEqnArray || type_ == hullAlign ||
722                 type_ == hullFlAlign || type_ == hullAlignAt ||
723                 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
724                 type_ == hullGather || type_ == hullMultline;
725 }
726
727
728 bool InsetMathHull::colChangeOK() const
729 {
730         return
731                 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
732                 type_ == hullXAlignAt || type_ == hullXXAlignAt;
733 }
734
735
736 void InsetMathHull::addRow(row_type row)
737 {
738         if (!rowChangeOK())
739                 return;
740
741         bool numbered = numberedType();
742         docstring lab;
743         if (type_ == hullMultline) {
744                 if (row + 1 == nrows())  {
745                         nonum_[row] = true;
746                         lab = label(row);
747                 } else
748                         numbered = false;
749         }
750
751         nonum_.insert(nonum_.begin() + row + 1, !numbered);
752         label_.insert(label_.begin() + row + 1, dummy_pointer);
753         if (!lab.empty())
754                 label(row + 1, lab);
755         InsetMathGrid::addRow(row);
756 }
757
758
759 void InsetMathHull::swapRow(row_type row)
760 {
761         if (nrows() <= 1)
762                 return;
763         if (row + 1 == nrows())
764                 --row;
765         // gcc implements the standard std::vector<bool> which is *not* a container:
766         //   http://www.gotw.ca/publications/N1185.pdf
767         // As a results, it doesn't like this:
768         //      swap(nonum_[row], nonum_[row + 1]);
769         // so we do it manually:
770         bool const b = nonum_[row];
771         nonum_[row] = nonum_[row + 1];
772         nonum_[row + 1] = b;
773         swap(label_[row], label_[row + 1]);
774         InsetMathGrid::swapRow(row);
775 }
776
777
778 void InsetMathHull::delRow(row_type row)
779 {
780         if (nrows() <= 1 || !rowChangeOK())
781                 return;
782         if (row + 1 == nrows() && type_ == hullMultline) {
783                 bool const b = nonum_[row - 1];
784                 nonum_[row - 1] = nonum_[row];
785                 nonum_[row] = b;
786                 swap(label_[row - 1], label_[row]);
787                 InsetMathGrid::delRow(row);
788                 return;
789         }
790         InsetMathGrid::delRow(row);
791         // The last dummy row has no number info nor a label.
792         // Test nrows() + 1 because we have already erased the row.
793         if (row == nrows() + 1)
794                 row--;
795         nonum_.erase(nonum_.begin() + row);
796         delete label_[row];
797         label_.erase(label_.begin() + row);
798 }
799
800
801 void InsetMathHull::addCol(col_type col)
802 {
803         if (!colChangeOK())
804                 return;
805         InsetMathGrid::addCol(col);
806 }
807
808
809 void InsetMathHull::delCol(col_type col)
810 {
811         if (ncols() <= 1 || !colChangeOK())
812                 return;
813         InsetMathGrid::delCol(col);
814 }
815
816
817 docstring InsetMathHull::nicelabel(row_type row) const
818 {
819         if (nonum_[row])
820                 return docstring();
821         if (!label_[row])
822                 return from_ascii("(#)");
823         return '(' + label_[row]->screenLabel() + from_ascii(", #)");
824 }
825
826
827 void InsetMathHull::glueall()
828 {
829         MathData ar;
830         for (idx_type i = 0; i < nargs(); ++i)
831                 ar.append(cell(i));
832         *this = InsetMathHull(buffer_, hullSimple);
833         cell(0) = ar;
834         setDefaults();
835 }
836
837
838 void InsetMathHull::splitTo2Cols()
839 {
840         LASSERT(ncols() == 1, /**/);
841         InsetMathGrid::addCol(1);
842         for (row_type row = 0; row < nrows(); ++row) {
843                 idx_type const i = 2 * row;
844                 pos_type pos = firstRelOp(cell(i));
845                 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
846                 cell(i).erase(pos, cell(i).size());
847         }
848 }
849
850
851 void InsetMathHull::splitTo3Cols()
852 {
853         LASSERT(ncols() < 3, /**/);
854         if (ncols() < 2)
855                 splitTo2Cols();
856         InsetMathGrid::addCol(2);
857         for (row_type row = 0; row < nrows(); ++row) {
858                 idx_type const i = 3 * row + 1;
859                 if (cell(i).size()) {
860                         cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
861                         cell(i).erase(1, cell(i).size());
862                 }
863         }
864 }
865
866
867 void InsetMathHull::changeCols(col_type cols)
868 {
869         if (ncols() == cols)
870                 return;
871         else if (ncols() < cols) {
872                 // split columns
873                 if (cols < 3)
874                         splitTo2Cols();
875                 else {
876                         splitTo3Cols();
877                         while (ncols() < cols)
878                                 InsetMathGrid::addCol(ncols());
879                 }
880                 return;
881         }
882
883         // combine columns
884         for (row_type row = 0; row < nrows(); ++row) {
885                 idx_type const i = row * ncols();
886                 for (col_type col = cols; col < ncols(); ++col) {
887                         cell(i + cols - 1).append(cell(i + col));
888                 }
889         }
890         // delete columns
891         while (ncols() > cols) {
892                 InsetMathGrid::delCol(ncols() - 1);
893         }
894 }
895
896
897 HullType InsetMathHull::getType() const
898 {
899         return type_;
900 }
901
902
903 void InsetMathHull::setType(HullType type)
904 {
905         type_ = type;
906         setDefaults();
907 }
908
909
910 void InsetMathHull::mutate(HullType newtype)
911 {
912         //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
913
914         // we try to move along the chain
915         // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
916         //                                     ^                                     |
917         //                                     +-------------------------------------+
918         // we use eqnarray as intermediate type for mutations that are not
919         // directly supported because it handles labels and numbering for
920         // "down mutation".
921
922         if (newtype == type_) {
923                 // done
924         }
925
926         else if (newtype < hullNone) {
927                 // unknown type
928                 dump();
929         }
930
931         else if (type_ == hullNone) {
932                 setType(hullSimple);
933                 numbered(0, false);
934                 mutate(newtype);
935         }
936
937         else if (type_ == hullSimple) {
938                 if (newtype == hullNone) {
939                         setType(hullNone);
940                         numbered(0, false);
941                 } else {
942                         setType(hullEquation);
943                         numbered(0, false);
944                         mutate(newtype);
945                 }
946         }
947
948         else if (type_ == hullEquation) {
949                 if (newtype < type_) {
950                         setType(hullSimple);
951                         numbered(0, false);
952                         mutate(newtype);
953                 } else if (newtype == hullEqnArray) {
954                         // split it "nicely" on the first relop
955                         splitTo3Cols();
956                         setType(hullEqnArray);
957                 } else if (newtype == hullMultline || newtype == hullGather) {
958                         setType(newtype);
959                 } else {
960                         // split it "nicely"
961                         splitTo2Cols();
962                         setType(hullAlign);
963                         mutate(newtype);
964                 }
965         }
966
967         else if (type_ == hullEqnArray) {
968                 if (newtype < type_) {
969                         // set correct (no)numbering
970                         nonum_[0] = true;
971                         for (row_type row = 0; row < nrows(); ++row) {
972                                 if (!nonum_[row]) {
973                                         nonum_[0] = false;
974                                         break;
975                                 }
976                         }
977
978                         // set first non-empty label
979                         for (row_type row = 0; row < nrows(); ++row) {
980                                 if (label_[row]) {
981                                         label_[0] = label_[row];
982                                         break;
983                                 }
984                         }
985
986                         glueall();
987                         mutate(newtype);
988                 } else { // align & Co.
989                         changeCols(2);
990                         setType(hullAlign);
991                         mutate(newtype);
992                 }
993         }
994
995         else if (type_ ==  hullAlign || type_ == hullAlignAt ||
996                  type_ == hullXAlignAt || type_ == hullFlAlign) {
997                 if (newtype < hullAlign) {
998                         changeCols(3);
999                         setType(hullEqnArray);
1000                         mutate(newtype);
1001                 } else if (newtype == hullGather || newtype == hullMultline) {
1002                         changeCols(1);
1003                         setType(newtype);
1004                 } else if (newtype ==   hullXXAlignAt) {
1005                         for (row_type row = 0; row < nrows(); ++row)
1006                                 numbered(row, false);
1007                         setType(newtype);
1008                 } else {
1009                         setType(newtype);
1010                 }
1011         }
1012
1013         else if (type_ == hullXXAlignAt) {
1014                 for (row_type row = 0; row < nrows(); ++row)
1015                         numbered(row, false);
1016                 if (newtype < hullAlign) {
1017                         changeCols(3);
1018                         setType(hullEqnArray);
1019                         mutate(newtype);
1020                 } else if (newtype == hullGather || newtype == hullMultline) {
1021                         changeCols(1);
1022                         setType(newtype);
1023                 } else {
1024                         setType(newtype);
1025                 }
1026         }
1027
1028         else if (type_ == hullMultline || type_ == hullGather) {
1029                 if (newtype == hullGather || newtype == hullMultline)
1030                         setType(newtype);
1031                 else if (newtype == hullAlign || newtype == hullFlAlign  ||
1032                          newtype == hullAlignAt || newtype == hullXAlignAt) {
1033                         splitTo2Cols();
1034                         setType(newtype);
1035                 } else if (newtype ==   hullXXAlignAt) {
1036                         splitTo2Cols();
1037                         for (row_type row = 0; row < nrows(); ++row)
1038                                 numbered(row, false);
1039                         setType(newtype);
1040                 } else {
1041                         splitTo3Cols();
1042                         setType(hullEqnArray);
1043                         mutate(newtype);
1044                 }
1045         }
1046
1047         else {
1048                 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1049                        << "' to '" << to_utf8(hullName(newtype))
1050                        << "' not implemented" << endl;
1051         }
1052 }
1053
1054
1055 docstring InsetMathHull::eolString(row_type row, bool fragile) const
1056 {
1057         docstring res;
1058         if (numberedType()) {
1059                 if (label_[row] && !nonum_[row])
1060                         res += "\\label{" + label_[row]->getParam("name") + '}';
1061                 if (nonum_[row] && (type_ != hullMultline))
1062                         res += "\\nonumber ";
1063         }
1064         return res + InsetMathGrid::eolString(row, fragile);
1065 }
1066
1067
1068 void InsetMathHull::write(WriteStream & os) const
1069 {
1070         ModeSpecifier specifier(os, MATH_MODE);
1071         header_write(os);
1072         InsetMathGrid::write(os);
1073         footer_write(os);
1074 }
1075
1076
1077 void InsetMathHull::normalize(NormalStream & os) const
1078 {
1079         os << "[formula " << hullName(type_) << ' ';
1080         InsetMathGrid::normalize(os);
1081         os << "] ";
1082 }
1083
1084
1085 void InsetMathHull::mathmlize(MathStream & os) const
1086 {
1087         InsetMathGrid::mathmlize(os);
1088 }
1089
1090
1091 void InsetMathHull::infoize(odocstream & os) const
1092 {
1093         os << "Type: " << hullName(type_);
1094 }
1095
1096
1097 void InsetMathHull::check() const
1098 {
1099         LASSERT(nonum_.size() == nrows(), /**/);
1100         LASSERT(label_.size() == nrows(), /**/);
1101 }
1102
1103
1104 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1105 {
1106         docstring dlang;
1107         docstring extra;
1108         idocstringstream iss(func.argument());
1109         iss >> dlang >> extra;
1110         if (extra.empty())
1111                 extra = from_ascii("noextra");
1112         string const lang = to_ascii(dlang);
1113
1114         // FIXME: temporarily disabled
1115         //if (cur.selection()) {
1116         //      MathData ar;
1117         //      selGet(cur.ar);
1118         //      lyxerr << "use selection: " << ar << endl;
1119         //      insert(pipeThroughExtern(lang, extra, ar));
1120         //      return;
1121         //}
1122
1123         MathData eq;
1124         eq.push_back(MathAtom(new InsetMathChar('=')));
1125
1126         // go to first item in line
1127         cur.idx() -= cur.idx() % ncols();
1128         cur.pos() = 0;
1129
1130         if (getType() == hullSimple) {
1131                 size_type pos = cur.cell().find_last(eq);
1132                 MathData ar;
1133                 if (cur.inMathed() && cur.selection()) {
1134                         asArray(grabAndEraseSelection(cur), ar);
1135                 } else if (pos == cur.cell().size()) {
1136                         ar = cur.cell();
1137                         lyxerr << "use whole cell: " << ar << endl;
1138                 } else {
1139                         ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1140                         lyxerr << "use partial cell form pos: " << pos << endl;
1141                 }
1142                 cur.cell().append(eq);
1143                 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1144                 cur.pos() = cur.lastpos();
1145                 return;
1146         }
1147
1148         if (getType() == hullEquation) {
1149                 lyxerr << "use equation inset" << endl;
1150                 mutate(hullEqnArray);
1151                 MathData & ar = cur.cell();
1152                 lyxerr << "use cell: " << ar << endl;
1153                 ++cur.idx();
1154                 cur.cell() = eq;
1155                 ++cur.idx();
1156                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1157                 // move to end of line
1158                 cur.pos() = cur.lastpos();
1159                 return;
1160         }
1161
1162         {
1163                 lyxerr << "use eqnarray" << endl;
1164                 cur.idx() += 2 - cur.idx() % ncols();
1165                 cur.pos() = 0;
1166                 MathData ar = cur.cell();
1167                 lyxerr << "use cell: " << ar << endl;
1168                 // FIXME: temporarily disabled
1169                 addRow(cur.row());
1170                 ++cur.idx();
1171                 ++cur.idx();
1172                 cur.cell() = eq;
1173                 ++cur.idx();
1174                 cur.cell() = pipeThroughExtern(lang, extra, ar);
1175                 cur.pos() = cur.lastpos();
1176         }
1177 }
1178
1179
1180 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1181 {
1182         //lyxerr << "action: " << cmd.action << endl;
1183         switch (cmd.action) {
1184
1185         case LFUN_FINISHED_BACKWARD:
1186         case LFUN_FINISHED_FORWARD:
1187         case LFUN_FINISHED_RIGHT:
1188         case LFUN_FINISHED_LEFT:
1189                 //lyxerr << "action: " << cmd.action << endl;
1190                 InsetMathGrid::doDispatch(cur, cmd);
1191                 cur.undispatched();
1192                 break;
1193
1194         case LFUN_BREAK_PARAGRAPH:
1195                 // just swallow this
1196                 break;
1197
1198         case LFUN_NEWLINE_INSERT:
1199                 // some magic for the common case
1200                 if (type_ == hullSimple || type_ == hullEquation) {
1201                         cur.recordUndoInset();
1202                         bool const align =
1203                                 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1204                         mutate(align ? hullAlign : hullEqnArray);
1205                         cur.idx() = nrows() * ncols() - 1;
1206                         cur.pos() = cur.lastpos();
1207                 }
1208                 InsetMathGrid::doDispatch(cur, cmd);
1209                 break;
1210
1211         case LFUN_MATH_NUMBER_TOGGLE: {
1212                 //lyxerr << "toggling all numbers" << endl;
1213                 cur.recordUndoInset();
1214                 bool old = numberedType();
1215                 if (type_ == hullMultline)
1216                         numbered(nrows() - 1, !old);
1217                 else
1218                         for (row_type row = 0; row < nrows(); ++row)
1219                                 numbered(row, !old);
1220
1221                 cur.message(old ? _("No number") : _("Number"));
1222                 break;
1223         }
1224
1225         case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1226                 cur.recordUndoInset();
1227                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1228                 bool old = numbered(r);
1229                 cur.message(old ? _("No number") : _("Number"));
1230                 numbered(r, !old);
1231                 break;
1232         }
1233
1234         case LFUN_LABEL_INSERT: {
1235                 cur.recordUndoInset();
1236                 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1237                 docstring old_label = label(r);
1238                 docstring const default_label = from_ascii(
1239                         (lyxrc.label_init_length >= 0) ? "eq:" : "");
1240                 if (old_label.empty())
1241                         old_label = default_label;
1242
1243                 InsetCommandParams p(LABEL_CODE);
1244                 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1245                 string const data = InsetCommand::params2string("label", p);
1246
1247                 if (cmd.argument().empty())
1248                         cur.bv().showDialog("label", data);
1249                 else {
1250                         FuncRequest fr(LFUN_INSET_INSERT, data);
1251                         dispatch(cur, fr);
1252                 }
1253                 break;
1254         }
1255
1256         case LFUN_LABEL_COPY_AS_REF: {
1257                 row_type row;
1258                 if (cmd.argument().empty() && &cur.inset() == this)
1259                         // if there is no argument and we're inside math, we retrieve
1260                         // the row number from the cursor position.
1261                         row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1262                 else {
1263                         // if there is an argument, find the corresponding label, else
1264                         // check whether there is at least one label.
1265                         for (row = 0; row != nrows(); ++row)
1266                                 if (!nonum_[row] && label_[row]
1267                                           && (cmd.argument().empty() || label(row) == cmd.argument()))
1268                                         break;
1269                 }
1270
1271                 if (row == nrows())
1272                         break;
1273
1274                 InsetCommandParams p(REF_CODE, "ref");
1275                 p["reference"] = label(row);
1276                 cap::clearSelection();
1277                 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1278                 break;
1279         }
1280
1281         case LFUN_WORD_DELETE_FORWARD:
1282         case LFUN_CHAR_DELETE_FORWARD:
1283                 if (col(cur.idx()) + 1 == ncols()
1284                     && cur.pos() == cur.lastpos()
1285                     && !cur.selection()) {
1286                         if (!label(row(cur.idx())).empty()) {
1287                                 cur.recordUndoInset();
1288                                 label(row(cur.idx()), docstring());
1289                         } else if (numbered(row(cur.idx()))) {
1290                                 cur.recordUndoInset();
1291                                 numbered(row(cur.idx()), false);
1292                         } else {
1293                                 InsetMathGrid::doDispatch(cur, cmd);
1294                                 return;
1295                         }
1296                 } else {
1297                         InsetMathGrid::doDispatch(cur, cmd);
1298                         return;
1299                 }
1300                 break;
1301
1302         case LFUN_INSET_INSERT: {
1303                 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1304                 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1305                 string const name = cmd.getArg(0);
1306                 if (name == "label") {
1307                         InsetCommandParams p(LABEL_CODE);
1308                         InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1309                         docstring str = p["name"];
1310                         cur.recordUndoInset();
1311                         row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1312                         str = trim(str);
1313                         if (!str.empty())
1314                                 numbered(r, true);
1315                         docstring old = label(r);
1316                         if (str != old) {
1317                                 if (label_[r])
1318                                         // The label will take care of the reference update.
1319                                         label(r, str);
1320                                 else {
1321                                         label(r, str);
1322                                         // Newly created inset so initialize it.
1323                                         label_[r]->initView();
1324                                 }
1325                         }
1326                         break;
1327                 }
1328                 InsetMathGrid::doDispatch(cur, cmd);
1329                 return;
1330         }
1331
1332         case LFUN_MATH_EXTERN:
1333                 cur.recordUndoInset();
1334                 doExtern(cur, cmd);
1335                 break;
1336
1337         case LFUN_MATH_MUTATE: {
1338                 cur.recordUndoInset();
1339                 row_type row = cur.row();
1340                 col_type col = cur.col();
1341                 mutate(hullType(cmd.argument()));
1342                 cur.idx() = row * ncols() + col;
1343                 if (cur.idx() > cur.lastidx()) {
1344                         cur.idx() = cur.lastidx();
1345                         cur.pos() = cur.lastpos();
1346                 }
1347                 if (cur.pos() > cur.lastpos())
1348                         cur.pos() = cur.lastpos();
1349
1350                 // FIXME: find some more clever handling of the selection,
1351                 // i.e. preserve it.
1352                 cur.clearSelection();
1353                 //cur.dispatched(FINISHED);
1354                 break;
1355         }
1356
1357         case LFUN_MATH_DISPLAY: {
1358                 cur.recordUndoInset();
1359                 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1360                 cur.idx() = 0;
1361                 cur.pos() = cur.lastpos();
1362                 //cur.dispatched(FINISHED);
1363                 break;
1364         }
1365
1366         default:
1367                 InsetMathGrid::doDispatch(cur, cmd);
1368                 break;
1369         }
1370 }
1371
1372
1373 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1374                 FuncStatus & status) const
1375 {
1376         switch (cmd.action) {
1377         case LFUN_FINISHED_BACKWARD:
1378         case LFUN_FINISHED_FORWARD:
1379         case LFUN_FINISHED_RIGHT:
1380         case LFUN_FINISHED_LEFT:
1381         case LFUN_UP:
1382         case LFUN_DOWN:
1383         case LFUN_NEWLINE_INSERT:
1384         case LFUN_MATH_EXTERN:
1385         case LFUN_MATH_DISPLAY:
1386                 // we handle these
1387                 status.setEnabled(true);
1388                 return true;
1389
1390         case LFUN_MATH_MUTATE: {
1391                 HullType ht = hullType(cmd.argument());
1392                 status.setOnOff(type_ == ht);
1393                 status.setEnabled(true);
1394                 return true;
1395         }
1396
1397         case LFUN_MATH_NUMBER_TOGGLE:
1398                 // FIXME: what is the right test, this or the one of
1399                 // LABEL_INSERT?
1400                 status.setEnabled(display());
1401                 status.setOnOff(numberedType());
1402                 return true;
1403
1404         case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1405                 // FIXME: what is the right test, this or the one of
1406                 // LABEL_INSERT?
1407                 bool const enable = (type_ == hullMultline)
1408                         ? (nrows() - 1 == cur.row())
1409                         : display() != Inline && nrows() > 1;
1410                 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1411                 status.setEnabled(enable);
1412                 status.setOnOff(enable && numbered(r));
1413                 return true;
1414         }
1415
1416         case LFUN_LABEL_INSERT:
1417                 status.setEnabled(type_ != hullSimple);
1418                 return true;
1419
1420         case LFUN_LABEL_COPY_AS_REF: {
1421                 bool enabled = false;
1422                 row_type row;
1423                 if (cmd.argument().empty() && &cur.inset() == this) {
1424                         // if there is no argument and we're inside math, we retrieve
1425                         // the row number from the cursor position.
1426                         row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1427                         enabled = numberedType() && label_[row] && !nonum_[row];
1428                 } else {
1429                         // if there is an argument, find the corresponding label, else
1430                         // check whether there is at least one label.
1431                         for (row_type row = 0; row != nrows(); ++row) {
1432                                 if (!nonum_[row] && label_[row] && 
1433                                         (cmd.argument().empty() || label(row) == cmd.argument())) {
1434                                                 enabled = true;
1435                                                 break;
1436                                 }
1437                         }
1438                 }
1439                 status.setEnabled(enabled);
1440                 return true;
1441         }
1442
1443         case LFUN_INSET_INSERT:
1444                 if (cmd.getArg(0) == "label") {
1445                         status.setEnabled(type_ != hullSimple);
1446                         return true;
1447                 }
1448                 return InsetMathGrid::getStatus(cur, cmd, status);
1449
1450         case LFUN_TABULAR_FEATURE: {
1451                 istringstream is(to_utf8(cmd.argument()));
1452                 string s;
1453                 is >> s;
1454                 if (!rowChangeOK()
1455                     && (s == "append-row"
1456                         || s == "delete-row"
1457                         || s == "copy-row")) {
1458                         status.message(bformat(
1459                                 from_utf8(N_("Can't change number of rows in '%1$s'")),
1460                                 hullName(type_)));
1461                         status.setEnabled(false);
1462                         return true;
1463                 }
1464                 if (!colChangeOK()
1465                     && (s == "append-column"
1466                         || s == "delete-column"
1467                         || s == "copy-column")) {
1468                         status.message(bformat(
1469                                 from_utf8(N_("Can't change number of columns in '%1$s'")),
1470                                 hullName(type_)));
1471                         status.setEnabled(false);
1472                         return true;
1473                 }
1474                 if ((type_ == hullSimple
1475                   || type_ == hullEquation
1476                   || type_ == hullNone) &&
1477                     (s == "add-hline-above" || s == "add-hline-below")) {
1478                         status.message(bformat(
1479                                 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1480                                 hullName(type_)));
1481                         status.setEnabled(false);
1482                         return true;
1483                 }
1484                 if (s == "add-vline-left" || s == "add-vline-right") {
1485                         status.message(bformat(
1486                                 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1487                                 hullName(type_)));
1488                         status.setEnabled(false);
1489                         return true;
1490                 }
1491                 if (s == "valign-top" || s == "valign-middle"
1492                  || s == "valign-bottom" || s == "align-left"
1493                  || s == "align-center" || s == "align-right") {
1494                         status.setEnabled(false);
1495                         return true;
1496                 }
1497                 return InsetMathGrid::getStatus(cur, cmd, status);
1498         }
1499
1500         default:
1501                 return InsetMathGrid::getStatus(cur, cmd, status);
1502         }
1503
1504         // This cannot really happen, but inserted to shut-up gcc
1505         return InsetMathGrid::getStatus(cur, cmd, status);
1506 }
1507
1508
1509 /////////////////////////////////////////////////////////////////////
1510
1511
1512
1513 // simply scrap this function if you want
1514 void InsetMathHull::mutateToText()
1515 {
1516 #if 0
1517         // translate to latex
1518         ostringstream os;
1519         latex(os, false, false);
1520         string str = os.str();
1521
1522         // insert this text
1523         Text * lt = view_->cursor().innerText();
1524         string::const_iterator cit = str.begin();
1525         string::const_iterator end = str.end();
1526         for (; cit != end; ++cit)
1527                 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1528
1529         // remove ourselves
1530         //dispatch(LFUN_ESCAPE);
1531 #endif
1532 }
1533
1534
1535 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1536         docstring const & font)
1537 {
1538         // this whole function is a hack and won't work for incremental font
1539         // changes...
1540         cur.recordUndo();
1541         if (cur.inset().asInsetMath()->name() == font)
1542                 cur.handleFont(to_utf8(font));
1543         else {
1544                 cur.handleNest(createInsetMath(font, cur.buffer()));
1545                 cur.insert(arg);
1546         }
1547 }
1548
1549
1550 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1551 {
1552         cur.recordUndo();
1553         Font font;
1554         bool b;
1555         font.fromString(to_utf8(arg), b);
1556         if (font.fontInfo().color() != Color_inherit) {
1557                 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1558                 cur.handleNest(at, 0);
1559         }
1560 }
1561
1562
1563 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1564 {
1565         cur.push(*this);
1566         bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1567                 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1568         enter_front ? idxFirst(cur) : idxLast(cur);
1569         // The inset formula dimension is not necessarily the same as the
1570         // one of the instant preview image, so we have to indicate to the
1571         // BufferView that a metrics update is needed.
1572         cur.updateFlags(Update::Force);
1573 }
1574
1575
1576 void InsetMathHull::revealCodes(Cursor & cur) const
1577 {
1578         if (!cur.inMathed())
1579                 return;
1580         odocstringstream os;
1581         cur.info(os);
1582         cur.message(os.str());
1583 /*
1584         // write something to the minibuffer
1585         // translate to latex
1586         cur.markInsert(bv);
1587         ostringstream os;
1588         write(os);
1589         string str = os.str();
1590         cur.markErase(bv);
1591         string::size_type pos = 0;
1592         string res;
1593         for (string::iterator it = str.begin(); it != str.end(); ++it) {
1594                 if (*it == '\n')
1595                         res += ' ';
1596                 else if (*it == '\0') {
1597                         res += "  -X-  ";
1598                         pos = it - str.begin();
1599                 }
1600                 else
1601                         res += *it;
1602         }
1603         if (pos > 30)
1604                 res = res.substr(pos - 30);
1605         if (res.size() > 60)
1606                 res = res.substr(0, 60);
1607         cur.message(res);
1608 */
1609 }
1610
1611
1612 /////////////////////////////////////////////////////////////////////
1613
1614
1615 #if 0
1616 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1617                                      bool, bool)
1618 {
1619         // FIXME: completely broken
1620         static InsetMathHull * lastformula = 0;
1621         static CursorBase current = DocIterator(ibegin(nucleus()));
1622         static MathData ar;
1623         static string laststr;
1624
1625         if (lastformula != this || laststr != str) {
1626                 //lyxerr << "reset lastformula to " << this << endl;
1627                 lastformula = this;
1628                 laststr = str;
1629                 current = ibegin(nucleus());
1630                 ar.clear();
1631                 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1632         } else {
1633                 increment(current);
1634         }
1635         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1636
1637         for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1638                 CursorSlice & top = it.back();
1639                 MathData const & a = top.asInsetMath()->cell(top.idx_);
1640                 if (a.matchpart(ar, top.pos_)) {
1641                         bv->cursor().setSelection(it, ar.size());
1642                         current = it;
1643                         top.pos_ += ar.size();
1644                         bv->update();
1645                         return true;
1646                 }
1647         }
1648
1649         //lyxerr << "not found!" << endl;
1650         lastformula = 0;
1651         return false;
1652 }
1653 #endif
1654
1655
1656 void InsetMathHull::write(ostream & os) const
1657 {
1658         odocstringstream oss;
1659         WriteStream wi(oss, false, false, WriteStream::wsDefault);
1660         oss << "Formula ";
1661         write(wi);
1662         os << to_utf8(oss.str());
1663 }
1664
1665
1666 void InsetMathHull::read(Lexer & lex)
1667 {
1668         MathAtom at;
1669         mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1670         operator=(*at->asHullInset());
1671 }
1672
1673
1674 bool InsetMathHull::readQuiet(Lexer & lex)
1675 {
1676         MathAtom at;
1677         bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1678         if (success)
1679                 operator=(*at->asHullInset());
1680         return success;
1681 }
1682
1683
1684 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1685 {
1686         if (0 && display()) {
1687                 Dimension dim;
1688                 TextMetricsInfo mi;
1689                 metricsT(mi, dim);
1690                 TextPainter tpain(dim.width(), dim.height());
1691                 drawT(tpain, 0, dim.ascent());
1692                 tpain.show(os, 3);
1693                 // reset metrics cache to "real" values
1694                 //metrics();
1695                 return tpain.textheight();
1696         } else {
1697                 odocstringstream oss;
1698                 Encoding const * const enc = encodings.fromLyXName("utf8");
1699                 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1700                 // Fix Bug #6139
1701                 if (type_ == hullRegexp)
1702                         write(wi);
1703                 else
1704                         wi << cell(0);
1705                 docstring const str = oss.str();
1706                 os << str;
1707                 return str.size();
1708         }
1709 }
1710
1711
1712 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1713 {
1714         MathStream ms(os);
1715         int res = 0;
1716         docstring name;
1717         if (getType() == hullSimple)
1718                 name = from_ascii("inlineequation");
1719         else
1720                 name = from_ascii("informalequation");
1721
1722         docstring bname = name;
1723         if (!label(0).empty())
1724                 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1725
1726         ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1727
1728         odocstringstream ls;
1729         if (runparams.flavor == OutputParams::XML) {
1730                 ms << MTag("alt role='tex' ");
1731                 // Workaround for db2latex: db2latex always includes equations with
1732                 // \ensuremath{} or \begin{display}\end{display}
1733                 // so we strip LyX' math environment
1734                 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1735                 InsetMathGrid::write(wi);
1736                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
1737                 ms << ETag("alt");
1738                 ms << MTag("math");
1739                 ms << ETag("alt");
1740                 ms << MTag("math");
1741                 InsetMathGrid::mathmlize(ms);
1742                 ms << ETag("math");
1743         } else {
1744                 ms << MTag("alt role='tex'");
1745                 res = latex(ls, runparams);
1746                 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&amp;"), "<", "&lt;"));
1747                 ms << ETag("alt");
1748         }
1749
1750         ms << from_ascii("<graphic fileref=\"eqn/");
1751         if (!label(0).empty())
1752                 ms << sgml::cleanID(buffer(), runparams, label(0));
1753         else
1754                 ms << sgml::uniqueID(from_ascii("anon"));
1755
1756         if (runparams.flavor == OutputParams::XML)
1757                 ms << from_ascii("\"/>");
1758         else
1759                 ms << from_ascii("\">");
1760
1761         ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1762
1763         return ms.line() + res;
1764 }
1765
1766
1767 docstring InsetMathHull::xhtml(odocstream & os, OutputParams const &) const
1768 {
1769         if (getType() == hullSimple)
1770                 os << "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">";
1771         else 
1772                 os << "<math display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\">";
1773         MathStream ms(os);
1774         InsetMathGrid::mathmlize(ms);
1775         os << "</math>";
1776         return docstring();
1777 }
1778
1779
1780 void InsetMathHull::tocString(odocstream & os) const
1781 {
1782         plaintext(os, OutputParams(0));
1783 }
1784
1785
1786 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1787 {
1788         return from_ascii("context-math");
1789 }
1790
1791
1792 } // namespace lyx