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