]> git.lyx.org Git - lyx.git/blob - src/mathed/MathMacroTemplate.cpp
Fix bug #6315: counters in insets that don't produce output have ghost values.
[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
39 #include "frontends/Painter.h"
40
41 #include "insets/RenderPreview.h"
42
43 #include "support/lassert.h"
44 #include "support/convert.h"
45 #include "support/debug.h"
46 #include "support/gettext.h"
47 #include "support/docstream.h"
48 #include "support/lstrings.h"
49
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) const
468 {
469         redefinition_ = mc.get(name()) != 0;
470 }
471
472
473 void MathMacroTemplate::updateLook() const
474 {
475         lookOutdated_ = true;
476 }
477
478
479 void MathMacroTemplate::createLook(int args) const
480 {
481         look_.clear();
482         argsInLook_ = args;
483
484         // \foo
485         look_.push_back(MathAtom(
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                 // updateToContext() - avoids another lookup
557                 redefinition_ = macro != 0;
558         }
559
560         // update look?
561         int argsInDef = maxArgumentInDefinition();
562         if (lookOutdated_ || argsInDef != argsInLook_) {
563                 lookOutdated_ = false;
564                 createLook(argsInDef);
565         }
566
567         /// metrics for inset contents
568         if (macro)
569                 macro->lock();
570
571         // first phase, premetric:
572         premetrics_ = true;
573         look_.metrics(mi, dim);
574         labelBoxAscent_ = dim.asc;
575         labelBoxDescent_ = dim.des;
576
577         // second phase, main metric:
578         premetrics_ = false;
579         look_.metrics(mi, dim);
580
581         if (macro)
582                 macro->unlock();
583
584         dim.wid += 6;
585         dim.des += 2;
586         dim.asc += 2;
587
588         setDimCache(mi, dim);
589 }
590
591
592 void MathMacroTemplate::draw(PainterInfo & pi, int x, int y) const
593 {
594         ColorChanger dummy0(pi.base.font, Color_math);
595         FontSetChanger dummy1(pi.base, from_ascii("mathnormal"));
596         StyleChanger dummy2(pi.base, LM_ST_TEXT);
597
598         setPosCache(pi, x, y);
599         Dimension const dim = dimension(*pi.base.bv);
600
601         // draw outer frame
602         int const a = y - dim.asc + 1;
603         int const w = dim.wid - 2;
604         int const h = dim.height() - 2;
605         pi.pain.rectangle(x, a, w, h, Color_mathframe);
606
607         // just to be sure: set some dummy values for coord cache
608         for (idx_type i = 0; i < nargs(); ++i)
609                 cell(i).setXY(*pi.base.bv, x, y);
610
611         // draw contents
612         look_.draw(pi, x + 3, y);
613 }
614
615
616 void MathMacroTemplate::edit(Cursor & cur, bool front, EntryDirection entry_from)
617 {
618         updateLook();
619         cur.screenUpdateFlags(Update::SinglePar);
620         InsetMathNest::edit(cur, front, entry_from);
621 }
622
623
624 bool MathMacroTemplate::notifyCursorLeaves(Cursor const & old, Cursor & cur)
625 {
626         commitEditChanges(cur, old);
627         updateLook();
628         cur.screenUpdateFlags(Update::Force);
629         return InsetMathNest::notifyCursorLeaves(old, cur);
630 }
631
632
633 void MathMacroTemplate::removeArguments(Cursor & cur,
634         DocIterator const & /*inset_pos*/, int from, int to)
635 {
636         DocIterator it = doc_iterator_begin(&buffer(), this);
637         for (; it; it.forwardChar()) {
638                 if (!it.nextInset())
639                         continue;
640                 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
641                         continue;
642                 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
643                 int n = arg->number() - 1;
644                 if (from <= n && n <= to) {
645                         int cellSlice = cur.find(it.cell());
646                         if (cellSlice != -1 && cur[cellSlice].pos() > it.pos())
647                                 --cur[cellSlice].pos();
648
649                         it.cell().erase(it.pos());
650                 }
651         }
652
653         updateLook();
654 }
655
656
657 void MathMacroTemplate::shiftArguments(size_t from, int by)
658 {
659         for (DocIterator it = doc_iterator_begin(&buffer(), this); it; it.forwardChar()) {
660                 if (!it.nextInset())
661                         continue;
662                 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
663                         continue;
664                 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
665                 if (arg->number() >= int(from) + 1)
666                         arg->setNumber(arg->number() + by);
667         }
668
669         updateLook();
670 }
671
672
673 int MathMacroTemplate::maxArgumentInDefinition() const
674 {
675         // We don't have a buffer when pasting from the clipboard (bug 6014).
676         Buffer const * macro_buffer = isBufferLoaded() ? &buffer() : 0;
677         int maxArg = 0;
678         DocIterator it = doc_iterator_begin(macro_buffer, this);
679         it.idx() = defIdx();
680         for (; it; it.forwardChar()) {
681                 if (!it.nextInset())
682                         continue;
683                 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
684                         continue;
685                 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
686                 maxArg = std::max(int(arg->number()), maxArg);
687         }
688         return maxArg;
689 }
690
691
692 void MathMacroTemplate::insertMissingArguments(int maxArg)
693 {
694         bool found[9] = { false, false, false, false, false, false, false, false, false };
695         idx_type idx = cell(displayIdx()).empty() ? defIdx() : displayIdx();
696
697         // search for #n macros arguments
698         DocIterator it = doc_iterator_begin(&buffer(), this);
699         it.idx() = idx;
700         for (; it && it[0].idx() == idx; it.forwardChar()) {
701                 if (!it.nextInset())
702                         continue;
703                 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
704                         continue;
705                 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
706                 found[arg->number() - 1] = true;
707         }
708
709         // add missing ones
710         for (int i = 0; i < maxArg; ++i) {
711                 if (found[i])
712                         continue;
713
714                 cell(idx).push_back(MathAtom(new MathMacroArgument(i + 1)));
715         }
716 }
717
718
719 void MathMacroTemplate::changeArity(Cursor & cur,
720         DocIterator const & inset_pos, int newNumArg)
721 {
722         // remove parameter which do not appear anymore in the definition
723         for (int i = numargs_; i > newNumArg; --i)
724                 removeParameter(cur, inset_pos, numargs_ - 1, false);
725         
726         // add missing parameter
727         for (int i = numargs_; i < newNumArg; ++i)
728                 insertParameter(cur, inset_pos, numargs_, false, false);
729 }
730
731
732 ///
733 class AddRemoveMacroInstanceFix
734 {
735 public:
736         ///
737         AddRemoveMacroInstanceFix(int n, bool insert) : n_(n), insert_(insert) {}
738         ///
739         void operator()(MathMacro * macro) {
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                 macro->setOptionals(optionals_);
765         }
766
767 private:
768         ///
769         int optionals_;
770 };
771
772
773 ///
774 class NullMacroInstanceFix
775 {
776 public:
777         ///
778         void operator()(MathMacro * ) {}
779 };
780
781
782 template<class F>
783 void fixMacroInstances(Cursor & cur, DocIterator const & inset_pos,
784         docstring const & name, F & fix)
785 {
786         // goto position behind macro template
787         DocIterator dit = inset_pos;
788         dit.pop_back();
789         dit.top().forwardPos();
790
791         // remember hull to trigger preview reload
792         DocIterator hull(dit.buffer());
793         bool preview_reload_needed = false;
794
795         // iterate over all positions until macro is redefined
796         for (; dit; dit.forwardPos()) {
797                 // left the outer hull?
798                 if (!hull.empty() && dit.depth() == hull.depth()) {
799                         // reload the preview if necessary 
800                         if (preview_reload_needed) {
801                                 InsetMathHull * inset_hull =
802                                         hull.nextInset()->asInsetMath()->asHullInset();
803                                 LASSERT(inset_hull, /**/);
804                                 inset_hull->reloadPreview(hull);
805                                 cur.screenUpdateFlags(Update::Force);
806                                 preview_reload_needed = false;
807                         }
808                         hull.clear();
809                 }
810
811                 // only until a macro is redefined
812                 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
813                         MathMacroTemplate const & macroTemplate
814                         = static_cast<MathMacroTemplate const &>(dit.inset());
815                         if (macroTemplate.name() == name)
816                                 break;
817                 }
818
819                 // in front of macro instance?
820                 Inset * inset = dit.nextInset();
821                 if (!inset)
822                         continue;
823                 InsetMath * insetMath = inset->asInsetMath();
824                 if (!insetMath)
825                         continue;
826
827                 // in front of outer hull?
828                 InsetMathHull * inset_hull = insetMath->asHullInset();
829                 if (inset_hull && hull.empty()) {
830                         // remember this for later preview reload
831                         hull = dit;
832                 }
833
834                 MathMacro * macro = insetMath->asMacro();
835                 if (macro && macro->name() == name && macro->folded()) {
836                         fix(macro);
837                         if (RenderPreview::status() == LyXRC::PREVIEW_ON)
838                                 preview_reload_needed = true;
839                 }
840         }
841 }
842
843
844 void MathMacroTemplate::commitEditChanges(Cursor & cur,
845         DocIterator const & inset_pos)
846 {
847         int args_in_def = maxArgumentInDefinition();
848         if (args_in_def != numargs_) {
849                 cur.recordUndoFullDocument();
850                 changeArity(cur, inset_pos, args_in_def);
851         }
852         insertMissingArguments(args_in_def);
853
854         // make sure the preview are up to date
855         NullMacroInstanceFix fix;
856         fixMacroInstances(cur, inset_pos, name(), fix);
857 }
858
859
860 void MathMacroTemplate::insertParameter(Cursor & cur,
861         DocIterator const & inset_pos, int pos, bool greedy, bool addarg)
862 {
863         if (pos <= numargs_ && pos >= optionals_ && numargs_ < 9) {
864                 ++numargs_;
865                 
866                 // append example #n
867                 if (addarg) {
868                         shiftArguments(pos, 1);
869
870                         cell(defIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
871                         if (!cell(displayIdx()).empty())
872                                 cell(displayIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
873                 }
874
875                 if (!greedy) {
876                         // fix macro instances
877                         AddRemoveMacroInstanceFix fix(pos, true);
878                         fixMacroInstances(cur, inset_pos, name(), fix);
879                 }
880         }
881
882         updateLook();
883 }
884
885
886 void MathMacroTemplate::removeParameter(Cursor & cur,
887         DocIterator const & inset_pos, int pos, bool greedy)
888 {
889         if (pos < numargs_ && pos >= 0) {
890                 --numargs_;
891                 removeArguments(cur, inset_pos, pos, pos);
892                 shiftArguments(pos + 1, -1);
893
894                 // removed optional parameter?
895                 if (pos < optionals_) {
896                         --optionals_;
897                         optionalValues_[pos] = cell(optIdx(pos));
898                         cells_.erase(cells_.begin() + optIdx(pos));
899
900                         // fix cursor
901                         int macroSlice = cur.find(this);
902                         if (macroSlice != -1) {
903                                 if (cur[macroSlice].idx() == optIdx(pos)) {
904                                         cur.cutOff(macroSlice);
905                                         cur[macroSlice].idx() = 1;
906                                         cur[macroSlice].pos() = 0;
907                                 } else if (cur[macroSlice].idx() > optIdx(pos))
908                                         --cur[macroSlice].idx();
909                         }
910                 }
911
912                 if (!greedy) {
913                         // fix macro instances
914                         AddRemoveMacroInstanceFix fix(pos, false);
915                         fixMacroInstances(cur, inset_pos, name(), fix);
916                 }
917         }
918
919         updateLook();
920 }
921
922
923 void MathMacroTemplate::makeOptional(Cursor & cur,
924         DocIterator const & inset_pos)
925 {
926         if (numargs_ > 0 && optionals_ < numargs_) {
927                 ++optionals_;
928                 cells_.insert(cells_.begin() + optIdx(optionals_ - 1), optionalValues_[optionals_ - 1]);
929                 // fix cursor
930                 int macroSlice = cur.find(this);
931                 if (macroSlice != -1 && cur[macroSlice].idx() >= optIdx(optionals_ - 1))
932                         ++cur[macroSlice].idx();
933
934                 // fix macro instances
935                 OptionalsMacroInstanceFix fix(optionals_);
936                 fixMacroInstances(cur, inset_pos, name(), fix);
937         }
938
939         updateLook();
940 }
941
942
943 void MathMacroTemplate::makeNonOptional(Cursor & cur,
944         DocIterator const & inset_pos)
945 {
946         if (numargs_ > 0 && optionals_ > 0) {
947                 --optionals_;
948
949                 // store default value for later if the user changes his mind
950                 optionalValues_[optionals_] = cell(optIdx(optionals_));
951                 cells_.erase(cells_.begin() + optIdx(optionals_));
952
953                 // fix cursor
954                 int macroSlice = cur.find(this);
955                 if (macroSlice != -1) {
956                         if (cur[macroSlice].idx() > optIdx(optionals_))
957                                 --cur[macroSlice].idx();
958                         else if (cur[macroSlice].idx() == optIdx(optionals_)) {
959                                 cur.cutOff(macroSlice);
960                                 cur[macroSlice].idx() = optIdx(optionals_);
961                                 cur[macroSlice].pos() = 0;
962                         }
963                 }
964
965                 // fix macro instances
966                 OptionalsMacroInstanceFix fix(optionals_);
967                 fixMacroInstances(cur, inset_pos, name(), fix);
968         }
969
970         updateLook();
971 }
972
973
974 void MathMacroTemplate::doDispatch(Cursor & cur, FuncRequest & cmd)
975 {
976         string const arg = to_utf8(cmd.argument());
977         switch (cmd.action()) {
978
979         case LFUN_MATH_MACRO_ADD_PARAM:
980                 if (numargs_ < 9) {
981                         commitEditChanges(cur, cur);
982                         cur.recordUndoFullDocument();
983                         size_t pos = numargs_;
984                         if (arg.size() != 0)
985                                 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
986                         insertParameter(cur, cur, pos);
987                 }
988                 break;
989
990
991         case LFUN_MATH_MACRO_REMOVE_PARAM:
992                 if (numargs_ > 0) {
993                         commitEditChanges(cur, cur);
994                         cur.recordUndoFullDocument();
995                         size_t pos = numargs_ - 1;
996                         if (arg.size() != 0)
997                                 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
998                         removeParameter(cur, cur, pos);
999                 }
1000                 break;
1001
1002         case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
1003                 if (numargs_ < 9) {
1004                         commitEditChanges(cur, cur);
1005                         cur.recordUndoFullDocument();
1006                         insertParameter(cur, cur, numargs_, true);
1007                 }
1008                 break;
1009
1010         case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
1011                 if (numargs_ > 0) {
1012                         commitEditChanges(cur, cur);
1013                         cur.recordUndoFullDocument();
1014                         removeParameter(cur, cur, numargs_ - 1, true);
1015                 }
1016                 break;
1017
1018         case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1019                 commitEditChanges(cur, cur);
1020                 cur.recordUndoFullDocument();
1021                 makeOptional(cur, cur);
1022                 break;
1023
1024         case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1025                 commitEditChanges(cur, cur);
1026                 cur.recordUndoFullDocument();
1027                 makeNonOptional(cur, cur);
1028                 break;
1029
1030         case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1031                 if (numargs_ < 9) {
1032                         commitEditChanges(cur, cur);
1033                         cur.recordUndoFullDocument();
1034                         insertParameter(cur, cur, optionals_);
1035                         makeOptional(cur, cur);
1036                 }
1037                 break;
1038
1039         case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1040                 if (optionals_ > 0) {
1041                         commitEditChanges(cur, cur);
1042                         cur.recordUndoFullDocument();
1043                         removeParameter(cur, cur, optionals_ - 1);
1044                 } break;
1045
1046         case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1047                 if (numargs_ == optionals_) {
1048                         commitEditChanges(cur, cur);
1049                         cur.recordUndoFullDocument();
1050                         insertParameter(cur, cur, 0, true);
1051                         makeOptional(cur, cur);
1052                 }
1053                 break;
1054
1055         default:
1056                 InsetMathNest::doDispatch(cur, cmd);
1057                 break;
1058         }
1059 }
1060
1061
1062 bool MathMacroTemplate::getStatus(Cursor & /*cur*/, FuncRequest const & cmd,
1063         FuncStatus & flag) const
1064 {
1065         bool ret = true;
1066         string const arg = to_utf8(cmd.argument());
1067         switch (cmd.action()) {
1068                 case LFUN_MATH_MACRO_ADD_PARAM: {
1069                         int num = numargs_ + 1;
1070                         if (arg.size() != 0)
1071                                 num = convert<int>(arg);
1072                         bool on = (num >= optionals_
1073                                    && numargs_ < 9 && num <= numargs_ + 1);
1074                         flag.setEnabled(on);
1075                         break;
1076                 }
1077
1078                 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
1079                         flag.setEnabled(numargs_ < 9);
1080                         break;
1081
1082                 case LFUN_MATH_MACRO_REMOVE_PARAM: {
1083                         int num = numargs_;
1084                         if (arg.size() != 0)
1085                                 num = convert<int>(arg);
1086                         flag.setEnabled(num >= 1 && num <= numargs_);
1087                         break;
1088                 }
1089
1090                 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1091                         flag.setEnabled(numargs_ > 0
1092                                      && optionals_ < numargs_
1093                                      && type_ != MacroTypeDef);
1094                         break;
1095
1096                 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1097                         flag.setEnabled(optionals_ > 0
1098                                      && type_ != MacroTypeDef);
1099                         break;
1100
1101                 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1102                         flag.setEnabled(numargs_ < 9);
1103                         break;
1104
1105                 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1106                         flag.setEnabled(optionals_ > 0);
1107                         break;
1108
1109                 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1110                         flag.setEnabled(numargs_ == 0
1111                                      && type_ != MacroTypeDef);
1112                         break;
1113
1114                 case LFUN_IN_MATHMACROTEMPLATE:
1115                         flag.setEnabled(true);
1116                         break;
1117
1118                 default:
1119                         ret = false;
1120                         break;
1121         }
1122         return ret;
1123 }
1124
1125
1126 void MathMacroTemplate::read(Lexer & lex)
1127 {
1128         MathData ar(buffer_);
1129         mathed_parse_cell(ar, lex.getStream(), Parse::TRACKMACRO);
1130         if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
1131                 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
1132                 lyxerr << "Read: " << to_utf8(asString(ar)) << endl;
1133                 return;
1134         }
1135         operator=( *(ar[0]->asMacroTemplate()) );
1136
1137         updateLook();
1138 }
1139
1140
1141 void MathMacroTemplate::write(ostream & os) const
1142 {
1143         odocstringstream oss;
1144         WriteStream wi(oss, false, false, WriteStream::wsDefault);
1145         oss << "FormulaMacro\n";
1146         write(wi);
1147         os << to_utf8(oss.str());
1148 }
1149
1150
1151 void MathMacroTemplate::write(WriteStream & os) const
1152 {
1153         write(os, false);
1154 }
1155
1156
1157 int MathMacroTemplate::write(WriteStream & os, bool overwriteRedefinition) const
1158 {
1159         int num_lines = 0;
1160
1161         if (os.latex()) {
1162                 if (optionals_ > 0) {
1163                         // macros with optionals use the xargs package, e.g.:
1164                         // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
1165                         // \long is implicit by xargs
1166                         if (redefinition_ && !overwriteRedefinition)
1167                                 os << "\\renewcommandx";
1168                         else
1169                                 os << "\\newcommandx";
1170
1171                         os << "\\" << name()
1172                            << "[" << numargs_ << "]"
1173                            << "[usedefault, addprefix=\\global";
1174                         for (int i = 0; i < optionals_; ++i) {
1175                                 docstring optValue = asString(cell(optIdx(i)));
1176                                 if (optValue.find(']') != docstring::npos
1177                                     || optValue.find(',') != docstring::npos)
1178                                         os << ", " << i + 1 << "="
1179                                         << "{" << cell(optIdx(i)) << "}";
1180                                 else
1181                                         os << ", " << i + 1 << "="
1182                                         << cell(optIdx(i));
1183                         }
1184                         os << "]";
1185                 } else {
1186                         // Macros without optionals use standard _global_ \def macros:
1187                         //   \global\def\long\foo#1#2{#1,#2}
1188                         // We use the \long prefix as this is the equivalent to \newcommand.
1189                         // We cannot use \newcommand directly because \global does not work with it.
1190                         os << "\\global\\long\\def\\" << name();
1191                         docstring param = from_ascii("#0");
1192                         for (int i = 1; i <= numargs_; ++i) { 
1193                                 param[1] = '0' + i;
1194                                 os << param;
1195                         }
1196                 }
1197         } else {
1198                 // in LyX output we use some pseudo syntax which is implementation
1199                 // independent, e.g.
1200                 // \newcommand{\foo}[2][default]{#1,#2}
1201                 if (redefinition_ && !overwriteRedefinition)
1202                         os << "\\renewcommand";
1203                 else
1204                         os << "\\newcommand";
1205                 os << "{\\" << name() << '}';
1206                 if (numargs_ > 0)
1207                         os << '[' << numargs_ << ']';
1208
1209                 for (int i = 0; i < optionals_; ++i) {
1210                         docstring optValue = asString(cell(optIdx(i)));
1211                         if (optValue.find(']') != docstring::npos)
1212                                 os << "[{" << cell(optIdx(i)) << "}]";
1213                         else
1214                                 os << "[" << cell(optIdx(i)) << "]";
1215                 }
1216         }
1217
1218         os << "{" << cell(defIdx()) << "}";
1219
1220         if (os.latex()) {
1221                 // writing .tex. done.
1222                 os << "\n";
1223                 ++num_lines;
1224         } else {
1225                 // writing .lyx, write special .tex export only if necessary
1226                 if (!cell(displayIdx()).empty()) {
1227                         os << "\n{" << cell(displayIdx()) << '}';
1228                         ++num_lines;
1229                 }
1230         }
1231
1232         return num_lines;
1233 }
1234
1235
1236 docstring MathMacroTemplate::xhtml(XHTMLStream &, OutputParams const &) const
1237 {
1238         return docstring();
1239 }
1240
1241 int MathMacroTemplate::plaintext(odocstream & os,
1242                                  OutputParams const &) const
1243 {
1244         static docstring const str = '[' + buffer().B_("math macro") + ']';
1245
1246         os << str;
1247         return str.size();
1248 }
1249
1250
1251 bool MathMacroTemplate::validName() const
1252 {
1253         docstring n = name();
1254
1255         // empty name?
1256         if (n.size() == 0)
1257                 return false;
1258
1259         // converting back and force doesn't swallow anything?
1260         /*MathData ma;
1261         asArray(n, ma);
1262         if (asString(ma) != n)
1263                 return false;*/
1264
1265         // valid characters?
1266         for (size_t i = 0; i < n.size(); ++i) {
1267                 if (!(n[i] >= 'a' && n[i] <= 'z')
1268                     && !(n[i] >= 'A' && n[i] <= 'Z')
1269                     && n[i] != '*')
1270                         return false;
1271         }
1272
1273         return true;
1274 }
1275
1276
1277 bool MathMacroTemplate::validMacro() const
1278 {
1279         return validName();
1280 }
1281
1282
1283 bool MathMacroTemplate::fixNameAndCheckIfValid()
1284 {
1285         // check all the characters/insets in the name cell
1286         size_t i = 0;
1287         MathData & data = cell(0);
1288         while (i < data.size()) {
1289                 InsetMathChar const * cinset = data[i]->asCharInset();
1290                 if (cinset) {
1291                         // valid character in [a-zA-Z]?
1292                         char_type c = cinset->getChar();
1293                         if ((c >= 'a' && c <= 'z')
1294                             || (c >= 'A' && c <= 'Z')) {
1295                                 ++i;
1296                                 continue;
1297                         }
1298                 }
1299
1300                 // throw cell away
1301                 data.erase(i);
1302         }
1303
1304         // now it should be valid if anything in the name survived
1305         return data.size() > 0;
1306 }
1307
1308         
1309 void MathMacroTemplate::validate(LaTeXFeatures & features) const
1310 {
1311         // we need global optional macro arguments. They are not available 
1312         // with \def, and \newcommand does not support global macros. So we
1313         // are bound to xargs also for the single-optional-parameter case.
1314         if (optionals_ > 0)
1315                 features.require("xargs");
1316 }
1317
1318 void MathMacroTemplate::getDefaults(vector<docstring> & defaults) const
1319 {
1320         defaults.resize(numargs_);
1321         for (int i = 0; i < optionals_; ++i)
1322                 defaults[i] = asString(cell(optIdx(i)));
1323 }
1324
1325
1326 docstring MathMacroTemplate::definition() const
1327 {
1328         return asString(cell(defIdx()));
1329 }
1330
1331
1332 docstring MathMacroTemplate::displayDefinition() const
1333 {
1334         return asString(cell(displayIdx()));
1335 }
1336
1337
1338 size_t MathMacroTemplate::numArgs() const
1339 {
1340         return numargs_;
1341 }
1342
1343
1344 size_t MathMacroTemplate::numOptionals() const
1345 {
1346         return optionals_;
1347 }
1348
1349
1350 void MathMacroTemplate::infoize(odocstream & os) const
1351 {
1352         os << "Math Macro: \\" << name();
1353 }
1354
1355
1356 docstring MathMacroTemplate::contextMenu(BufferView const &, int, int) const
1357 {
1358         return from_ascii("context-math-macro-definition");
1359 }
1360
1361 } // namespace lyx