]> git.lyx.org Git - lyx.git/blob - src/mathed/MathMacroTemplate.cpp
fc5e57a5e4baf2617677c9a24906a1a98c6e7786
[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  * \author Stefan Schimanski
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "MathMacroTemplate.h"
15
16 #include "DocIterator.h"
17 #include "LaTeXFeatures.h"
18 #include "InsetMathBrace.h"
19 #include "InsetMathChar.h"
20 #include "InsetMathSqrt.h"
21 #include "MathMacro.h"
22 #include "MathMacroArgument.h"
23 #include "MathStream.h"
24 #include "MathParser.h"
25 #include "MathSupport.h"
26 #include "MathMacroArgument.h"
27
28 #include "Buffer.h"
29 #include "BufferView.h"
30 #include "Color.h"
31 #include "Cursor.h"
32 #include "DispatchResult.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "Lexer.h"
36 #include "Undo.h"
37
38 #include "frontends/Painter.h"
39
40 #include "support/lassert.h"
41 #include "support/convert.h"
42 #include "support/debug.h"
43 #include "support/gettext.h"
44 #include "support/docstream.h"
45 #include "support/lstrings.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 class InsetColoredCell : public InsetMathNest {
280 public:
281         ///
282         InsetColoredCell(ColorCode min, ColorCode max);
283         ///
284         InsetColoredCell(ColorCode min, ColorCode max, MathAtom const & atom);
285         ///
286         void draw(PainterInfo &, int x, int y) const;
287         ///
288         void metrics(MetricsInfo & mi, Dimension & dim) const;
289
290 protected:
291         ///
292         Inset * clone() const;
293         ///
294         ColorCode min_;
295         ///
296         ColorCode max_;
297 };
298
299
300 InsetColoredCell::InsetColoredCell(ColorCode min, ColorCode max)
301         : InsetMathNest(1), min_(min), max_(max)
302 {
303 }
304
305
306 InsetColoredCell::InsetColoredCell(ColorCode min, ColorCode max, MathAtom const & atom)
307         : InsetMathNest(1), min_(min), max_(max)
308 {
309         cell(0).insert(0, atom);
310 }
311
312
313 Inset * InsetColoredCell::clone() const
314 {
315         return new InsetColoredCell(*this);
316 }
317
318
319 void InsetColoredCell::metrics(MetricsInfo & mi, Dimension & dim) const
320 {
321         cell(0).metrics(mi, dim);
322 }
323
324
325 void InsetColoredCell::draw(PainterInfo & pi, int x, int y) const
326 {
327         pi.pain.enterMonochromeMode(min_, max_);
328         cell(0).draw(pi, x, y);
329         pi.pain.leaveMonochromeMode();
330 }
331
332
333 ///////////////////////////////////////////////////////////////////////
334
335 class InsetNameWrapper : public InsetMathWrapper {
336 public:
337         ///
338         InsetNameWrapper(MathData const * value, MathMacroTemplate const & parent);
339         ///
340         void metrics(MetricsInfo & mi, Dimension & dim) const;
341         ///
342         void draw(PainterInfo &, int x, int y) const;
343
344 private:
345         ///
346         MathMacroTemplate const & parent_;
347         ///
348         Inset * clone() const;
349 };
350
351
352 InsetNameWrapper::InsetNameWrapper(MathData const * value,
353                                    MathMacroTemplate const & parent)
354         : InsetMathWrapper(value), parent_(parent)
355 {
356 }
357
358
359 Inset * InsetNameWrapper::clone() const
360 {
361         return new InsetNameWrapper(*this);
362 }
363
364
365 void InsetNameWrapper::metrics(MetricsInfo & mi, Dimension & dim) const
366 {
367         InsetMathWrapper::metrics(mi, dim);
368         dim.wid += mathed_string_width(mi.base.font, from_ascii("\\"));
369 }
370
371
372 void InsetNameWrapper::draw(PainterInfo & pi, int x, int y) const
373 {
374         // create fonts
375         PainterInfo namepi = pi;
376         if (parent_.validMacro())
377                 namepi.base.font.setColor(Color_latex);
378         else
379                 namepi.base.font.setColor(Color_error);
380
381         // draw backslash
382         pi.pain.text(x, y, from_ascii("\\"), namepi.base.font);
383         x += mathed_string_width(namepi.base.font, from_ascii("\\"));
384
385         // draw name
386         InsetMathWrapper::draw(namepi, x, y);
387 }
388
389
390 ///////////////////////////////////////////////////////////////////////
391
392
393 MathMacroTemplate::MathMacroTemplate(Buffer * buf)
394         : InsetMathNest(3), numargs_(0), argsInLook_(0), optionals_(0),
395           type_(MacroTypeNewcommand), lookOutdated_(true)
396 {
397         buffer_ = buf;
398         initMath();
399 }
400
401
402 MathMacroTemplate::MathMacroTemplate(docstring const & name, int numargs,
403         int optionals, MacroType type, Buffer * buf,
404         vector<MathData> const & optionalValues,
405         MathData const & def, MathData const & display)
406         : InsetMathNest(optionals + 3), numargs_(numargs), argsInLook_(numargs),
407           optionals_(optionals), optionalValues_(optionalValues),
408           type_(type), lookOutdated_(true)
409 {
410         buffer_ = buf;
411         initMath();
412
413         if (numargs_ > 9)
414                 lyxerr << "MathMacroTemplate::MathMacroTemplate: wrong # of arguments: "
415                         << numargs_ << endl;
416
417         asArray(name, cell(0));
418         optionalValues_.resize(9);
419         for (int i = 0; i < optionals_; ++i)
420                 cell(optIdx(i)) = optionalValues_[i];
421         cell(defIdx()) = def;
422         cell(displayIdx()) = display;
423
424         updateLook();
425 }
426
427
428 MathMacroTemplate::MathMacroTemplate(docstring const & str, Buffer * buf)
429         : InsetMathNest(3), numargs_(0), optionals_(0),
430         type_(MacroTypeNewcommand), lookOutdated_(true)
431 {
432         buffer_ = buf;
433         initMath();
434
435         MathData ar;
436         mathed_parse_cell(ar, str, Parse::NORMAL, buf);
437         if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
438                 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
439                 asArray(from_ascii("invalidmacro"), cell(0));
440                 // FIXME: The macro template does not make sense after this.
441                 // The whole parsing should not be in a constructor which
442                 // has no chance to report failure.
443                 return;
444         }
445         operator=( *(ar[0]->asMacroTemplate()) );
446
447         updateLook();
448 }
449
450
451 Inset * MathMacroTemplate::clone() const
452 {
453         MathMacroTemplate * inset = new MathMacroTemplate(*this);
454         // the parent pointers of the proxy insets above will point to
455         // to the old template. Hence, the look must be updated.
456         inset->updateLook();
457         return inset;
458 }
459
460
461 docstring MathMacroTemplate::name() const
462 {
463         return asString(cell(0));
464 }
465
466
467 void MathMacroTemplate::updateToContext(MacroContext const & mc) const
468 {
469         redefinition_ = mc.get(name()) != 0;
470 }
471
472
473 void MathMacroTemplate::updateLook() const
474 {
475         lookOutdated_ = true;
476 }
477
478
479 void MathMacroTemplate::createLook(int args) const
480 {
481         look_.clear();
482         argsInLook_ = args;
483
484         // \foo
485         look_.push_back(MathAtom(new InsetLabelBox(_("Name"), *this, false)));
486         MathData & nameData = look_[look_.size() - 1].nucleus()->cell(0);
487         nameData.push_back(MathAtom(new InsetNameWrapper(&cell(0), *this)));
488
489         // [#1][#2]
490         int i = 0;
491         if (optionals_ > 0) {
492                 look_.push_back(MathAtom(new InsetLabelBox(_("optional"), *this, false)));
493                 
494                 MathData * optData = &look_[look_.size() - 1].nucleus()->cell(0);
495                 for (; i < optionals_; ++i) {
496                         // color it light grey, if it is to be removed when the cursor leaves
497                         if (i == argsInLook_) {
498                                 optData->push_back(MathAtom(
499                                         new InsetColoredCell(Color_mathbg, Color_mathmacrooldarg)));
500                                 optData = &(*optData)[optData->size() - 1].nucleus()->cell(0);
501                         }
502
503                         optData->push_back(MathAtom(new InsetMathChar('[')));
504                         optData->push_back(MathAtom(new InsetMathWrapper(&cell(1 + i))));
505                         optData->push_back(MathAtom(new InsetMathChar(']')));
506                 }
507         }
508
509         // {#3}{#4}
510         for (; i < numargs_; ++i) {
511                 MathData arg;
512                 arg.push_back(MathAtom(new MathMacroArgument(i + 1)));
513                 if (i >= argsInLook_) {
514                         look_.push_back(MathAtom(new InsetColoredCell(
515                                 Color_mathbg, Color_mathmacrooldarg,
516                                 MathAtom(new InsetMathBrace(arg)))));
517                 } else
518                         look_.push_back(MathAtom(new InsetMathBrace(arg)));
519         }
520         for (; i < argsInLook_; ++i) {
521                 MathData arg;
522                 arg.push_back(MathAtom(new MathMacroArgument(i + 1)));
523                 look_.push_back(MathAtom(new InsetColoredCell(
524                         Color_mathbg, Color_mathmacronewarg,
525                         MathAtom(new InsetMathBrace(arg)))));
526         }
527         
528         // :=
529         look_.push_back(MathAtom(new InsetMathChar(':')));
530         look_.push_back(MathAtom(new InsetMathChar('=')));
531
532         // definition
533         look_.push_back(MathAtom(
534                 new InsetLabelBox(MathAtom(
535                         new InsetMathWrapper(&cell(defIdx()))), _("TeX"), *this,        true)));
536
537         // display
538         look_.push_back(MathAtom(
539                 new DisplayLabelBox(MathAtom(
540                         new InsetMathWrapper(&cell(displayIdx()))), _("LyX"), *this)));
541 }
542
543
544 void MathMacroTemplate::metrics(MetricsInfo & mi, Dimension & dim) const
545 {
546         FontSetChanger dummy1(mi.base, from_ascii("mathnormal"));
547         StyleChanger dummy2(mi.base, LM_ST_TEXT);
548
549         // valid macro?
550         MacroData const * macro = 0;
551         if (validName()) {
552                 macro = mi.macrocontext.get(name());
553
554                 // updateToContext() - avoids another lookup
555                 redefinition_ = macro != 0;
556         }
557
558         // update look?
559         int argsInDef = maxArgumentInDefinition();
560         if (lookOutdated_ || argsInDef != argsInLook_) {
561                 lookOutdated_ = false;
562                 createLook(argsInDef);
563         }
564
565         /// metrics for inset contents
566         if (macro)
567                 macro->lock();
568
569         // first phase, premetric:
570         premetrics_ = true;
571         look_.metrics(mi, dim);
572         labelBoxAscent_ = dim.asc;
573         labelBoxDescent_ = dim.des;
574
575         // second phase, main metric:
576         premetrics_ = false;
577         look_.metrics(mi, dim);
578
579         if (macro)
580                 macro->unlock();
581
582         dim.wid += 6;
583         dim.des += 2;
584         dim.asc += 2;
585
586         setDimCache(mi, dim);
587 }
588
589
590 void MathMacroTemplate::draw(PainterInfo & pi, int x, int y) const
591 {
592         FontSetChanger dummy1(pi.base, from_ascii("mathnormal"));
593         StyleChanger dummy2(pi.base, LM_ST_TEXT);
594
595         setPosCache(pi, x, y);
596         Dimension const dim = dimension(*pi.base.bv);
597
598         // draw outer frame
599         int const a = y - dim.asc + 1;
600         int const w = dim.wid - 2;
601         int const h = dim.height() - 2;
602         pi.pain.rectangle(x, a, w, h, Color_mathframe);
603
604         // just to be sure: set some dummy values for coord cache
605         for (idx_type i = 0; i < nargs(); ++i)
606                 cell(i).setXY(*pi.base.bv, x, y);
607
608         // draw contents
609         look_.draw(pi, x + 3, y);
610 }
611
612
613 void MathMacroTemplate::edit(Cursor & cur, bool front, EntryDirection entry_from)
614 {
615         updateLook();
616         cur.updateFlags(Update::SinglePar);
617         InsetMathNest::edit(cur, front, entry_from);
618 }
619
620
621 bool MathMacroTemplate::notifyCursorLeaves(Cursor const & old, Cursor & cur)
622 {
623         // find this in cursor old
624         Cursor insetCur = old;
625         int scriptSlice = insetCur.find(this);
626         LASSERT(scriptSlice != -1, /**/);
627         insetCur.cutOff(scriptSlice);
628         
629         commitEditChanges(insetCur);
630         updateLook();
631         cur.updateFlags(Update::Force);
632         return InsetMathNest::notifyCursorLeaves(old, cur);
633 }
634
635
636 void MathMacroTemplate::removeArguments(Cursor & cur, int from, int to)
637 {
638         for (DocIterator it = doc_iterator_begin(&buffer(), this); it; it.forwardChar()) {
639                 if (!it.nextInset())
640                         continue;
641                 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
642                         continue;
643                 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
644                 int n = arg->number() - 1;
645                 if (from <= n && n <= to) {
646                         int cellSlice = cur.find(it.cell());
647                         if (cellSlice != -1 && cur[cellSlice].pos() > it.pos())
648                                 --cur[cellSlice].pos();
649
650                         it.cell().erase(it.pos());
651                 }
652         }
653
654         updateLook();
655 }
656
657
658 void MathMacroTemplate::shiftArguments(size_t from, int by)
659 {
660         for (DocIterator it = doc_iterator_begin(&buffer(), this); it; it.forwardChar()) {
661                 if (!it.nextInset())
662                         continue;
663                 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
664                         continue;
665                 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
666                 if (arg->number() >= int(from) + 1)
667                         arg->setNumber(arg->number() + by);
668         }
669
670         updateLook();
671 }
672
673
674 int MathMacroTemplate::maxArgumentInDefinition() const
675 {
676         // We don't have a buffer when pasting from the clipboard (bug 6014).
677         Buffer const * macro_buffer = this->isBufferValid() ? &buffer() : 0;
678         int maxArg = 0;
679         DocIterator it = doc_iterator_begin(macro_buffer, this);
680         it.idx() = defIdx();
681         for (; it; it.forwardChar()) {
682                 if (!it.nextInset())
683                         continue;
684                 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
685                         continue;
686                 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
687                 maxArg = std::max(int(arg->number()), maxArg);
688         }
689         return maxArg;
690 }
691
692
693 void MathMacroTemplate::insertMissingArguments(int maxArg)
694 {
695         bool found[9] = { false, false, false, false, false, false, false, false, false };
696         idx_type idx = cell(displayIdx()).empty() ? defIdx() : displayIdx();
697
698         // search for #n macros arguments
699         DocIterator it = doc_iterator_begin(&buffer(), this);
700         it.idx() = idx;
701         for (; it && it[0].idx() == idx; it.forwardChar()) {
702                 if (!it.nextInset())
703                         continue;
704                 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
705                         continue;
706                 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
707                 found[arg->number() - 1] = true;
708         }
709
710         // add missing ones
711         for (int i = 0; i < maxArg; ++i) {
712                 if (found[i])
713                         continue;
714
715                 cell(idx).push_back(MathAtom(new MathMacroArgument(i + 1)));
716         }
717 }
718
719
720 void MathMacroTemplate::changeArity(Cursor & cur, int newNumArg)
721 {
722         // remove parameter which do not appear anymore in the definition
723         for (int i = numargs_; i > newNumArg; --i)
724                 removeParameter(cur, numargs_ - 1, false);
725         
726         // add missing parameter
727         for (int i = numargs_; i < newNumArg; ++i)
728                 insertParameter(cur, numargs_, false, false);
729 }
730
731
732 void MathMacroTemplate::commitEditChanges(Cursor & cur)
733 {
734         int argsInDef = maxArgumentInDefinition();
735         if (argsInDef != numargs_) {
736                 cur.recordUndoFullDocument();
737                 changeArity(cur, argsInDef);
738         }
739         insertMissingArguments(argsInDef);
740 }
741
742
743 // FIXME: factorize those functions here with a functional style, maybe using Boost's function
744 // objects?
745
746 void fixMacroInstancesAddRemove(Cursor const & from, docstring const & name, int n, bool insert) {
747         Cursor dit = from;
748
749         for (; dit; dit.forwardPos()) {
750                 // only until a macro is redefined
751                 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
752                         MathMacroTemplate const & macroTemplate
753                         = static_cast<MathMacroTemplate const &>(dit.inset());
754                         if (macroTemplate.name() == name)
755                                 break;
756                 }
757
758                 // in front of macro instance?
759                 Inset * inset = dit.nextInset();
760                 if (!inset)
761                         continue;
762                 InsetMath * insetMath = inset->asInsetMath();
763                 if (!insetMath)
764                         continue;
765
766                 MathMacro * macro = insetMath->asMacro();
767                 if (macro && macro->name() == name && macro->folded()) {
768                         // found macro instance
769                         if (insert)
770                                 macro->insertArgument(n);
771                         else
772                                 macro->removeArgument(n);
773                 }
774         }
775 }
776
777
778 void fixMacroInstancesOptional(Cursor const & from, docstring const & name, int optionals) {
779         Cursor dit = from;
780
781         for (; dit; dit.forwardPos()) {
782                 // only until a macro is redefined
783                 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
784                         MathMacroTemplate const & macroTemplate
785                         = static_cast<MathMacroTemplate const &>(dit.inset());
786                         if (macroTemplate.name() == name)
787                                 break;
788                 }
789
790                 // in front of macro instance?
791                 Inset * inset = dit.nextInset();
792                 if (!inset)
793                         continue;
794                 InsetMath * insetMath = inset->asInsetMath();
795                 if (!insetMath)
796                         continue;
797                 MathMacro * macro = insetMath->asMacro();
798                 if (macro && macro->name() == name && macro->folded()) {
799                         // found macro instance
800                         macro->setOptionals(optionals);
801                 }
802         }
803 }
804
805
806 template<class F>
807 void fixMacroInstancesFunctional(Cursor const & from,
808         docstring const & name, F & fix) {
809         Cursor dit = from;
810
811         for (; dit; dit.forwardPos()) {
812                 // only until a macro is redefined
813                 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
814                         MathMacroTemplate const & macroTemplate
815                         = static_cast<MathMacroTemplate const &>(dit.inset());
816                         if (macroTemplate.name() == name)
817                                 break;
818                 }
819
820                 // in front of macro instance?
821                 Inset * inset = dit.nextInset();
822                 if (!inset)
823                         continue;
824                 InsetMath * insetMath = inset->asInsetMath();
825                 if (!insetMath)
826                         continue;
827                 MathMacro * macro = insetMath->asMacro();
828                 if (macro && macro->name() == name && macro->folded())
829                         F(macro);
830         }
831 }
832
833
834 void MathMacroTemplate::insertParameter(Cursor & cur, int pos, bool greedy, bool addarg)
835 {
836         if (pos <= numargs_ && pos >= optionals_ && numargs_ < 9) {
837                 ++numargs_;
838                 
839                 // append example #n
840                 if (addarg) {
841                         shiftArguments(pos, 1);
842
843                         cell(defIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
844                         if (!cell(displayIdx()).empty())
845                                 cell(displayIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
846                 }
847
848                 if (!greedy) {
849                         Cursor dit = cur;
850                         dit.leaveInset(*this);
851                         // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
852                         dit.top().forwardPos();
853
854                         // fix macro instances
855                         fixMacroInstancesAddRemove(dit, name(), pos, true);
856                 }
857         }
858
859         updateLook();
860 }
861
862
863 void MathMacroTemplate::removeParameter(Cursor & cur, int pos, bool greedy)
864 {
865         if (pos < numargs_ && pos >= 0) {
866                 --numargs_;
867                 removeArguments(cur, pos, pos);
868                 shiftArguments(pos + 1, -1);
869
870                 // removed optional parameter?
871                 if (pos < optionals_) {
872                         --optionals_;
873                         optionalValues_[pos] = cell(optIdx(pos));
874                         cells_.erase(cells_.begin() + optIdx(pos));
875
876                         // fix cursor
877                         int macroSlice = cur.find(this);
878                         if (macroSlice != -1) {
879                                 if (cur[macroSlice].idx() == optIdx(pos)) {
880                                         cur.cutOff(macroSlice);
881                                         cur[macroSlice].idx() = 1;
882                                         cur[macroSlice].pos() = 0;
883                                 } else if (cur[macroSlice].idx() > optIdx(pos))
884                                         --cur[macroSlice].idx();
885                         }
886                 }
887
888                 if (!greedy) {
889                         // fix macro instances
890                         //boost::function<void(MathMacro *)> fix = _1->insertArgument(n);
891                         //fixMacroInstancesFunctional(dit, name(), fix);
892                         Cursor dit = cur;
893                         dit.leaveInset(*this);
894                         // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
895                         dit.top().forwardPos();
896                         fixMacroInstancesAddRemove(dit, name(), pos, false);
897                 }
898         }
899
900         updateLook();
901 }
902
903
904 void MathMacroTemplate::makeOptional(Cursor & cur) {
905         if (numargs_ > 0 && optionals_ < numargs_) {
906                 ++optionals_;
907                 cells_.insert(cells_.begin() + optIdx(optionals_ - 1), optionalValues_[optionals_ - 1]);
908                 // fix cursor
909                 int macroSlice = cur.find(this);
910                 if (macroSlice != -1 && cur[macroSlice].idx() >= optIdx(optionals_ - 1))
911                         ++cur[macroSlice].idx();
912
913                 // fix macro instances
914                 Cursor dit = cur;
915                 dit.leaveInset(*this);
916                 // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
917                 dit.top().forwardPos();
918                 fixMacroInstancesOptional(dit, name(), optionals_);
919         }
920
921         updateLook();
922 }
923
924
925 void MathMacroTemplate::makeNonOptional(Cursor & cur) {
926         if (numargs_ > 0 && optionals_ > 0) {
927                 --optionals_;
928
929                 // store default value for later if the user changes his mind
930                 optionalValues_[optionals_] = cell(optIdx(optionals_));
931                 cells_.erase(cells_.begin() + optIdx(optionals_));
932
933                 // fix cursor
934                 int macroSlice = cur.find(this);
935                 if (macroSlice != -1) {
936                         if (cur[macroSlice].idx() > optIdx(optionals_))
937                                 --cur[macroSlice].idx();
938                         else if (cur[macroSlice].idx() == optIdx(optionals_)) {
939                                 cur.cutOff(macroSlice);
940                                 cur[macroSlice].idx() = optIdx(optionals_);
941                                 cur[macroSlice].pos() = 0;
942                         }
943                 }
944
945                 // fix macro instances
946                 Cursor dit = cur;
947                 dit.leaveInset(*this);
948                 // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
949                 dit.top().forwardPos();
950                 fixMacroInstancesOptional(dit, name(), optionals_);
951         }
952
953         updateLook();
954 }
955
956
957 void MathMacroTemplate::doDispatch(Cursor & cur, FuncRequest & cmd)
958 {
959         string const arg = to_utf8(cmd.argument());
960         switch (cmd.action) {
961
962         case LFUN_MATH_MACRO_ADD_PARAM:
963                 if (numargs_ < 9) {
964                         commitEditChanges(cur);
965                         cur.recordUndoFullDocument();
966                         size_t pos = numargs_;
967                         if (arg.size() != 0)
968                                 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
969                         insertParameter(cur, pos);
970                 }
971                 break;
972
973
974         case LFUN_MATH_MACRO_REMOVE_PARAM:
975                 if (numargs_ > 0) {
976                         commitEditChanges(cur);
977                         cur.recordUndoFullDocument();
978                         size_t pos = numargs_ - 1;
979                         if (arg.size() != 0)
980                                 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
981                         removeParameter(cur, pos);
982                 }
983                 break;
984
985         case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
986                 if (numargs_ < 9) {
987                         commitEditChanges(cur);
988                         cur.recordUndoFullDocument();
989                         insertParameter(cur, numargs_, true);
990                 }
991                 break;
992
993         case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
994                 if (numargs_ > 0) {
995                         commitEditChanges(cur);
996                         cur.recordUndoFullDocument();
997                         removeParameter(cur, numargs_ - 1, true);
998                 }
999                 break;
1000
1001         case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1002                 commitEditChanges(cur);
1003                 cur.recordUndoFullDocument();
1004                 makeOptional(cur);
1005                 break;
1006
1007         case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1008                 commitEditChanges(cur);
1009                 cur.recordUndoFullDocument();
1010                 makeNonOptional(cur);
1011                 break;
1012
1013         case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1014                 if (numargs_ < 9) {
1015                         commitEditChanges(cur);
1016                         cur.recordUndoFullDocument();
1017                         insertParameter(cur, optionals_);
1018                         makeOptional(cur);
1019                 }
1020                 break;
1021
1022         case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1023                 if (optionals_ > 0) {
1024                         commitEditChanges(cur);
1025                         cur.recordUndoFullDocument();
1026                         removeParameter(cur, optionals_ - 1);
1027                 } break;
1028
1029         case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1030                 if (numargs_ == optionals_) {
1031                         commitEditChanges(cur);
1032                         cur.recordUndoFullDocument();
1033                         insertParameter(cur, 0, true);
1034                         makeOptional(cur);
1035                 }
1036                 break;
1037
1038         default:
1039                 InsetMathNest::doDispatch(cur, cmd);
1040                 break;
1041         }
1042 }
1043
1044
1045 bool MathMacroTemplate::getStatus(Cursor & /*cur*/, FuncRequest const & cmd,
1046         FuncStatus & flag) const
1047 {
1048         bool ret = true;
1049         string const arg = to_utf8(cmd.argument());
1050         switch (cmd.action) {
1051                 case LFUN_MATH_MACRO_ADD_PARAM: {
1052                         int num = numargs_ + 1;
1053                         if (arg.size() != 0)
1054                                 num = convert<int>(arg);
1055                         bool on = (num >= optionals_
1056                                    && numargs_ < 9 && num <= numargs_ + 1);
1057                         flag.setEnabled(on);
1058                         break;
1059                 }
1060
1061                 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
1062                         flag.setEnabled(numargs_ < 9);
1063                         break;
1064
1065                 case LFUN_MATH_MACRO_REMOVE_PARAM: {
1066                         int num = numargs_;
1067                         if (arg.size() != 0)
1068                                 num = convert<int>(arg);
1069                         flag.setEnabled(num >= 1 && num <= numargs_);
1070                         break;
1071                 }
1072
1073                 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1074                         flag.setEnabled(numargs_ > 0
1075                                      && optionals_ < numargs_
1076                                      && type_ != MacroTypeDef);
1077                         break;
1078
1079                 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1080                         flag.setEnabled(optionals_ > 0
1081                                      && type_ != MacroTypeDef);
1082                         break;
1083
1084                 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1085                         flag.setEnabled(numargs_ < 9);
1086                         break;
1087
1088                 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1089                         flag.setEnabled(optionals_ > 0);
1090                         break;
1091
1092                 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1093                         flag.setEnabled(numargs_ == 0
1094                                      && type_ != MacroTypeDef);
1095                         break;
1096
1097                 case LFUN_IN_MATHMACROTEMPLATE:
1098                         flag.setEnabled(true);
1099                         break;
1100
1101                 default:
1102                         ret = false;
1103                         break;
1104         }
1105         return ret;
1106 }
1107
1108
1109 void MathMacroTemplate::read(Lexer & lex)
1110 {
1111         MathData ar;
1112         mathed_parse_cell(ar, lex.getStream(), Parse::NORMAL, &buffer());
1113         if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
1114                 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
1115                 lyxerr << "Read: " << to_utf8(asString(ar)) << endl;
1116                 return;
1117         }
1118         operator=( *(ar[0]->asMacroTemplate()) );
1119
1120         updateLook();
1121 }
1122
1123
1124 void MathMacroTemplate::write(ostream & os) const
1125 {
1126         odocstringstream oss;
1127         WriteStream wi(oss, false, false, WriteStream::wsDefault);
1128         oss << "FormulaMacro\n";
1129         write(wi);
1130         os << to_utf8(oss.str());
1131 }
1132
1133
1134 void MathMacroTemplate::write(WriteStream & os) const
1135 {
1136         write(os, false);
1137 }
1138
1139
1140 void MathMacroTemplate::write(WriteStream & os, bool overwriteRedefinition) const
1141 {
1142         if (os.latex()) {
1143                 if (optionals_ > 0) {
1144                         // macros with optionals use the xargs package, e.g.:
1145                         // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
1146                         // \long is implicit by xargs
1147                         if (redefinition_ && !overwriteRedefinition)
1148                                 os << "\\renewcommandx";
1149                         else
1150                                 os << "\\newcommandx";
1151
1152                         os << "\\" << name()
1153                            << "[" << numargs_ << "]"
1154                            << "[usedefault, addprefix=\\global";
1155                         for (int i = 0; i < optionals_; ++i) {
1156                                 docstring optValue = asString(cell(optIdx(i)));
1157                                 if (optValue.find(']') != docstring::npos
1158                                     || optValue.find(',') != docstring::npos)
1159                                         os << ", " << i + 1 << "="
1160                                         << "{" << cell(optIdx(i)) << "}";
1161                                 else
1162                                         os << ", " << i + 1 << "="
1163                                         << cell(optIdx(i));
1164                         }
1165                         os << "]";
1166                 } else {
1167                         // Macros without optionals use standard _global_ \def macros:
1168                         //   \global\def\long\foo#1#2{#1,#2}
1169                         // We use the \long prefix as this is the equivalent to \newcommand.
1170                         // We cannot use \newcommand directly because \global does not work with it.
1171                         os << "\\global\\long\\def\\" << name();
1172                         docstring param = from_ascii("#0");
1173                         for (int i = 1; i <= numargs_; ++i) { 
1174                                 param[1] = '0' + i;
1175                                 os << param;
1176                         }
1177                 }
1178         } else {
1179                 // in LyX output we use some pseudo syntax which is implementation
1180                 // independent, e.g.
1181                 // \newcommand{\foo}[2][default]{#1,#2}
1182                 if (redefinition_ && !overwriteRedefinition)
1183                         os << "\\renewcommand";
1184                 else
1185                         os << "\\newcommand";
1186                 os << "{\\" << name() << '}';
1187                 if (numargs_ > 0)
1188                         os << '[' << numargs_ << ']';
1189
1190                 for (int i = 0; i < optionals_; ++i) {
1191                         docstring optValue = asString(cell(optIdx(i)));
1192                         if (optValue.find(']') != docstring::npos)
1193                                 os << "[{" << cell(optIdx(i)) << "}]";
1194                         else
1195                                 os << "[" << cell(optIdx(i)) << "]";
1196                 }
1197         }
1198
1199         os << "{" << cell(defIdx()) << "}";
1200
1201         if (os.latex()) {
1202                 // writing .tex. done.
1203                 os << "\n";
1204         } else {
1205                 // writing .lyx, write special .tex export only if necessary
1206                 if (!cell(displayIdx()).empty())
1207                         os << "\n{" << cell(displayIdx()) << '}';
1208         }
1209 }
1210
1211
1212 int MathMacroTemplate::plaintext(odocstream & os,
1213                                  OutputParams const &) const
1214 {
1215         static docstring const str = '[' + buffer().B_("math macro") + ']';
1216
1217         os << str;
1218         return str.size();
1219 }
1220
1221
1222 bool MathMacroTemplate::validName() const
1223 {
1224         docstring n = name();
1225
1226         // empty name?
1227         if (n.size() == 0)
1228                 return false;
1229
1230         // converting back and force doesn't swallow anything?
1231         /*MathData ma;
1232         asArray(n, ma);
1233         if (asString(ma) != n)
1234                 return false;*/
1235
1236         // valid characters?
1237         for (size_t i = 0; i < n.size(); ++i) {
1238                 if (!(n[i] >= 'a' && n[i] <= 'z')
1239                     && !(n[i] >= 'A' && n[i] <= 'Z')
1240                     && n[i] != '*')
1241                         return false;
1242         }
1243
1244         return true;
1245 }
1246
1247
1248 bool MathMacroTemplate::validMacro() const
1249 {
1250         return validName();
1251 }
1252
1253
1254 bool MathMacroTemplate::fixNameAndCheckIfValid()
1255 {
1256         // check all the characters/insets in the name cell
1257         size_t i = 0;
1258         MathData & data = cell(0);
1259         while (i < data.size()) {
1260                 InsetMathChar const * cinset = data[i]->asCharInset();
1261                 if (cinset) {
1262                         // valid character in [a-zA-Z]?
1263                         char_type c = cinset->getChar();
1264                         if ((c >= 'a' && c <= 'z')
1265                             || (c >= 'A' && c <= 'Z')) {
1266                                 ++i;
1267                                 continue;
1268                         }
1269                 }
1270
1271                 // throw cell away
1272                 data.erase(i);
1273         }
1274
1275         // now it should be valid if anything in the name survived
1276         return data.size() > 0;
1277 }
1278
1279         
1280 void MathMacroTemplate::validate(LaTeXFeatures & features) const
1281 {
1282         // we need global optional macro arguments. They are not available 
1283         // with \def, and \newcommand does not support global macros. So we
1284         // are bound to xargs also for the single-optional-parameter case.
1285         if (optionals_ > 0)
1286                 features.require("xargs");
1287 }
1288
1289 void MathMacroTemplate::getDefaults(vector<docstring> & defaults) const
1290 {
1291         defaults.resize(numargs_);
1292         for (int i = 0; i < optionals_; ++i)
1293                 defaults[i] = asString(cell(optIdx(i)));
1294 }
1295
1296
1297 docstring MathMacroTemplate::definition() const
1298 {
1299         return asString(cell(defIdx()));
1300 }
1301
1302
1303 docstring MathMacroTemplate::displayDefinition() const
1304 {
1305         return asString(cell(displayIdx()));
1306 }
1307
1308
1309 size_t MathMacroTemplate::numArgs() const
1310 {
1311         return numargs_;
1312 }
1313
1314
1315 size_t MathMacroTemplate::numOptionals() const
1316 {
1317         return optionals_;
1318 }
1319
1320
1321 void MathMacroTemplate::infoize(odocstream & os) const
1322 {
1323         os << "Math Macro: \\" << name();
1324 }
1325
1326
1327 docstring MathMacroTemplate::contextMenu(BufferView const &, int, int) const
1328 {
1329         return from_ascii("context-math-macro-definition");
1330 }
1331
1332 } // namespace lyx