]> git.lyx.org Git - lyx.git/blob - src/mathed/MathMacroTemplate.cpp
* tabs are evil
[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 "InsetMathBrace.h"
17 #include "InsetMathChar.h"
18 #include "InsetMathSqrt.h"
19 #include "MathMacro.h"
20 #include "MathMacroArgument.h"
21 #include "MathStream.h"
22 #include "MathParser.h"
23 #include "MathSupport.h"
24 #include "MathMacroArgument.h"
25
26 #include "Buffer.h"
27 #include "BufferView.h"
28 #include "Color.h"
29 #include "Cursor.h"
30 #include "support/debug.h"
31 #include "DispatchResult.h"
32 #include "FuncRequest.h"
33 #include "FuncStatus.h"
34 #include "support/gettext.h"
35 #include "Lexer.h"
36 #include "Undo.h"
37
38 #include "frontends/FontMetrics.h"
39 #include "frontends/Painter.h"
40
41 #include "support/convert.h"
42 #include "support/docstream.h"
43 #include "support/lstrings.h"
44
45 #include "support/debug.h"
46
47 #include <sstream>
48
49 using namespace std;
50
51 namespace lyx {
52
53 using support::bformat;
54
55 //////////////////////////////////////////////////////////////////////
56
57 class InsetLabelBox : public InsetMathNest {
58 public:
59         ///
60         InsetLabelBox(MathAtom const & atom, docstring label, 
61                       MathMacroTemplate const & parent, bool frame = false);
62         InsetLabelBox(docstring label, MathMacroTemplate const & parent, 
63                       bool frame = false);
64         ///
65         void metrics(MetricsInfo & mi, Dimension & dim) const;
66         ///
67         void draw(PainterInfo &, int x, int y) const;
68         
69 protected:
70         ///
71         MathMacroTemplate const & parent_;
72         ///
73         Inset * clone() const;
74         ///
75         docstring const label_;
76         ///
77         bool frame_;
78 };
79
80
81 InsetLabelBox::InsetLabelBox(MathAtom const & atom, docstring label, 
82                                                                                                                  MathMacroTemplate const & parent, bool frame)
83 :       InsetMathNest(1), parent_(parent), label_(label), frame_(frame)
84 {
85         cell(0).insert(0, atom);
86 }
87
88
89 InsetLabelBox::InsetLabelBox(docstring label,
90                                                                                                                  MathMacroTemplate const & parent, bool frame)
91 :       InsetMathNest(1), parent_(parent), label_(label), frame_(frame)
92 {
93 }
94         
95
96 Inset * InsetLabelBox::clone() const 
97 {
98         return new InsetLabelBox(*this);
99 }
100
101
102 void InsetLabelBox::metrics(MetricsInfo & mi, Dimension & dim) const 
103 {
104         // kernel
105         cell(0).metrics(mi, dim);
106
107         // frame
108         if (frame_) {
109                 dim.wid += 6;
110                 dim.asc += 5;
111                 dim.des += 5;
112         }
113                 
114         // adjust to common height in main metrics phase
115         if (!parent_.premetrics()) {
116                 dim.asc = max(dim.asc, parent_.commonLabelBoxAscent());
117                 dim.des = max(dim.des, parent_.commonLabelBoxDescent());
118         }
119         
120         // label
121         if (parent_.editing(mi.base.bv) && label_.length() > 0) {
122                 // grey
123                 FontInfo font = sane_font;
124                 font.setSize(FONT_SIZE_TINY);
125                 font.setColor(Color_mathmacrolabel);
126                 
127                 // make space for label and box
128                 int lwid = mathed_string_width(font, label_);
129                 int maxasc;
130                 int maxdes;
131                 math_font_max_dim(font, maxasc, maxdes);                
132                 
133                 dim.wid = max(dim.wid, lwid + 2);
134
135                 // space for the label
136                 if (!parent_.premetrics())
137                         dim.des += maxasc + maxdes + 1;
138         }
139
140         setDimCache(mi, dim);
141 }
142
143
144 void InsetLabelBox::draw(PainterInfo & pi, int x, int y) const 
145 {
146         Dimension const dim = dimension(*pi.base.bv);
147         Dimension const cdim = cell(0).dimension(*pi.base.bv);
148         
149         // kernel
150         cell(0).draw(pi, x + (dim.wid - cdim.wid) / 2, y);
151         
152         // label
153         if (parent_.editing(pi.base.bv) && label_.length() > 0) {
154                 // grey
155                 FontInfo font = sane_font;
156                 font.setSize(FONT_SIZE_TINY);
157                 font.setColor(Color_mathmacrolabel);
158                 
159                 // make space for label and box
160                 int lwid = mathed_string_width(font, label_);
161                 int maxasc;
162                 int maxdes;
163                 math_font_max_dim(font, maxasc, maxdes);
164                 
165                 if (lwid < dim.wid)
166                         pi.pain.text(x + (dim.wid - lwid) / 2, y + dim.des - maxdes, label_, font);
167                 else
168                         pi.pain.text(x, y + dim.des - maxdes, label_, font);
169         }
170         
171         // draw frame
172         int boxHeight = parent_.commonLabelBoxAscent() + parent_.commonLabelBoxDescent();
173         if (frame_) {
174                 pi.pain.rectangle(x + 1, y - dim.ascent() + 1, 
175                                   dim.wid - 2, boxHeight - 2, 
176                                   Color_mathline);
177         }
178 }
179
180
181 //////////////////////////////////////////////////////////////////////
182
183 class DisplayLabelBox : public InsetLabelBox {
184 public:
185         ///
186         DisplayLabelBox(MathAtom const & atom, docstring label, 
187                         MathMacroTemplate const & parent);
188                 
189         ///
190         void metrics(MetricsInfo & mi, Dimension & dim) const;
191         ///
192         void draw(PainterInfo &, int x, int y) const;
193         
194 protected:
195         ///
196         Inset * clone() const;
197 };
198
199
200 DisplayLabelBox::DisplayLabelBox(MathAtom const & atom, 
201                                  docstring label, 
202                                  MathMacroTemplate const & parent)
203         : InsetLabelBox(atom, label, parent, true)
204 {
205 }
206         
207         
208         
209 Inset * DisplayLabelBox::clone() const 
210 {
211         return new DisplayLabelBox(*this);
212 }
213         
214         
215 void DisplayLabelBox::metrics(MetricsInfo & mi, Dimension & dim) const
216 {
217         InsetLabelBox::metrics(mi, dim);
218         if (!parent_.editing(mi.base.bv)
219             && parent_.cell(parent_.displayIdx()).empty()) {
220                 dim.wid = 0;
221                 dim.asc = 0;
222                 dim.des = 0;
223                 setDimCache(mi, dim);
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
283 class InsetNameWrapper : public InsetMathWrapper {
284 public:
285         ///
286         InsetNameWrapper(MathData const * value, MathMacroTemplate const & parent);
287         ///
288         void metrics(MetricsInfo & mi, Dimension & dim) const;
289         ///
290         void draw(PainterInfo &, int x, int y) const;
291         
292 private:
293         ///
294         MathMacroTemplate const & parent_;
295         ///
296         Inset * clone() const;
297 };
298
299
300 InsetNameWrapper::InsetNameWrapper(MathData const * value, 
301                                                                                                                                          MathMacroTemplate const & parent)
302         : InsetMathWrapper(value), parent_(parent)
303 {
304 }
305
306
307 Inset * InsetNameWrapper::clone() const 
308 {
309         return new InsetNameWrapper(*this);
310 }
311
312
313 void InsetNameWrapper::metrics(MetricsInfo & mi, Dimension & dim) const 
314 {
315         InsetMathWrapper::metrics(mi, dim);
316         dim.wid += mathed_string_width(mi.base.font, from_ascii("\\"));
317 }
318
319
320 void InsetNameWrapper::draw(PainterInfo & pi, int x, int y) const 
321 {
322         // create fonts
323         PainterInfo namepi = pi;
324         if (parent_.validMacro())
325                 namepi.base.font.setColor(Color_latex);
326         else
327                 namepi.base.font.setColor(Color_error);         
328         
329         // draw backslash
330         pi.pain.text(x, y, from_ascii("\\"), namepi.base.font);
331         x += mathed_string_width(namepi.base.font, from_ascii("\\"));
332         
333         // draw name
334         InsetMathWrapper::draw(namepi, x, y);
335 }
336
337         
338 ///////////////////////////////////////////////////////////////////////
339         
340         
341 MathMacroTemplate::MathMacroTemplate()
342         : InsetMathNest(3), numargs_(0), optionals_(0), 
343           type_(MacroTypeNewcommand), lookOutdated_(true)
344 {
345         initMath();
346 }
347
348
349 MathMacroTemplate::MathMacroTemplate(docstring const & name, int numargs,
350         int optionals, MacroType type, 
351         vector<MathData> const & optionalValues, 
352         MathData const & def, MathData const & display)
353         : InsetMathNest(optionals + 3), numargs_(numargs), 
354           optionals_(optionals), optionalValues_(optionalValues),
355           type_(type), lookOutdated_(true)
356 {
357         initMath();
358
359         if (numargs_ > 9)
360                 lyxerr << "MathMacroTemplate::MathMacroTemplate: wrong # of arguments: "
361                         << numargs_ << endl;
362         
363         asArray(name, cell(0));
364         optionalValues_.resize(9);
365         for (int i = 0; i < optionals_; ++i) 
366                 cell(optIdx(i)) = optionalValues_[i];
367         cell(defIdx()) = def;
368         cell(displayIdx()) = display;
369
370         updateLook();
371 }
372
373
374 MathMacroTemplate::MathMacroTemplate(docstring const & str)
375         : InsetMathNest(3), numargs_(0), optionals_(0),
376         type_(MacroTypeNewcommand), lookOutdated_(true)
377 {
378         initMath();
379
380         MathData ar;
381         mathed_parse_cell(ar, str);
382         if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
383                 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
384                 asArray(from_ascii("invalidmacro"), cell(0));
385                 // FIXME: The macro template does not make sense after this.
386                 // The whole parsing should not be in a constructor which
387                 // has no chance to report failure.
388                 return;
389         }
390         operator=( *(ar[0]->asMacroTemplate()) );
391
392         updateLook();
393 }
394
395
396 Inset * MathMacroTemplate::clone() const
397 {
398         return new MathMacroTemplate(*this);
399 }
400
401
402 docstring MathMacroTemplate::name() const
403 {
404         return asString(cell(0));
405 }
406
407
408 void MathMacroTemplate::updateToContext(MacroContext const & mc) const
409 {
410         redefinition_ = mc.get(name()) != 0;
411 }
412
413         
414 void MathMacroTemplate::updateLook() const
415 {
416         lookOutdated_ = true;
417 }
418
419
420 void MathMacroTemplate::createLook() const
421 {
422         look_.clear();
423
424         // \foo
425         look_.push_back(MathAtom(new InsetLabelBox(_("Name"), *this, false)));
426         MathData & nameData = look_[look_.size() - 1].nucleus()->cell(0);
427         nameData.push_back(MathAtom(new InsetNameWrapper(&cell(0), *this)));
428         
429         // [#1][#2]
430         int i = 0;
431         if (optionals_ > 0) {
432                 look_.push_back(MathAtom(new InsetLabelBox(_("optional"), *this, false)));
433                 MathData & optData = look_[look_.size() - 1].nucleus()->cell(0);
434         
435                 for (; i < optionals_; ++i) {
436                         optData.push_back(MathAtom(new InsetMathChar('[')));
437                         optData.push_back(MathAtom(new InsetMathWrapper(&cell(1 + i))));
438                         optData.push_back(MathAtom(new InsetMathChar(']')));
439                 }
440         }
441         
442         // {#3}{#4}
443         for (; i < numargs_; ++i) {
444                 MathData arg;
445                 arg.push_back(MathAtom(new MathMacroArgument(i + 1)));
446                 look_.push_back(MathAtom(new InsetMathBrace(arg)));
447         }
448         
449         // :=
450         look_.push_back(MathAtom(new InsetMathChar(':')));
451         look_.push_back(MathAtom(new InsetMathChar('=')));
452
453         // definition
454         look_.push_back(MathAtom(
455                 new InsetLabelBox(MathAtom(
456                         new InsetMathWrapper(&cell(defIdx()))), _("TeX"), *this,        true)));
457
458         // display
459         look_.push_back(MathAtom(
460                 new DisplayLabelBox(MathAtom(
461                         new InsetMathWrapper(&cell(displayIdx()))), _("LyX"), *this)));
462 }
463         
464
465 void MathMacroTemplate::metrics(MetricsInfo & mi, Dimension & dim) const
466 {
467         FontSetChanger dummy1(mi.base, from_ascii("mathnormal"));
468         StyleChanger dummy2(mi.base, LM_ST_TEXT);
469         
470         // valid macro?
471         MacroData const * macro = 0;
472         if (validName()) {
473                 macro = mi.macrocontext.get(name());
474
475                 // updateToContext() - avoids another lookup
476                 redefinition_ = macro != 0;
477         }
478                 
479         // update look?
480         if (lookOutdated_) {
481                 lookOutdated_ = false;
482                 createLook();
483         }
484         
485         /// metrics for inset contents
486         if (macro)
487                 macro->lock();          
488         
489         // first phase, premetric:
490         premetrics_ = true;
491         look_.metrics(mi, dim);
492         labelBoxAscent_ = dim.asc;
493         labelBoxDescent_ = dim.des;
494         
495         // second phase, main metric:
496         premetrics_ = false;
497         look_.metrics(mi, dim);
498         
499         if (macro)
500                 macro->unlock();
501         
502         dim.wid += 6;
503         dim.des += 2;
504         dim.asc += 2;
505         
506         setDimCache(mi, dim);
507 }
508
509
510 void MathMacroTemplate::draw(PainterInfo & pi, int x, int y) const
511 {
512         FontSetChanger dummy1(pi.base, from_ascii("mathnormal"));
513         StyleChanger dummy2(pi.base, LM_ST_TEXT);
514         
515         setPosCache(pi, x, y);
516         Dimension const dim = dimension(*pi.base.bv);
517
518         // draw outer frame
519         int const a = y - dim.asc + 1;
520         int const w = dim.wid - 2;
521         int const h = dim.height() - 2;
522         pi.pain.rectangle(x, a, w, h, Color_mathframe); 
523         
524         // just to be sure: set some dummy values for coord cache
525         for (idx_type i = 0; i < nargs(); ++i) {
526                 cell(i).setXY(*pi.base.bv, x, y);
527         }
528         
529         // draw contents
530         look_.draw(pi, x + 3, y);
531 }
532
533         
534 void MathMacroTemplate::edit(Cursor & cur, bool left)
535 {
536         updateLook();
537         cur.updateFlags(Update::Force);
538         InsetMathNest::edit(cur, left);
539 }
540         
541         
542 bool MathMacroTemplate::notifyCursorLeaves(Cursor & cur)
543 {
544         updateLook();
545         cur.updateFlags(Update::Force);
546         return InsetMathNest::notifyCursorLeaves(cur);
547 }
548         
549
550 void MathMacroTemplate::removeArguments(Cursor & cur, int from, int to) {
551         for (DocIterator it = doc_iterator_begin(*this); it; it.forwardChar()) {
552                 if (!it.nextInset())
553                         continue;
554                 if (it.nextInset()->lyxCode() != MATHMACROARG_CODE)
555                         continue;
556                 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
557                 int n = arg->number() - 1;
558                 if (from <= n && n <= to) {
559                         int cellSlice = cur.find(it.cell());
560                         if (cellSlice != -1 && cur[cellSlice].pos() > it.pos())
561                                 --cur[cellSlice].pos();
562
563                         it.cell().erase(it.pos());
564                 }
565         }
566         
567         updateLook();
568 }
569
570
571 void MathMacroTemplate::shiftArguments(size_t from, int by) {
572         for (DocIterator it = doc_iterator_begin(*this); it; it.forwardChar()) {
573                 if (!it.nextInset())
574                         continue;
575                 if (it.nextInset()->lyxCode() != MATHMACROARG_CODE)
576                         continue;
577                 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
578                 if (arg->number() >= from + 1)
579                         arg->setNumber(arg->number() + by);
580         }
581
582         updateLook();
583 }
584
585
586 // FIXME: factorize those functions here with a functional style, maybe using Boost's function
587 // objects?
588
589 void fixMacroInstancesAddRemove(Cursor const & from, docstring const & name, int n, bool insert) {
590         Cursor dit = from;
591
592         for (; dit; dit.forwardPos()) {
593                 // only until a macro is redefined
594                 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
595                         MathMacroTemplate const & macroTemplate
596                         = static_cast<MathMacroTemplate const &>(dit.inset());
597                         if (macroTemplate.name() == name)
598                                 break;
599                 }
600
601                 // in front of macro instance?
602                 Inset * inset = dit.nextInset();
603                 if (inset) {
604                         InsetMath * insetMath = inset->asInsetMath();
605                         if (insetMath) {
606                                 MathMacro * macro = insetMath->asMacro();
607                                 if (macro && macro->name() == name && macro->folded()) {
608                                         // found macro instance
609                                         if (insert)
610                                                 macro->insertArgument(n);
611                                         else
612                                                 macro->removeArgument(n);
613                                 }
614                         }
615                 }
616         }
617 }
618
619
620 void fixMacroInstancesOptional(Cursor const & from, docstring const & name, int optionals) {
621         Cursor dit = from;
622
623         for (; dit; dit.forwardPos()) {
624                 // only until a macro is redefined
625                 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
626                         MathMacroTemplate const & macroTemplate
627                         = static_cast<MathMacroTemplate const &>(dit.inset());
628                         if (macroTemplate.name() == name)
629                                 break;
630                 }
631
632                 // in front of macro instance?
633                 Inset * inset = dit.nextInset();
634                 if (inset) {
635                         InsetMath * insetMath = inset->asInsetMath();
636                         if (insetMath) {
637                                 MathMacro * macro = insetMath->asMacro();
638                                 if (macro && macro->name() == name && macro->folded()) {
639                                         // found macro instance
640                                         macro->setOptionals(optionals);
641                                 }
642                         }
643                 }
644         }
645 }
646
647
648 template<class F>
649 void fixMacroInstancesFunctional(Cursor const & from, 
650         docstring const & name, F & fix) {
651         Cursor dit = from;
652
653         for (; dit; dit.forwardPos()) {
654                 // only until a macro is redefined
655                 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
656                         MathMacroTemplate const & macroTemplate
657                         = static_cast<MathMacroTemplate const &>(dit.inset());
658                         if (macroTemplate.name() == name)
659                                 break;
660                 }
661
662                 // in front of macro instance?
663                 Inset * inset = dit.nextInset();
664                 if (inset) {
665                         InsetMath * insetMath = inset->asInsetMath();
666                         if (insetMath) {
667                                 MathMacro * macro = insetMath->asMacro();
668                                 if (macro && macro->name() == name && macro->folded())
669                                         F(macro);
670                         }
671                 }
672         }
673 }
674
675
676 void MathMacroTemplate::insertParameter(Cursor & cur, int pos, bool greedy) 
677 {
678         if (pos <= numargs_ && pos >= optionals_ && numargs_ < 9) {
679                 ++numargs_;
680                 shiftArguments(pos, 1);
681
682                 // append example #n
683                 cell(defIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
684                 if (!cell(displayIdx()).empty())
685                         cell(displayIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
686
687                 if (!greedy) {
688                         Cursor dit = cur;
689                         dit.leaveInset(*this);
690                         // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
691                         dit.top().forwardPos();
692                         
693                         // fix macro instances
694                         fixMacroInstancesAddRemove(dit, name(), pos, true);
695                 }
696         }
697
698         updateLook();
699 }
700
701
702 void MathMacroTemplate::removeParameter(Cursor & cur, int pos, bool greedy)
703 {
704         if (pos < numargs_ && pos >= 0) {
705                 --numargs_;
706                 removeArguments(cur, pos, pos);
707                 shiftArguments(pos + 1, -1);
708
709                 // removed optional parameter?
710                 if (pos < optionals_) {
711                         --optionals_;
712                         optionalValues_[pos] = cell(optIdx(pos));
713                         cells_.erase(cells_.begin() + optIdx(pos));
714
715                         // fix cursor
716                         int macroSlice = cur.find(this);
717                         if (macroSlice != -1) {
718                                 if (cur[macroSlice].idx() == optIdx(pos)) {
719                                         cur.cutOff(macroSlice);
720                                         cur[macroSlice].idx() = 1;
721                                         cur[macroSlice].pos() = 0;
722                                 } else if (cur[macroSlice].idx() > optIdx(pos))
723                                         --cur[macroSlice].idx();
724                         }
725                 }
726
727                 if (!greedy) {
728                         // fix macro instances
729                         //boost::function<void(MathMacro *)> fix = _1->insertArgument(n);
730                         //fixMacroInstancesFunctional(dit, name(), fix);
731                         Cursor dit = cur;
732                         dit.leaveInset(*this);
733                         // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
734                         dit.top().forwardPos();
735                         fixMacroInstancesAddRemove(dit, name(), pos, false);
736                 }
737         }
738
739         updateLook();
740 }
741
742
743 void MathMacroTemplate::makeOptional(Cursor & cur) {
744         if (numargs_ > 0 && optionals_ < numargs_) {
745                 ++optionals_;
746                 cells_.insert(cells_.begin() + optIdx(optionals_ - 1), optionalValues_[optionals_ - 1]);
747                 // fix cursor
748                 int macroSlice = cur.find(this);
749                 if (macroSlice != -1 && cur[macroSlice].idx() >= optIdx(optionals_ - 1))
750                         ++cur[macroSlice].idx();
751
752                 // fix macro instances
753                 Cursor dit = cur;
754                 dit.leaveInset(*this);
755                 // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
756                 dit.top().forwardPos();
757                 fixMacroInstancesOptional(dit, name(), optionals_);
758         }
759
760         updateLook();
761 }
762
763
764 void MathMacroTemplate::makeNonOptional(Cursor & cur) {
765         if (numargs_ > 0 && optionals_ > 0) {
766                 --optionals_;
767                 
768                 // store default value for later if the use changes his mind
769                 optionalValues_[optionals_] = cell(optIdx(optionals_));
770                 cells_.erase(cells_.begin() + optIdx(optionals_));
771
772                 // fix cursor
773                 int macroSlice = cur.find(this);
774                 if (macroSlice != -1) {
775                         if (cur[macroSlice].idx() > optIdx(optionals_))
776                                 --cur[macroSlice].idx();
777                         else if (cur[macroSlice].idx() == optIdx(optionals_)) {
778                                 cur.cutOff(macroSlice);
779                                 cur[macroSlice].idx() = optIdx(optionals_);
780                                 cur[macroSlice].pos() = 0;
781                         }
782                 }
783
784                 // fix macro instances
785                 Cursor dit = cur;
786                 dit.leaveInset(*this);
787                 // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
788                 dit.top().forwardPos();
789                 fixMacroInstancesOptional(dit, name(), optionals_);
790         }
791
792         updateLook();
793 }
794
795
796 void MathMacroTemplate::doDispatch(Cursor & cur, FuncRequest & cmd)
797 {
798         string const arg = to_utf8(cmd.argument());
799         switch (cmd.action) {
800
801         case LFUN_MATH_MACRO_ADD_PARAM: 
802                 if (numargs_ < 9) {
803                         cur.recordUndoFullDocument();
804                         size_t pos = numargs_;
805                         if (arg.size() != 0)
806                                 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
807                         insertParameter(cur, pos);
808                 }
809                 break;
810
811
812         case LFUN_MATH_MACRO_REMOVE_PARAM: 
813                 if (numargs_ > 0) {
814                         cur.recordUndoFullDocument();
815                         size_t pos = numargs_ - 1;
816                         if (arg.size() != 0)
817                                 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
818                         removeParameter(cur, pos);
819                 }
820                 break;
821
822         case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
823                 if (numargs_ < 9) {
824                         cur.recordUndoFullDocument();
825                         insertParameter(cur, numargs_, true);
826                 }
827                 break;
828
829         case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
830                 if (numargs_ > 0) {
831                         cur.recordUndoFullDocument();
832                         removeParameter(cur, numargs_ - 1, true);
833                 }
834                 break;
835
836         case LFUN_MATH_MACRO_MAKE_OPTIONAL:
837                 cur.recordUndoFullDocument();
838                 makeOptional(cur);
839                 break;
840
841         case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
842                 cur.recordUndoFullDocument();
843                 makeNonOptional(cur);
844                 break;
845
846         case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
847                 if (numargs_ < 9) {
848                         cur.recordUndoFullDocument();
849                         insertParameter(cur, optionals_);
850                         makeOptional(cur);
851                 }
852                 break;
853
854         case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
855                 if (optionals_ > 0) {
856                         cur.recordUndoFullDocument();
857                         removeParameter(cur, optionals_ - 1);
858                 } break;
859
860         case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
861                 if (numargs_ == optionals_) {
862                         cur.recordUndoFullDocument();
863                         insertParameter(cur, 0, true);
864                         makeOptional(cur);
865                 }
866                 break;
867
868         default:
869                 InsetMathNest::doDispatch(cur, cmd);
870                 break;
871         }
872 }
873
874
875 bool MathMacroTemplate::getStatus(Cursor & /*cur*/, FuncRequest const & cmd,
876         FuncStatus & flag) const
877 {
878         bool ret = true;
879         string const arg = to_utf8(cmd.argument());
880         switch (cmd.action) {
881                 case LFUN_MATH_MACRO_ADD_PARAM: {
882                         int num = numargs_ + 1;
883                         if (arg.size() != 0)
884                                 num = convert<int>(arg);
885                         bool on = (num >= optionals_ 
886                                    && numargs_ < 9 && num <= numargs_ + 1);
887                         flag.enabled(on);
888                         break;
889                 }
890
891                 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
892                         flag.enabled(numargs_ < 9);
893                         break;
894
895                 case LFUN_MATH_MACRO_REMOVE_PARAM: {
896                         int num = numargs_;
897                         if (arg.size() != 0)
898                                 num = convert<int>(arg);
899                         flag.enabled(num >= 1 && num <= numargs_);
900                         break;
901                 }
902
903                 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
904                         flag.enabled(numargs_ > 0 
905                                      && optionals_ < numargs_ 
906                                      && type_ != MacroTypeDef);
907                         break;
908
909                 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
910                         flag.enabled(optionals_ > 0 
911                                      && type_ != MacroTypeDef);
912                         break;
913
914                 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
915                         flag.enabled(numargs_ < 9);
916                         break;
917
918                 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
919                         flag.enabled(optionals_ > 0);
920                         break;
921
922                 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
923                         flag.enabled(numargs_ == 0 
924                                      && type_ != MacroTypeDef);
925                         break;
926
927                 case LFUN_IN_MATHMACROTEMPLATE:
928                         flag.enabled();
929                         break;
930
931                 default:
932                         ret = false;
933                         break;
934         }
935         return ret;
936 }
937
938
939 void MathMacroTemplate::read(Buffer const &, Lexer & lex)
940 {
941         MathData ar;
942         mathed_parse_cell(ar, lex.getStream());
943         if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
944                 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
945                 lyxerr << "Read: " << to_utf8(asString(ar)) << endl;
946                 return;
947         }
948         operator=( *(ar[0]->asMacroTemplate()) );
949         
950         updateLook();
951 }
952
953
954 void MathMacroTemplate::write(Buffer const &, ostream & os) const
955 {
956         odocstringstream oss;
957         WriteStream wi(oss, false, false);
958         oss << "FormulaMacro\n";
959         write(wi);
960         os << to_utf8(oss.str());
961 }
962
963
964 void MathMacroTemplate::write(WriteStream & os) const
965 {
966         write(os, false);
967 }
968
969
970 void MathMacroTemplate::write(WriteStream & os, bool overwriteRedefinition) const
971 {
972         if (type_ == MacroTypeDef) {
973                 os << "\\def\\" << name().c_str();
974                 for (int i = 1; i <= numargs_; ++i)
975                         os << '#' << i;
976         } else {
977                 // newcommand or renewcommand
978                 if (redefinition_ && !overwriteRedefinition)
979                         os << "\\renewcommand";
980                 else
981                         os << "\\newcommand";
982                 os << "{\\" << name().c_str() << '}';
983                 if (numargs_ > 0)
984                         os << '[' << numargs_ << ']';
985                 
986                 // optional values
987                 if (os.latex()) {
988                         // in latex only one optional possible, simulate the others
989                         if (optionals_ >= 1) {
990                                 docstring optValue = asString(cell(optIdx(0)));
991                                 if (optValue.find(']') != docstring::npos)
992                                         os << "[{" << cell(optIdx(0)) << "}]";
993                                 else
994                                         os << "[" << cell(optIdx(0)) << "]";
995                         }
996                 } else {
997                         // in lyx we handle all optionals as real optionals
998                         for (int i = 0; i < optionals_; ++i) {
999                                 docstring optValue = asString(cell(optIdx(i)));
1000                                 if (optValue.find(']') != docstring::npos)
1001                                         os << "[{" << cell(optIdx(i)) << "}]";
1002                                 else
1003                                         os << "[" << cell(optIdx(i)) << "]";
1004                         }
1005                 }
1006         }
1007
1008         os << "{" << cell(defIdx()) << "}";
1009
1010         if (os.latex()) {
1011                 // writing .tex. done.
1012                 os << "\n";
1013         } else {
1014                 // writing .lyx, write special .tex export only if necessary
1015                 if (!cell(displayIdx()).empty())
1016                         os << "\n{" << cell(displayIdx()) << '}';
1017         }
1018 }
1019
1020
1021 int MathMacroTemplate::plaintext(Buffer const & buf, odocstream & os,
1022                                  OutputParams const &) const
1023 {
1024         static docstring const str = '[' + buf.B_("math macro") + ']';
1025
1026         os << str;
1027         return str.size();
1028 }
1029
1030
1031 bool MathMacroTemplate::validName() const
1032 {
1033         docstring n = name();
1034
1035         // empty name?
1036         if (n.size() == 0)
1037                 return false;
1038
1039         // converting back and force doesn't swallow anything?
1040         /*MathData ma;
1041         asArray(n, ma);
1042         if (asString(ma) != n)
1043                 return false;*/
1044
1045         // valid characters?
1046         for (size_t i = 0; i < n.size(); ++i) {
1047                 if (!(n[i] >= 'a' && n[i] <= 'z') &&
1048                                 !(n[i] >= 'A' && n[i] <= 'Z')) 
1049                         return false;
1050         }
1051
1052         return true;
1053 }
1054
1055
1056 bool MathMacroTemplate::validMacro() const
1057 {
1058         return validName();
1059 }
1060
1061
1062 bool MathMacroTemplate::fixNameAndCheckIfValid()
1063 {
1064         // check all the characters/insets in the name cell
1065         size_t i = 0;
1066         MathData & data = cell(0);
1067         while (i < data.size()) {
1068                 InsetMathChar const * cinset = data[i]->asCharInset();
1069                 if (cinset) {
1070                         // valid character in [a-zA-Z]?
1071                         char_type c = cinset->getChar();
1072                         if ((c >= 'a' && c <= 'z')
1073                             || (c >= 'A' && c <= 'Z')) {
1074                                 ++i;
1075                                 continue;
1076                         }
1077                 }
1078                 
1079                 // throw cell away
1080                 data.erase(i);
1081         }
1082
1083         // now it should be valid if anything in the name survived
1084         return data.size() > 0;
1085 }
1086
1087
1088 void MathMacroTemplate::getDefaults(vector<docstring> & defaults) const
1089 {
1090         defaults.resize(numargs_);
1091         for (int i = 0; i < optionals_; ++i)
1092                 defaults[i] = asString(cell(optIdx(i)));        
1093 }
1094
1095
1096 docstring MathMacroTemplate::definition() const
1097 {
1098         return asString(cell(defIdx()));
1099 }
1100
1101
1102 docstring MathMacroTemplate::displayDefinition() const
1103 {
1104         return asString(cell(displayIdx()));
1105 }
1106
1107
1108 size_t MathMacroTemplate::numArgs() const
1109 {
1110         return numargs_;
1111 }
1112
1113
1114 size_t MathMacroTemplate::numOptionals() const
1115 {
1116         return optionals_;
1117 }
1118
1119         
1120 void MathMacroTemplate::infoize(odocstream & os) const
1121 {
1122         os << "Math Macro: \\" << name();
1123 }
1124
1125 } // namespace lyx