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