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