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