]> git.lyx.org Git - lyx.git/blob - src/mathed/MathMacroTemplate.cpp
* \newlyxcommand support
[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 bool MathMacroTemplate::notifyCursorLeaves(Cursor & cur)
543 {
544         updateLook();
545         cur.updateFlags(Update::Force);
546         return InsetMathNest::notifyCursorLeaves(cur);
547 }
548
549
550 void MathMacroTemplate::removeArguments(Cursor & cur, int from, int to) {
551         for (DocIterator it = doc_iterator_begin(*this); it; it.forwardChar()) {
552                 if (!it.nextInset())
553                         continue;
554                 if (it.nextInset()->lyxCode() != MATHMACROARG_CODE)
555                         continue;
556                 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
557                 int n = arg->number() - 1;
558                 if (from <= n && n <= to) {
559                         int cellSlice = cur.find(it.cell());
560                         if (cellSlice != -1 && cur[cellSlice].pos() > it.pos())
561                                 --cur[cellSlice].pos();
562
563                         it.cell().erase(it.pos());
564                 }
565         }
566
567         updateLook();
568 }
569
570
571 void MathMacroTemplate::shiftArguments(size_t from, int by) {
572         for (DocIterator it = doc_iterator_begin(*this); it; it.forwardChar()) {
573                 if (!it.nextInset())
574                         continue;
575                 if (it.nextInset()->lyxCode() != MATHMACROARG_CODE)
576                         continue;
577                 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
578                 if (arg->number() >= from + 1)
579                         arg->setNumber(arg->number() + by);
580         }
581
582         updateLook();
583 }
584
585
586 // FIXME: factorize those functions here with a functional style, maybe using Boost's function
587 // objects?
588
589 void fixMacroInstancesAddRemove(Cursor const & from, docstring const & name, int n, bool insert) {
590         Cursor dit = from;
591
592         for (; dit; dit.forwardPos()) {
593                 // only until a macro is redefined
594                 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
595                         MathMacroTemplate const & macroTemplate
596                         = static_cast<MathMacroTemplate const &>(dit.inset());
597                         if (macroTemplate.name() == name)
598                                 break;
599                 }
600
601                 // in front of macro instance?
602                 Inset * inset = dit.nextInset();
603                 if (!inset)
604                         continue;
605                 InsetMath * insetMath = inset->asInsetMath();
606                 if (!insetMath)
607                         continue;
608
609                 MathMacro * macro = insetMath->asMacro();
610                 if (macro && macro->name() == name && macro->folded()) {
611                         // found macro instance
612                         if (insert)
613                                 macro->insertArgument(n);
614                         else
615                                 macro->removeArgument(n);
616                 }
617         }
618 }
619
620
621 void fixMacroInstancesOptional(Cursor const & from, docstring const & name, int optionals) {
622         Cursor dit = from;
623
624         for (; dit; dit.forwardPos()) {
625                 // only until a macro is redefined
626                 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
627                         MathMacroTemplate const & macroTemplate
628                         = static_cast<MathMacroTemplate const &>(dit.inset());
629                         if (macroTemplate.name() == name)
630                                 break;
631                 }
632
633                 // in front of macro instance?
634                 Inset * inset = dit.nextInset();
635                 if (!inset)
636                         continue;
637                 InsetMath * insetMath = inset->asInsetMath();
638                 if (!insetMath)
639                         continue;
640                 MathMacro * macro = insetMath->asMacro();
641                 if (macro && macro->name() == name && macro->folded()) {
642                         // found macro instance
643                         macro->setOptionals(optionals);
644                 }
645         }
646 }
647
648
649 template<class F>
650 void fixMacroInstancesFunctional(Cursor const & from,
651         docstring const & name, F & fix) {
652         Cursor dit = from;
653
654         for (; dit; dit.forwardPos()) {
655                 // only until a macro is redefined
656                 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
657                         MathMacroTemplate const & macroTemplate
658                         = static_cast<MathMacroTemplate const &>(dit.inset());
659                         if (macroTemplate.name() == name)
660                                 break;
661                 }
662
663                 // in front of macro instance?
664                 Inset * inset = dit.nextInset();
665                 if (!inset)
666                         continue;
667                 InsetMath * insetMath = inset->asInsetMath();
668                 if (!insetMath)
669                         continue;
670                 MathMacro * macro = insetMath->asMacro();
671                 if (macro && macro->name() == name && macro->folded())
672                         F(macro);
673         }
674 }
675
676
677 void MathMacroTemplate::insertParameter(Cursor & cur, int pos, bool greedy)
678 {
679         if (pos <= numargs_ && pos >= optionals_ && numargs_ < 9) {
680                 ++numargs_;
681                 shiftArguments(pos, 1);
682
683                 // append example #n
684                 cell(defIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
685                 if (!cell(displayIdx()).empty())
686                         cell(displayIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
687
688                 if (!greedy) {
689                         Cursor dit = cur;
690                         dit.leaveInset(*this);
691                         // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
692                         dit.top().forwardPos();
693
694                         // fix macro instances
695                         fixMacroInstancesAddRemove(dit, name(), pos, true);
696                 }
697         }
698
699         updateLook();
700 }
701
702
703 void MathMacroTemplate::removeParameter(Cursor & cur, int pos, bool greedy)
704 {
705         if (pos < numargs_ && pos >= 0) {
706                 --numargs_;
707                 removeArguments(cur, pos, pos);
708                 shiftArguments(pos + 1, -1);
709
710                 // removed optional parameter?
711                 if (pos < optionals_) {
712                         --optionals_;
713                         optionalValues_[pos] = cell(optIdx(pos));
714                         cells_.erase(cells_.begin() + optIdx(pos));
715
716                         // fix cursor
717                         int macroSlice = cur.find(this);
718                         if (macroSlice != -1) {
719                                 if (cur[macroSlice].idx() == optIdx(pos)) {
720                                         cur.cutOff(macroSlice);
721                                         cur[macroSlice].idx() = 1;
722                                         cur[macroSlice].pos() = 0;
723                                 } else if (cur[macroSlice].idx() > optIdx(pos))
724                                         --cur[macroSlice].idx();
725                         }
726                 }
727
728                 if (!greedy) {
729                         // fix macro instances
730                         //boost::function<void(MathMacro *)> fix = _1->insertArgument(n);
731                         //fixMacroInstancesFunctional(dit, name(), fix);
732                         Cursor dit = cur;
733                         dit.leaveInset(*this);
734                         // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
735                         dit.top().forwardPos();
736                         fixMacroInstancesAddRemove(dit, name(), pos, false);
737                 }
738         }
739
740         updateLook();
741 }
742
743
744 void MathMacroTemplate::makeOptional(Cursor & cur) {
745         if (numargs_ > 0 && optionals_ < numargs_) {
746                 ++optionals_;
747                 cells_.insert(cells_.begin() + optIdx(optionals_ - 1), optionalValues_[optionals_ - 1]);
748                 // fix cursor
749                 int macroSlice = cur.find(this);
750                 if (macroSlice != -1 && cur[macroSlice].idx() >= optIdx(optionals_ - 1))
751                         ++cur[macroSlice].idx();
752
753                 // fix macro instances
754                 Cursor dit = cur;
755                 dit.leaveInset(*this);
756                 // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
757                 dit.top().forwardPos();
758                 fixMacroInstancesOptional(dit, name(), optionals_);
759         }
760
761         updateLook();
762 }
763
764
765 void MathMacroTemplate::makeNonOptional(Cursor & cur) {
766         if (numargs_ > 0 && optionals_ > 0) {
767                 --optionals_;
768
769                 // store default value for later if the use changes his mind
770                 optionalValues_[optionals_] = cell(optIdx(optionals_));
771                 cells_.erase(cells_.begin() + optIdx(optionals_));
772
773                 // fix cursor
774                 int macroSlice = cur.find(this);
775                 if (macroSlice != -1) {
776                         if (cur[macroSlice].idx() > optIdx(optionals_))
777                                 --cur[macroSlice].idx();
778                         else if (cur[macroSlice].idx() == optIdx(optionals_)) {
779                                 cur.cutOff(macroSlice);
780                                 cur[macroSlice].idx() = optIdx(optionals_);
781                                 cur[macroSlice].pos() = 0;
782                         }
783                 }
784
785                 // fix macro instances
786                 Cursor dit = cur;
787                 dit.leaveInset(*this);
788                 // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
789                 dit.top().forwardPos();
790                 fixMacroInstancesOptional(dit, name(), optionals_);
791         }
792
793         updateLook();
794 }
795
796
797 void MathMacroTemplate::doDispatch(Cursor & cur, FuncRequest & cmd)
798 {
799         string const arg = to_utf8(cmd.argument());
800         switch (cmd.action) {
801
802         case LFUN_MATH_MACRO_ADD_PARAM:
803                 if (numargs_ < 9) {
804                         cur.recordUndoFullDocument();
805                         size_t pos = numargs_;
806                         if (arg.size() != 0)
807                                 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
808                         insertParameter(cur, pos);
809                 }
810                 break;
811
812
813         case LFUN_MATH_MACRO_REMOVE_PARAM:
814                 if (numargs_ > 0) {
815                         cur.recordUndoFullDocument();
816                         size_t pos = numargs_ - 1;
817                         if (arg.size() != 0)
818                                 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
819                         removeParameter(cur, pos);
820                 }
821                 break;
822
823         case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
824                 if (numargs_ < 9) {
825                         cur.recordUndoFullDocument();
826                         insertParameter(cur, numargs_, true);
827                 }
828                 break;
829
830         case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
831                 if (numargs_ > 0) {
832                         cur.recordUndoFullDocument();
833                         removeParameter(cur, numargs_ - 1, true);
834                 }
835                 break;
836
837         case LFUN_MATH_MACRO_MAKE_OPTIONAL:
838                 cur.recordUndoFullDocument();
839                 makeOptional(cur);
840                 break;
841
842         case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
843                 cur.recordUndoFullDocument();
844                 makeNonOptional(cur);
845                 break;
846
847         case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
848                 if (numargs_ < 9) {
849                         cur.recordUndoFullDocument();
850                         insertParameter(cur, optionals_);
851                         makeOptional(cur);
852                 }
853                 break;
854
855         case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
856                 if (optionals_ > 0) {
857                         cur.recordUndoFullDocument();
858                         removeParameter(cur, optionals_ - 1);
859                 } break;
860
861         case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
862                 if (numargs_ == optionals_) {
863                         cur.recordUndoFullDocument();
864                         insertParameter(cur, 0, true);
865                         makeOptional(cur);
866                 }
867                 break;
868
869         default:
870                 InsetMathNest::doDispatch(cur, cmd);
871                 break;
872         }
873 }
874
875
876 bool MathMacroTemplate::getStatus(Cursor & /*cur*/, FuncRequest const & cmd,
877         FuncStatus & flag) const
878 {
879         bool ret = true;
880         string const arg = to_utf8(cmd.argument());
881         switch (cmd.action) {
882                 case LFUN_MATH_MACRO_ADD_PARAM: {
883                         int num = numargs_ + 1;
884                         if (arg.size() != 0)
885                                 num = convert<int>(arg);
886                         bool on = (num >= optionals_
887                                    && numargs_ < 9 && num <= numargs_ + 1);
888                         flag.enabled(on);
889                         break;
890                 }
891
892                 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
893                         flag.enabled(numargs_ < 9);
894                         break;
895
896                 case LFUN_MATH_MACRO_REMOVE_PARAM: {
897                         int num = numargs_;
898                         if (arg.size() != 0)
899                                 num = convert<int>(arg);
900                         flag.enabled(num >= 1 && num <= numargs_);
901                         break;
902                 }
903
904                 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
905                         flag.enabled(numargs_ > 0
906                                      && optionals_ < numargs_
907                                      && type_ != MacroTypeDef);
908                         break;
909
910                 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
911                         flag.enabled(optionals_ > 0
912                                      && type_ != MacroTypeDef);
913                         break;
914
915                 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
916                         flag.enabled(numargs_ < 9);
917                         break;
918
919                 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
920                         flag.enabled(optionals_ > 0);
921                         break;
922
923                 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
924                         flag.enabled(numargs_ == 0
925                                      && type_ != MacroTypeDef);
926                         break;
927
928                 case LFUN_IN_MATHMACROTEMPLATE:
929                         flag.enabled();
930                         break;
931
932                 default:
933                         ret = false;
934                         break;
935         }
936         return ret;
937 }
938
939
940 void MathMacroTemplate::read(Buffer const &, Lexer & lex)
941 {
942         MathData ar;
943         mathed_parse_cell(ar, lex.getStream());
944         if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
945                 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
946                 lyxerr << "Read: " << to_utf8(asString(ar)) << endl;
947                 return;
948         }
949         operator=( *(ar[0]->asMacroTemplate()) );
950
951         updateLook();
952 }
953
954
955 void MathMacroTemplate::write(Buffer const &, ostream & os) const
956 {
957         odocstringstream oss;
958         WriteStream wi(oss, false, false);
959         oss << "FormulaMacro\n";
960         write(wi);
961         os << to_utf8(oss.str());
962 }
963
964
965 void MathMacroTemplate::write(WriteStream & os) const
966 {
967         write(os, false);
968 }
969
970
971 void MathMacroTemplate::write(WriteStream & os, bool overwriteRedefinition) const
972 {
973         // newcommand or renewcommand
974         if (os.latex() && optionals_ > 1)
975                 os << "\\newlyxcommand";
976         else {
977                 if (redefinition_)
978                         os << "\\renewcommand";
979                 else
980                         os << "\\newcommand";
981         }
982         os << "{\\" << name().c_str() << '}';
983         if (numargs_ > 0)
984                 os << '[' << numargs_ << ']';
985
986         // optional values
987         for (int i = 0; i < optionals_; ++i) {
988                 docstring optValue = asString(cell(optIdx(i)));
989                 if (optValue.find(']') != docstring::npos)
990                         os << "[{" << cell(optIdx(i)) << "}]";
991                 else
992                         os << "[" << cell(optIdx(i)) << "]";
993         }
994
995         os << "{" << cell(defIdx()) << "}";
996
997         if (os.latex()) {
998                 // writing .tex. done.
999                 os << "\n";
1000         } else {
1001                 // writing .lyx, write special .tex export only if necessary
1002                 if (!cell(displayIdx()).empty())
1003                         os << "\n{" << cell(displayIdx()) << '}';
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::getDefaults(vector<docstring> & defaults) const
1075 {
1076         defaults.resize(numargs_);
1077         for (int i = 0; i < optionals_; ++i)
1078                 defaults[i] = asString(cell(optIdx(i)));
1079 }
1080
1081
1082 docstring MathMacroTemplate::definition() const
1083 {
1084         return asString(cell(defIdx()));
1085 }
1086
1087
1088 docstring MathMacroTemplate::displayDefinition() const
1089 {
1090         return asString(cell(displayIdx()));
1091 }
1092
1093
1094 size_t MathMacroTemplate::numArgs() const
1095 {
1096         return numargs_;
1097 }
1098
1099
1100 size_t MathMacroTemplate::numOptionals() const
1101 {
1102         return optionals_;
1103 }
1104
1105
1106 void MathMacroTemplate::infoize(odocstream & os) const
1107 {
1108         os << "Math Macro: \\" << name();
1109 }
1110
1111 } // namespace lyx