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