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