]> git.lyx.org Git - lyx.git/blob - src/mathed/MathMacroTemplate.cpp
* newlyxcommand support as LaTeX feature
[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         setDimCache(mi, dim);
142 }
143
144
145 void InsetLabelBox::draw(PainterInfo & pi, int x, int y) const
146 {
147         Dimension const dim = dimension(*pi.base.bv);
148         Dimension const cdim = cell(0).dimension(*pi.base.bv);
149
150         // kernel
151         cell(0).draw(pi, x + (dim.wid - cdim.wid) / 2, y);
152
153         // label
154         if (parent_.editing(pi.base.bv) && label_.length() > 0) {
155                 // grey
156                 FontInfo font = sane_font;
157                 font.setSize(FONT_SIZE_TINY);
158                 font.setColor(Color_mathmacrolabel);
159
160                 // make space for label and box
161                 int lwid = mathed_string_width(font, label_);
162                 int maxasc;
163                 int maxdes;
164                 math_font_max_dim(font, maxasc, maxdes);
165
166                 if (lwid < dim.wid)
167                         pi.pain.text(x + (dim.wid - lwid) / 2, y + dim.des - maxdes, label_, font);
168                 else
169                         pi.pain.text(x, y + dim.des - maxdes, label_, font);
170         }
171
172         // draw frame
173         int boxHeight = parent_.commonLabelBoxAscent() + parent_.commonLabelBoxDescent();
174         if (frame_) {
175                 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
176                                   dim.wid - 2, boxHeight - 2,
177                                   Color_mathline);
178         }
179 }
180
181
182 //////////////////////////////////////////////////////////////////////
183
184 class DisplayLabelBox : public InsetLabelBox {
185 public:
186         ///
187         DisplayLabelBox(MathAtom const & atom, docstring label,
188                         MathMacroTemplate const & parent);
189
190         ///
191         void metrics(MetricsInfo & mi, Dimension & dim) const;
192         ///
193         void draw(PainterInfo &, int x, int y) const;
194
195 protected:
196         ///
197         Inset * clone() const;
198 };
199
200
201 DisplayLabelBox::DisplayLabelBox(MathAtom const & atom,
202                                  docstring label,
203                                  MathMacroTemplate const & parent)
204         : InsetLabelBox(atom, label, parent, true)
205 {
206 }
207
208
209
210 Inset * DisplayLabelBox::clone() const
211 {
212         return new DisplayLabelBox(*this);
213 }
214
215
216 void DisplayLabelBox::metrics(MetricsInfo & mi, Dimension & dim) const
217 {
218         InsetLabelBox::metrics(mi, dim);
219         if (!parent_.editing(mi.base.bv)
220             && parent_.cell(parent_.displayIdx()).empty()) {
221                 dim.wid = 0;
222                 dim.asc = 0;
223                 dim.des = 0;
224                 setDimCache(mi, dim);
225         }
226 }
227
228
229 void DisplayLabelBox::draw(PainterInfo & pi, int x, int y) const
230 {
231         if (parent_.editing(pi.base.bv)
232             || !parent_.cell(parent_.displayIdx()).empty()) {
233                 InsetLabelBox::draw(pi, x, y);
234         } else {
235                 bool enabled = pi.pain.isDrawingEnabled();
236                 pi.pain.setDrawingEnabled(false);
237                 InsetLabelBox::draw(pi, x, y);
238                 pi.pain.setDrawingEnabled(enabled);
239         }
240 }
241
242
243 //////////////////////////////////////////////////////////////////////
244
245 class InsetMathWrapper : public InsetMath {
246 public:
247         ///
248         InsetMathWrapper(MathData const * value) : value_(value) {}
249         ///
250         void metrics(MetricsInfo & mi, Dimension & dim) const;
251         ///
252         void draw(PainterInfo &, int x, int y) const;
253
254 private:
255         ///
256         Inset * clone() const;
257         ///
258         MathData const * value_;
259 };
260
261
262 Inset * InsetMathWrapper::clone() const
263 {
264         return new InsetMathWrapper(*this);
265 }
266
267
268 void InsetMathWrapper::metrics(MetricsInfo & mi, Dimension & dim) const
269 {
270         value_->metrics(mi, dim);
271         //metricsMarkers2(dim);
272 }
273
274
275 void InsetMathWrapper::draw(PainterInfo & pi, int x, int y) const
276 {
277         value_->draw(pi, x, y);
278         //drawMarkers(pi, x, y);
279 }
280
281
282 ///////////////////////////////////////////////////////////////////////
283
284 class InsetNameWrapper : public InsetMathWrapper {
285 public:
286         ///
287         InsetNameWrapper(MathData const * value, MathMacroTemplate const & parent);
288         ///
289         void metrics(MetricsInfo & mi, Dimension & dim) const;
290         ///
291         void draw(PainterInfo &, int x, int y) const;
292
293 private:
294         ///
295         MathMacroTemplate const & parent_;
296         ///
297         Inset * clone() const;
298 };
299
300
301 InsetNameWrapper::InsetNameWrapper(MathData const * value,
302                                    MathMacroTemplate const & parent)
303         : InsetMathWrapper(value), parent_(parent)
304 {
305 }
306
307
308 Inset * InsetNameWrapper::clone() const
309 {
310         return new InsetNameWrapper(*this);
311 }
312
313
314 void InsetNameWrapper::metrics(MetricsInfo & mi, Dimension & dim) const
315 {
316         InsetMathWrapper::metrics(mi, dim);
317         dim.wid += mathed_string_width(mi.base.font, from_ascii("\\"));
318 }
319
320
321 void InsetNameWrapper::draw(PainterInfo & pi, int x, int y) const
322 {
323         // create fonts
324         PainterInfo namepi = pi;
325         if (parent_.validMacro())
326                 namepi.base.font.setColor(Color_latex);
327         else
328                 namepi.base.font.setColor(Color_error);
329
330         // draw backslash
331         pi.pain.text(x, y, from_ascii("\\"), namepi.base.font);
332         x += mathed_string_width(namepi.base.font, from_ascii("\\"));
333
334         // draw name
335         InsetMathWrapper::draw(namepi, x, y);
336 }
337
338
339 ///////////////////////////////////////////////////////////////////////
340
341
342 MathMacroTemplate::MathMacroTemplate()
343         : InsetMathNest(3), numargs_(0), optionals_(0),
344           type_(MacroTypeNewcommand), lookOutdated_(true)
345 {
346         initMath();
347 }
348
349
350 MathMacroTemplate::MathMacroTemplate(docstring const & name, int numargs,
351         int optionals, MacroType type,
352         vector<MathData> const & optionalValues,
353         MathData const & def, MathData const & display)
354         : InsetMathNest(optionals + 3), numargs_(numargs),
355           optionals_(optionals), optionalValues_(optionalValues),
356           type_(type), lookOutdated_(true)
357 {
358         initMath();
359
360         if (numargs_ > 9)
361                 lyxerr << "MathMacroTemplate::MathMacroTemplate: wrong # of arguments: "
362                         << numargs_ << endl;
363
364         asArray(name, cell(0));
365         optionalValues_.resize(9);
366         for (int i = 0; i < optionals_; ++i)
367                 cell(optIdx(i)) = optionalValues_[i];
368         cell(defIdx()) = def;
369         cell(displayIdx()) = display;
370
371         updateLook();
372 }
373
374
375 MathMacroTemplate::MathMacroTemplate(docstring const & str)
376         : InsetMathNest(3), numargs_(0), optionals_(0),
377         type_(MacroTypeNewcommand), lookOutdated_(true)
378 {
379         initMath();
380
381         MathData ar;
382         mathed_parse_cell(ar, str);
383         if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
384                 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
385                 asArray(from_ascii("invalidmacro"), cell(0));
386                 // FIXME: The macro template does not make sense after this.
387                 // The whole parsing should not be in a constructor which
388                 // has no chance to report failure.
389                 return;
390         }
391         operator=( *(ar[0]->asMacroTemplate()) );
392
393         updateLook();
394 }
395
396
397 Inset * MathMacroTemplate::clone() const
398 {
399         return new MathMacroTemplate(*this);
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 left)
536 {
537         updateLook();
538         cur.updateFlags(Update::Force);
539         InsetMathNest::edit(cur, left);
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_)
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 int MathMacroTemplate::plaintext(Buffer const & buf, odocstream & os,
1009                                  OutputParams const &) const
1010 {
1011         static docstring const str = '[' + buf.B_("math macro") + ']';
1012
1013         os << str;
1014         return str.size();
1015 }
1016
1017
1018 bool MathMacroTemplate::validName() const
1019 {
1020         docstring n = name();
1021
1022         // empty name?
1023         if (n.size() == 0)
1024                 return false;
1025
1026         // converting back and force doesn't swallow anything?
1027         /*MathData ma;
1028         asArray(n, ma);
1029         if (asString(ma) != n)
1030                 return false;*/
1031
1032         // valid characters?
1033         for (size_t i = 0; i < n.size(); ++i) {
1034                 if (!(n[i] >= 'a' && n[i] <= 'z') &&
1035                                 !(n[i] >= 'A' && n[i] <= 'Z'))
1036                         return false;
1037         }
1038
1039         return true;
1040 }
1041
1042
1043 bool MathMacroTemplate::validMacro() const
1044 {
1045         return validName();
1046 }
1047
1048
1049 bool MathMacroTemplate::fixNameAndCheckIfValid()
1050 {
1051         // check all the characters/insets in the name cell
1052         size_t i = 0;
1053         MathData & data = cell(0);
1054         while (i < data.size()) {
1055                 InsetMathChar const * cinset = data[i]->asCharInset();
1056                 if (cinset) {
1057                         // valid character in [a-zA-Z]?
1058                         char_type c = cinset->getChar();
1059                         if ((c >= 'a' && c <= 'z')
1060                             || (c >= 'A' && c <= 'Z')) {
1061                                 ++i;
1062                                 continue;
1063                         }
1064                 }
1065
1066                 // throw cell away
1067                 data.erase(i);
1068         }
1069
1070         // now it should be valid if anything in the name survived
1071         return data.size() > 0;
1072 }
1073
1074         
1075 void MathMacroTemplate::validate(LaTeXFeatures & features) const
1076 {
1077         if (optionals_ > 1) {
1078                 features.require("newlyxcommand");
1079         }
1080 }
1081
1082 void MathMacroTemplate::getDefaults(vector<docstring> & defaults) const
1083 {
1084         defaults.resize(numargs_);
1085         for (int i = 0; i < optionals_; ++i)
1086                 defaults[i] = asString(cell(optIdx(i)));
1087 }
1088
1089
1090 docstring MathMacroTemplate::definition() const
1091 {
1092         return asString(cell(defIdx()));
1093 }
1094
1095
1096 docstring MathMacroTemplate::displayDefinition() const
1097 {
1098         return asString(cell(displayIdx()));
1099 }
1100
1101
1102 size_t MathMacroTemplate::numArgs() const
1103 {
1104         return numargs_;
1105 }
1106
1107
1108 size_t MathMacroTemplate::numOptionals() const
1109 {
1110         return optionals_;
1111 }
1112
1113
1114 void MathMacroTemplate::infoize(odocstream & os) const
1115 {
1116         os << "Math Macro: \\" << name();
1117 }
1118
1119 } // namespace lyx