]> git.lyx.org Git - lyx.git/blob - src/mathed/MathMacroTemplate.cpp
cb661f23cd1d3674dd8d8e9ce00f652a0b797158
[lyx.git] / src / mathed / MathMacroTemplate.cpp
1 /**
2  * \file MathMacroTemplate.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 "MathMacroTemplate.h"
14
15 #include "DocIterator.h"
16 #include "InsetMathBrace.h"
17 #include "InsetMathChar.h"
18 #include "InsetMathSqrt.h"
19 #include "MathMacro.h"
20 #include "MathMacroArgument.h"
21 #include "MathStream.h"
22 #include "MathParser.h"
23 #include "MathSupport.h"
24 #include "MathMacroArgument.h"
25
26 #include "Buffer.h"
27 #include "BufferView.h"
28 #include "Color.h"
29 #include "Cursor.h"
30 #include "support/debug.h"
31 #include "DispatchResult.h"
32 #include "FuncRequest.h"
33 #include "FuncStatus.h"
34 #include "support/gettext.h"
35 #include "Lexer.h"
36 #include "Undo.h"
37
38 #include "frontends/FontMetrics.h"
39 #include "frontends/Painter.h"
40
41 #include "support/convert.h"
42 #include "support/docstream.h"
43 #include "support/lstrings.h"
44
45 #include "support/debug.h"
46
47 #include <sstream>
48
49 using namespace std;
50
51 namespace lyx {
52
53 using support::bformat;
54
55 //////////////////////////////////////////////////////////////////////
56
57 class InsetLabelBox : public InsetMathNest {
58 public:
59         ///
60         InsetLabelBox(MathAtom const & atom, docstring label, 
61                                                                 MathMacroTemplate const & parent, bool frame = false);
62         InsetLabelBox(docstring label, MathMacroTemplate const & parent, 
63                                                                 bool frame = false);
64         ///
65         void metrics(MetricsInfo & mi, Dimension & dim) const;
66         ///
67         void draw(PainterInfo &, int x, int y) const;
68         
69 protected:
70         ///
71         MathMacroTemplate const & parent_;
72         ///
73         Inset * clone() const;
74         ///
75         docstring const label_;
76         ///
77         bool frame_;
78 };
79
80
81 InsetLabelBox::InsetLabelBox(MathAtom const & atom, docstring label, 
82                                                                                                                  MathMacroTemplate const & parent, bool frame)
83 :       InsetMathNest(1), parent_(parent), label_(label), frame_(frame)
84 {
85         cell(0).insert(0, atom);
86 }
87
88
89 InsetLabelBox::InsetLabelBox(docstring label,
90                                                                                                                  MathMacroTemplate const & parent, bool frame)
91 :       InsetMathNest(1), parent_(parent), label_(label), frame_(frame)
92 {
93 }
94         
95
96 Inset * InsetLabelBox::clone() const 
97 {
98         return new InsetLabelBox(*this);
99 }
100
101
102 void InsetLabelBox::metrics(MetricsInfo & mi, Dimension & dim) const 
103 {
104         // kernel
105         cell(0).metrics(mi, dim);
106
107         // frame
108         if (frame_) {
109                 dim.wid += 6;
110                 dim.asc += 5;
111                 dim.des += 5;
112         }
113                 
114         // adjust to common height in main metrics phase
115         if (!parent_.premetrics()) {
116                 dim.asc = max(dim.asc, parent_.commonLabelBoxAscent());
117                 dim.des = max(dim.des, parent_.commonLabelBoxDescent());
118         }
119         
120         // label
121         if (parent_.editing(mi.base.bv) && label_.length() > 0) {
122                 // grey
123                 FontInfo font = sane_font;
124                 font.setSize(FONT_SIZE_TINY);
125                 font.setColor(Color_mathmacrolabel);
126                 
127                 // make space for label and box
128                 int lwid = mathed_string_width(font, label_);
129                 int maxasc;
130                 int maxdes;
131                 math_font_max_dim(font, maxasc, maxdes);                
132                 
133                 dim.wid = max(dim.wid, lwid + 2);
134
135                 // space for the label
136                 if (!parent_.premetrics())
137                         dim.des += maxasc + maxdes + 1;
138         }
139
140         setDimCache(mi, dim);
141 }
142
143
144 void InsetLabelBox::draw(PainterInfo & pi, int x, int y) const 
145 {
146         Dimension const dim = dimension(*pi.base.bv);
147         Dimension const cdim = cell(0).dimension(*pi.base.bv);
148         
149         // kernel
150         cell(0).draw(pi, x + (dim.wid - cdim.wid) / 2, y);
151         
152         // label
153         if (parent_.editing(pi.base.bv) && label_.length() > 0) {
154                 // grey
155                 FontInfo font = sane_font;
156                 font.setSize(FONT_SIZE_TINY);
157                 font.setColor(Color_mathmacrolabel);
158                 
159                 // make space for label and box
160                 int lwid = mathed_string_width(font, label_);
161                 int maxasc;
162                 int maxdes;
163                 math_font_max_dim(font, maxasc, maxdes);
164                 
165                 if (lwid < dim.wid)
166                         pi.pain.text(x + (dim.wid - lwid) / 2, y + dim.des - maxdes, label_, font);
167                 else
168                         pi.pain.text(x, y + dim.des - maxdes, label_, font);
169         }
170         
171         // draw frame
172         int boxHeight = parent_.commonLabelBoxAscent() + parent_.commonLabelBoxDescent();
173         if (frame_) {
174                 pi.pain.rectangle(x + 1, y - dim.ascent() + 1, 
175                                                                                         dim.wid - 2, boxHeight - 2, 
176                                                                                         Color_mathline);
177         }
178 }
179
180
181 //////////////////////////////////////////////////////////////////////
182
183 class DisplayLabelBox : public InsetLabelBox {
184 public:
185         ///
186         DisplayLabelBox(MathAtom const & atom, docstring label, 
187                                                                         MathMacroTemplate const & parent);
188                 
189         ///
190         void metrics(MetricsInfo & mi, Dimension & dim) const;
191         ///
192         void draw(PainterInfo &, int x, int y) const;
193         
194 protected:
195         ///
196         Inset * clone() const;
197 };
198
199
200 DisplayLabelBox::DisplayLabelBox(MathAtom const & atom, 
201                                                                                                                                  docstring label, 
202                                                                                                                                  MathMacroTemplate const & parent)
203         : InsetLabelBox(atom, label, parent, true)
204 {
205 }
206         
207         
208         
209 Inset * DisplayLabelBox::clone() const 
210 {
211         return new DisplayLabelBox(*this);
212 }
213         
214         
215 void DisplayLabelBox::metrics(MetricsInfo & mi, Dimension & dim) const
216 {
217         InsetLabelBox::metrics(mi, dim);
218         if (!parent_.editing(mi.base.bv)
219                         && parent_.cell(parent_.displayIdx()).empty()) {
220                 dim.wid = 0;
221                 dim.asc = 0;
222                 dim.des = 0;
223                 setDimCache(mi, dim);
224         }
225 }
226
227         
228 void DisplayLabelBox::draw(PainterInfo & pi, int x, int y) const
229 {
230         if (parent_.editing(pi.base.bv)
231                         || !parent_.cell(parent_.displayIdx()).empty()) {
232                 InsetLabelBox::draw(pi, x, y);
233         } else {
234                 bool enabled = pi.pain.isDrawingEnabled();
235                 pi.pain.setDrawingEnabled(false);
236                 InsetLabelBox::draw(pi, x, y);
237                 pi.pain.setDrawingEnabled(enabled);
238         }
239 }
240         
241
242 //////////////////////////////////////////////////////////////////////
243
244 class InsetMathWrapper : public InsetMath {
245 public:
246         ///
247         InsetMathWrapper(MathData const * value) : value_(value) {}
248         ///
249         void metrics(MetricsInfo & mi, Dimension & dim) const;
250         ///
251         void draw(PainterInfo &, int x, int y) const;
252         
253 private:
254         ///
255         Inset * clone() const;
256         ///
257         MathData const * value_;
258 };
259
260
261 Inset * InsetMathWrapper::clone() const 
262 {
263         return new InsetMathWrapper(*this);
264 }
265
266
267 void InsetMathWrapper::metrics(MetricsInfo & mi, Dimension & dim) const 
268 {
269         value_->metrics(mi, dim);
270         //metricsMarkers2(dim);
271 }
272
273
274 void InsetMathWrapper::draw(PainterInfo & pi, int x, int y) const 
275 {
276         value_->draw(pi, x, y);
277         //drawMarkers(pi, x, y);
278 }
279
280
281 ///////////////////////////////////////////////////////////////////////
282
283 class InsetNameWrapper : public InsetMathWrapper {
284 public:
285         ///
286         InsetNameWrapper(MathData const * value, MathMacroTemplate const & parent);
287         ///
288         void metrics(MetricsInfo & mi, Dimension & dim) const;
289         ///
290         void draw(PainterInfo &, int x, int y) const;
291         
292 private:
293         ///
294         MathMacroTemplate const & parent_;
295         ///
296         Inset * clone() const;
297 };
298
299
300 InsetNameWrapper::InsetNameWrapper(MathData const * value, 
301                                                                                                                                          MathMacroTemplate const & parent)
302         :       InsetMathWrapper(value), parent_(parent)
303 {
304 }
305
306
307 Inset * InsetNameWrapper::clone() const 
308 {
309         return new InsetNameWrapper(*this);
310 }
311
312
313 void InsetNameWrapper::metrics(MetricsInfo & mi, Dimension & dim) const 
314 {
315         InsetMathWrapper::metrics(mi, dim);
316         dim.wid += mathed_string_width(mi.base.font, from_ascii("\\"));
317 }
318
319
320 void InsetNameWrapper::draw(PainterInfo & pi, int x, int y) const 
321 {
322         // create fonts
323         PainterInfo namepi = pi;
324         if (parent_.validMacro())
325                 namepi.base.font.setColor(Color_latex);
326         else
327                 namepi.base.font.setColor(Color_error);         
328         
329         // draw backslash
330         pi.pain.text(x, y, from_ascii("\\"), namepi.base.font);
331         x += mathed_string_width(namepi.base.font, from_ascii("\\"));
332         
333         // draw name
334         InsetMathWrapper::draw(namepi, x, y);
335 }
336
337         
338 ///////////////////////////////////////////////////////////////////////
339         
340         
341 MathMacroTemplate::MathMacroTemplate()
342         : InsetMathNest(3), numargs_(0), optionals_(0), 
343           type_(MacroTypeNewcommand), lookOutdated_(true)
344 {
345         initMath();
346 }
347
348
349 MathMacroTemplate::MathMacroTemplate(docstring const & name, int numargs,
350         int optionals, MacroType type, 
351         vector<MathData> const & optionalValues, 
352         MathData const & def, MathData const & display)
353         : InsetMathNest(optionals + 3), numargs_(numargs), 
354           optionals_(optionals), optionalValues_(optionalValues),
355           type_(type), lookOutdated_(true)
356 {
357         initMath();
358
359         if (numargs_ > 9)
360                 lyxerr << "MathMacroTemplate::MathMacroTemplate: wrong # of arguments: "
361                         << numargs_ << endl;
362         
363         asArray(name, cell(0));
364         optionalValues_.resize(9);
365         for (int i = 0; i < optionals_; ++i) 
366                 cell(optIdx(i)) = optionalValues_[i];
367         cell(defIdx()) = def;
368         cell(displayIdx()) = display;
369
370         updateLook();
371 }
372
373
374 MathMacroTemplate::MathMacroTemplate(docstring const & str)
375         : InsetMathNest(3), numargs_(0), optionals_(0),
376         type_(MacroTypeNewcommand), lookOutdated_(true)
377 {
378         initMath();
379
380         MathData ar;
381         mathed_parse_cell(ar, str);
382         if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
383                 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
384                 asArray(from_ascii("invalidmacro"), cell(0));
385                 // FIXME: The macro template does not make sense after this.
386                 // The whole parsing should not be in a constructor which
387                 // has no chance to report failure.
388                 return;
389         }
390         operator=( *(ar[0]->asMacroTemplate()) );
391
392         updateLook();
393 }
394
395
396 Inset * MathMacroTemplate::clone() const
397 {
398         return new MathMacroTemplate(*this);
399 }
400
401
402 docstring MathMacroTemplate::name() const
403 {
404         return asString(cell(0));
405 }
406
407
408 void MathMacroTemplate::updateToContext(MacroContext const & mc) const
409 {
410         redefinition_ = mc.get(name()) != 0;
411 }
412
413         
414 void MathMacroTemplate::updateLook() const
415 {
416         lookOutdated_ = true;
417 }
418
419
420 void MathMacroTemplate::createLook() const
421 {
422         look_.clear();
423
424         // \foo
425         look_.push_back(MathAtom(new InsetLabelBox(_("Name"), *this, false)));
426         MathData & nameData = look_[look_.size() - 1].nucleus()->cell(0);
427         nameData.push_back(MathAtom(new InsetNameWrapper(&cell(0), *this)));
428         
429         // [#1][#2]
430         int i = 0;
431         if (optionals_ > 0) {
432                 look_.push_back(MathAtom(new InsetLabelBox(_("optional"), *this, false)));
433                 MathData & optData = look_[look_.size() - 1].nucleus()->cell(0);
434         
435                 for (; i < optionals_; ++i) {
436                         optData.push_back(MathAtom(new InsetMathChar('[')));
437                         optData.push_back(MathAtom(new InsetMathWrapper(&cell(1 + i))));
438                         optData.push_back(MathAtom(new InsetMathChar(']')));
439                 }
440         }
441         
442         // {#3}{#4}
443         for (; i < numargs_; ++i) {
444                 MathData arg;
445                 arg.push_back(MathAtom(new MathMacroArgument(i + 1)));
446                 look_.push_back(MathAtom(new InsetMathBrace(arg)));
447         }
448         
449         // :=
450         look_.push_back(MathAtom(new InsetMathChar(':')));
451         look_.push_back(MathAtom(new InsetMathChar('=')));
452
453         // definition
454         look_.push_back(MathAtom(
455                 new InsetLabelBox(MathAtom(
456                         new InsetMathWrapper(&cell(defIdx()))), _("TeX"), *this,        true)));
457
458         // display
459         look_.push_back(MathAtom(
460                 new DisplayLabelBox(MathAtom(
461                         new InsetMathWrapper(&cell(displayIdx()))), _("LyX"), *this)));
462 }
463         
464
465 void MathMacroTemplate::metrics(MetricsInfo & mi, Dimension & dim) const
466 {
467         FontSetChanger dummy1(mi.base, from_ascii("mathnormal"));
468         StyleChanger dummy2(mi.base, LM_ST_TEXT);
469         
470         // valid macro?
471         MacroData const * macro = 0;
472         if (validName()) {
473                 macro = mi.macrocontext.get(name());
474
475                 // updateToContext() - avoids another lookup
476                 redefinition_ = macro != 0;
477         }
478                 
479         // update look?
480         if (lookOutdated_) {
481                 lookOutdated_ = false;
482                 createLook();
483         }
484         
485         /// metrics for inset contents
486         if (macro)
487                 macro->lock();          
488         
489         // first phase, premetric:
490         premetrics_ = true;
491         look_.metrics(mi, dim);
492         labelBoxAscent_ = dim.asc;
493         labelBoxDescent_ = dim.des;
494         
495         // second phase, main metric:
496         premetrics_ = false;
497         look_.metrics(mi, dim);
498         
499         if (macro)
500                 macro->unlock();
501         
502         dim.wid += 6;
503         dim.des += 2;
504         dim.asc += 2;
505         
506         setDimCache(mi, dim);
507 }
508
509
510 void MathMacroTemplate::draw(PainterInfo & pi, int x, int y) const
511 {
512         FontSetChanger dummy1(pi.base, from_ascii("mathnormal"));
513         StyleChanger dummy2(pi.base, LM_ST_TEXT);
514         
515         setPosCache(pi, x, y);
516         Dimension const dim = dimension(*pi.base.bv);
517
518         // draw outer frame
519         int const a = y - dim.asc + 1;
520         int const w = dim.wid - 2;
521         int const h = dim.height() - 2;
522         pi.pain.rectangle(x, a, w, h, Color_mathframe); 
523         
524         // just to be sure: set some dummy values for coord cache
525         for (idx_type i = 0; i < nargs(); ++i) {
526                 cell(i).setXY(*pi.base.bv, x, y);
527         }
528         
529         // draw contents
530         look_.draw(pi, x + 3, y);
531 }
532
533         
534 void MathMacroTemplate::edit(Cursor & cur, bool left)
535 {
536         updateLook();
537         cur.updateFlags(Update::Force);
538         InsetMathNest::edit(cur, left);
539 }
540         
541         
542 Inset * MathMacroTemplate::editXY(Cursor & cur, int x, int y)
543 {
544         Inset * ret = InsetMathNest::editXY(cur, x, y);
545 /*      if (!editing_ && editing(cur.bv())) {
546                 
547                 cur.updateFlags(Update::Force);
548         }*/
549         return ret;
550 }
551         
552         
553 bool MathMacroTemplate::notifyCursorLeaves(Cursor & cur)
554 {
555         updateLook();
556         cur.updateFlags(Update::Force);
557         return InsetMathNest::notifyCursorLeaves(cur);
558 }
559         
560
561 void MathMacroTemplate::removeArguments(Cursor & cur, int from, int to) {
562         for (DocIterator it = doc_iterator_begin(*this); it; it.forwardChar()) {
563                 if (!it.nextInset())
564                         continue;
565                 if (it.nextInset()->lyxCode() != MATHMACROARG_CODE)
566                         continue;
567                 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
568                 int n = arg->number() - 1;
569                 if (from <= n && n <= to) {
570                         int cellSlice = cur.find(it.cell());
571                         if (cellSlice != -1 && cur[cellSlice].pos() > it.pos())
572                                 --cur[cellSlice].pos();
573
574                         it.cell().erase(it.pos());
575                 }
576         }
577         
578         updateLook();
579 }
580
581
582 void MathMacroTemplate::shiftArguments(size_t from, int by) {
583         for (DocIterator it = doc_iterator_begin(*this); it; it.forwardChar()) {
584                 if (!it.nextInset())
585                         continue;
586                 if (it.nextInset()->lyxCode() != MATHMACROARG_CODE)
587                         continue;
588                 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
589                 if (arg->number() >= from + 1)
590                         arg->setNumber(arg->number() + by);
591         }
592
593         updateLook();
594 }
595
596
597 // FIXME: factorize those functions here with a functional style, maybe using Boost's function
598 // objects?
599
600 void fixMacroInstancesAddRemove(Cursor const & from, docstring const & name, int n, bool insert) {
601         Cursor dit = from;
602
603         for (; dit; dit.forwardPos()) {
604                 // only until a macro is redefined
605                 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
606                         MathMacroTemplate const & macroTemplate
607                         = static_cast<MathMacroTemplate const &>(dit.inset());
608                         if (macroTemplate.name() == name)
609                                 break;
610                 }
611
612                 // in front of macro instance?
613                 Inset * inset = dit.nextInset();
614                 if (inset) {
615                         InsetMath * insetMath = inset->asInsetMath();
616                         if (insetMath) {
617                                 MathMacro * macro = insetMath->asMacro();
618                                 if (macro && macro->name() == name && macro->folded()) {
619                                         // found macro instance
620                                         if (insert)
621                                                 macro->insertArgument(n);
622                                         else
623                                                 macro->removeArgument(n);
624                                 }
625                         }
626                 }
627         }
628 }
629
630
631 void fixMacroInstancesOptional(Cursor const & from, docstring const & name, int optionals) {
632         Cursor dit = from;
633
634         for (; dit; dit.forwardPos()) {
635                 // only until a macro is redefined
636                 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
637                         MathMacroTemplate const & macroTemplate
638                         = static_cast<MathMacroTemplate const &>(dit.inset());
639                         if (macroTemplate.name() == name)
640                                 break;
641                 }
642
643                 // in front of macro instance?
644                 Inset * inset = dit.nextInset();
645                 if (inset) {
646                         InsetMath * insetMath = inset->asInsetMath();
647                         if (insetMath) {
648                                 MathMacro * macro = insetMath->asMacro();
649                                 if (macro && macro->name() == name && macro->folded()) {
650                                         // found macro instance
651                                         macro->setOptionals(optionals);
652                                 }
653                         }
654                 }
655         }
656 }
657
658
659 template<class F>
660 void fixMacroInstancesFunctional(Cursor const & from, 
661         docstring const & name, F & fix) {
662         Cursor dit = from;
663
664         for (; dit; dit.forwardPos()) {
665                 // only until a macro is redefined
666                 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
667                         MathMacroTemplate const & macroTemplate
668                         = static_cast<MathMacroTemplate const &>(dit.inset());
669                         if (macroTemplate.name() == name)
670                                 break;
671                 }
672
673                 // in front of macro instance?
674                 Inset * inset = dit.nextInset();
675                 if (inset) {
676                         InsetMath * insetMath = inset->asInsetMath();
677                         if (insetMath) {
678                                 MathMacro * macro = insetMath->asMacro();
679                                 if (macro && macro->name() == name && macro->folded())
680                                         F(macro);
681                         }
682                 }
683         }
684 }
685
686
687 void MathMacroTemplate::insertParameter(Cursor & cur, int pos, bool greedy) 
688 {
689         if (pos <= numargs_ && pos >= optionals_ && numargs_ < 9) {
690                 ++numargs_;
691                 shiftArguments(pos, 1);
692
693                 // append example #n
694                 cell(defIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
695                 if (!cell(displayIdx()).empty())
696                         cell(displayIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
697
698                 if (!greedy) {
699                         Cursor dit = cur;
700                         dit.leaveInset(*this);
701                         // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
702                         dit.top().forwardPos();
703                         
704                         // fix macro instances
705                         fixMacroInstancesAddRemove(dit, name(), pos, true);
706                 }
707         }
708
709         updateLook();
710 }
711
712
713 void MathMacroTemplate::removeParameter(Cursor & cur, int pos, bool greedy)
714 {
715         if (pos < numargs_ && pos >= 0) {
716                 --numargs_;
717                 removeArguments(cur, pos, pos);
718                 shiftArguments(pos + 1, -1);
719
720                 // removed optional parameter?
721                 if (pos < optionals_) {
722                         --optionals_;
723                         optionalValues_[pos] = cell(optIdx(pos));
724                         cells_.erase(cells_.begin() + optIdx(pos));
725
726                         // fix cursor
727                         int macroSlice = cur.find(this);
728                         if (macroSlice != -1) {
729                                 if (cur[macroSlice].idx() == optIdx(pos)) {
730                                         cur.cutOff(macroSlice);
731                                         cur[macroSlice].idx() = 1;
732                                         cur[macroSlice].pos() = 0;
733                                 } else if (cur[macroSlice].idx() > optIdx(pos))
734                                         --cur[macroSlice].idx();
735                         }
736                 }
737
738                 if (!greedy) {
739                         // fix macro instances
740                         //boost::function<void(MathMacro *)> fix = _1->insertArgument(n);
741                         //fixMacroInstancesFunctional(dit, name(), fix);
742                         Cursor dit = cur;
743                         dit.leaveInset(*this);
744                         // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
745                         dit.top().forwardPos();
746                         fixMacroInstancesAddRemove(dit, name(), pos, false);
747                 }
748         }
749
750         updateLook();
751 }
752
753
754 void MathMacroTemplate::makeOptional(Cursor & cur) {
755         if (numargs_ > 0 && optionals_ < numargs_) {
756                 ++optionals_;
757                 cells_.insert(cells_.begin() + optIdx(optionals_ - 1), optionalValues_[optionals_ - 1]);
758                 // fix cursor
759                 int macroSlice = cur.find(this);
760                 if (macroSlice != -1 && cur[macroSlice].idx() >= optIdx(optionals_ - 1))
761                         ++cur[macroSlice].idx();
762
763                 // fix macro instances
764                 Cursor dit = cur;
765                 dit.leaveInset(*this);
766                 // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
767                 dit.top().forwardPos();
768                 fixMacroInstancesOptional(dit, name(), optionals_);
769         }
770
771         updateLook();
772 }
773
774
775 void MathMacroTemplate::makeNonOptional(Cursor & cur) {
776         if (numargs_ > 0 && optionals_ > 0) {
777                 --optionals_;
778                 
779                 // store default value for later if the use changes his mind
780                 optionalValues_[optionals_] = cell(optIdx(optionals_));
781                 cells_.erase(cells_.begin() + optIdx(optionals_));
782
783                 // fix cursor
784                 int macroSlice = cur.find(this);
785                 if (macroSlice != -1) {
786                         if (cur[macroSlice].idx() > optIdx(optionals_))
787                                 --cur[macroSlice].idx();
788                         else if (cur[macroSlice].idx() == optIdx(optionals_)) {
789                                 cur.cutOff(macroSlice);
790                                 cur[macroSlice].idx() = optIdx(optionals_);
791                                 cur[macroSlice].pos() = 0;
792                         }
793                 }
794
795                 // fix macro instances
796                 Cursor dit = cur;
797                 dit.leaveInset(*this);
798                 // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
799                 dit.top().forwardPos();
800                 fixMacroInstancesOptional(dit, name(), optionals_);
801         }
802
803         updateLook();
804 }
805
806
807 void MathMacroTemplate::doDispatch(Cursor & cur, FuncRequest & cmd)
808 {
809         string const arg = to_utf8(cmd.argument());
810         switch (cmd.action) {
811
812         case LFUN_MATH_MACRO_ADD_PARAM: 
813                 if (numargs_ < 9) {
814                         cur.recordUndoFullDocument();
815                         size_t pos = numargs_;
816                         if (arg.size() != 0)
817                                 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
818                         insertParameter(cur, pos);
819                 }
820                 break;
821
822
823         case LFUN_MATH_MACRO_REMOVE_PARAM: 
824                 if (numargs_ > 0) {
825                         cur.recordUndoFullDocument();
826                         size_t pos = numargs_ - 1;
827                         if (arg.size() != 0)
828                                 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
829                         removeParameter(cur, pos);
830                 }
831                 break;
832
833         case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
834                 if (numargs_ < 9) {
835                         cur.recordUndoFullDocument();
836                         insertParameter(cur, numargs_, true);
837                 }
838                 break;
839
840         case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
841                 if (numargs_ > 0) {
842                         cur.recordUndoFullDocument();
843                         removeParameter(cur, numargs_ - 1, true);
844                 }
845                 break;
846
847         case LFUN_MATH_MACRO_MAKE_OPTIONAL:
848                 cur.recordUndoFullDocument();
849                 makeOptional(cur);
850                 break;
851
852         case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
853                 cur.recordUndoFullDocument();
854                 makeNonOptional(cur);
855                 break;
856
857         case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
858                 if (numargs_ < 9) {
859                         cur.recordUndoFullDocument();
860                         insertParameter(cur, optionals_);
861                         makeOptional(cur);
862                 }
863                 break;
864
865         case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
866                 if (optionals_ > 0) {
867                         cur.recordUndoFullDocument();
868                         removeParameter(cur, optionals_ - 1);
869                 } break;
870
871         case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
872                 if (numargs_ == optionals_) {
873                         cur.recordUndoFullDocument();
874                         insertParameter(cur, 0, true);
875                         makeOptional(cur);
876                 }
877                 break;
878
879         default:
880                 InsetMathNest::doDispatch(cur, cmd);
881                 break;
882         }
883 }
884
885
886 bool MathMacroTemplate::getStatus(Cursor & /*cur*/, FuncRequest const & cmd,
887         FuncStatus & flag) const
888 {
889         bool ret = true;
890         string const arg = to_utf8(cmd.argument());
891         switch (cmd.action) {
892                 case LFUN_MATH_MACRO_ADD_PARAM: {
893                         int num = numargs_ + 1;
894                         if (arg.size() != 0)
895                                 num = convert<int>(arg);
896                         bool on = (num >= optionals_ 
897                                    && numargs_ < 9 && num <= numargs_ + 1);
898                         flag.enabled(on);
899                         break;
900                 }
901
902                 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
903                         flag.enabled(numargs_ < 9);
904                         break;
905
906                 case LFUN_MATH_MACRO_REMOVE_PARAM: {
907                         int num = numargs_;
908                         if (arg.size() != 0)
909                                 num = convert<int>(arg);
910                         flag.enabled(num >= 1 && num <= numargs_);
911                         break;
912                 }
913
914                 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
915                         flag.enabled(numargs_ > 0 
916                                      && optionals_ < numargs_ 
917                                      && type_ != MacroTypeDef);
918                         break;
919
920                 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
921                         flag.enabled(optionals_ > 0 
922                                      && type_ != MacroTypeDef);
923                         break;
924
925                 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
926                         flag.enabled(numargs_ < 9);
927                         break;
928
929                 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
930                         flag.enabled(optionals_ > 0);
931                         break;
932
933                 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
934                         flag.enabled(numargs_ == 0 
935                                      && type_ != MacroTypeDef);
936                         break;
937
938                 case LFUN_IN_MATHMACROTEMPLATE:
939                         flag.enabled();
940                         break;
941
942                 default:
943                         ret = false;
944                         break;
945         }
946         return ret;
947 }
948
949
950 void MathMacroTemplate::read(Buffer const &, Lexer & lex)
951 {
952         MathData ar;
953         mathed_parse_cell(ar, lex.getStream());
954         if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
955                 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
956                 lyxerr << "Read: " << to_utf8(asString(ar)) << endl;
957                 return;
958         }
959         operator=( *(ar[0]->asMacroTemplate()) );
960         
961         updateLook();
962 }
963
964
965 void MathMacroTemplate::write(Buffer const &, ostream & os) const
966 {
967         odocstringstream oss;
968         WriteStream wi(oss, false, false);
969         oss << "FormulaMacro\n";
970         write(wi);
971         os << to_utf8(oss.str());
972 }
973
974
975 void MathMacroTemplate::write(WriteStream & os) const
976 {
977         write(os, false);
978 }
979
980
981 void MathMacroTemplate::write(WriteStream & os, bool overwriteRedefinition) const
982 {
983         if (type_ == MacroTypeDef) {
984                 os << "\\def\\" << name().c_str();
985                 for (int i = 1; i <= numargs_; ++i)
986                         os << '#' << i;
987         } else {
988                 // newcommand or renewcommand
989                 if (redefinition_ && !overwriteRedefinition)
990                         os << "\\renewcommand";
991                 else
992                         os << "\\newcommand";
993                 os << "{\\" << name().c_str() << '}';
994                 if (numargs_ > 0)
995                         os << '[' << numargs_ << ']';
996                 
997                 // optional values
998                 if (os.latex()) {
999                         // in latex only one optional possible, simulate the others
1000                         if (optionals_ >= 1) {
1001                                 docstring optValue = asString(cell(optIdx(0)));
1002                                 if (optValue.find(']') != docstring::npos)
1003                                         os << "[{" << cell(optIdx(0)) << "}]";
1004                                 else
1005                                         os << "[" << cell(optIdx(0)) << "]";
1006                         }
1007                 } else {
1008                         // in lyx we handle all optionals as real optionals
1009                         for (int i = 0; i < optionals_; ++i) {
1010                                 docstring optValue = asString(cell(optIdx(i)));
1011                                 if (optValue.find(']') != docstring::npos)
1012                                         os << "[{" << cell(optIdx(i)) << "}]";
1013                                 else
1014                                         os << "[" << cell(optIdx(i)) << "]";
1015                         }
1016                 }
1017         }
1018
1019         os << "{" << cell(defIdx()) << "}";
1020
1021         if (os.latex()) {
1022                 // writing .tex. done.
1023                 os << "\n";
1024         } else {
1025                 // writing .lyx, write special .tex export only if necessary
1026                 if (!cell(displayIdx()).empty())
1027                         os << "\n{" << cell(displayIdx()) << '}';
1028         }
1029 }
1030
1031
1032 int MathMacroTemplate::plaintext(Buffer const & buf, odocstream & os,
1033                                  OutputParams const &) const
1034 {
1035         static docstring const str = '[' + buf.B_("math macro") + ']';
1036
1037         os << str;
1038         return str.size();
1039 }
1040
1041
1042 bool MathMacroTemplate::validName() const
1043 {
1044         docstring n = name();
1045
1046         // empty name?
1047         if (n.size() == 0)
1048                 return false;
1049
1050         // converting back and force doesn't swallow anything?
1051         /*MathData ma;
1052         asArray(n, ma);
1053         if (asString(ma) != n)
1054                 return false;*/
1055
1056         // valid characters?
1057         for (size_t i = 0; i < n.size(); ++i) {
1058                 if (!(n[i] >= 'a' && n[i] <= 'z') &&
1059                                 !(n[i] >= 'A' && n[i] <= 'Z')) 
1060                         return false;
1061         }
1062
1063         return true;
1064 }
1065
1066
1067 bool MathMacroTemplate::validMacro() const
1068 {
1069         return validName();
1070 }
1071
1072
1073 bool MathMacroTemplate::fixNameAndCheckIfValid()
1074 {
1075         // check all the characters/insets in the name cell
1076         size_t i = 0;
1077         MathData & data = cell(0);
1078         while (i < data.size()) {
1079                 InsetMathChar const * cinset = data[i]->asCharInset();
1080                 if (cinset) {
1081                         // valid character in [a-zA-Z]?
1082                         char_type c = cinset->getChar();
1083                         if ((c >= 'a' && c <= 'z')
1084                             || (c >= 'A' && c <= 'Z')) {
1085                                 ++i;
1086                                 continue;
1087                         }
1088                 }
1089                 
1090                 // throw cell away
1091                 data.erase(i);
1092         }
1093
1094         // now it should be valid if anything in the name survived
1095         return data.size() > 0;
1096 }
1097
1098
1099 void MathMacroTemplate::getDefaults(vector<docstring> & defaults) const
1100 {
1101         defaults.resize(numargs_);
1102         for (int i = 0; i < optionals_; ++i)
1103                 defaults[i] = asString(cell(optIdx(i)));        
1104 }
1105
1106
1107 docstring MathMacroTemplate::definition() const
1108 {
1109         return asString(cell(defIdx()));
1110 }
1111
1112
1113 docstring MathMacroTemplate::displayDefinition() const
1114 {
1115         return asString(cell(displayIdx()));
1116 }
1117
1118
1119 size_t MathMacroTemplate::numArgs() const
1120 {
1121         return numargs_;
1122 }
1123
1124
1125 size_t MathMacroTemplate::numOptionals() const
1126 {
1127         return optionals_;
1128 }
1129
1130         
1131 void MathMacroTemplate::infoize(odocstream & os) const
1132 {
1133         os << "Math Macro: \\" << name();
1134 }
1135
1136 } // namespace lyx