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