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