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